【发布时间】:2019-01-15 20:08:03
【问题描述】:
我正在尝试从 Pro Spring 5 Book 中学习 Spring。
这是一个我不理解的自动装配示例:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="fooOne" class="com.apress.prospring5.ch3.xml.Foo"/>
<bean id="barOne" class="com.apress.prospring5.ch3.xml.Bar"/>
<bean id="targetByName" autowire="byName" class="com.apress.prospring5.ch3.xml.Target"
lazy-init="true"/>
<bean id="targetByType" autowire="byType" class="com.apress.prospring5.ch3.xml.Target"
lazy-init="true"/>
<bean id="targetConstructor" autowire="constructor"
class="com.apress.prospring5.ch3.xml.Target" lazy-init="true"/>
</beans>
Tarjet 类
package com.apress.prospring5.ch3.xml;
import org.springframework.context.support.GenericXmlApplicationContext;
public class Target {
private Foo fooOne;
private Foo fooTwo;
private Bar bar;
public Target() {
}
public Target(Foo foo) {
System.out.println("Target(Foo) called");
}
public Target(Foo foo, Bar bar) {
System.out.println("Target(Foo, Bar) called");
}
public void setFooOne(Foo fooOne) {
this.fooOne = fooOne;
System.out.println("Property fooOne set");
}
public void setFooTwo(Foo foo) {
this.fooTwo = foo;
System.out.println("Property fooTwo set");
}
public void setBar(Bar bar) {
this.bar = bar;
System.out.println("Property bar set");
}
public static void main(String... args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:spring/app-context-03.xml");
ctx.refresh();
Target t = null;
System.out.println("Using byName:\n");
t = (Target) ctx.getBean("targetByName");
System.out.println("\nUsing byType:\n");
t = (Target) ctx.getBean("targetByType");
System.out.println("\nUsing constructor:\n");
t = (Target) ctx.getBean("targetConstructor");
ctx.close();
}
}
Foo 类
package com.apress.prospring5.ch3.xml;
public class Foo {
}
酒吧类
package com.apress.prospring5.ch3.xml;
public class Bar {
}
我不明白的:
<bean id="targetByName" autowire="byName" class="com.apress.prospring5.ch3.xml.Target"
lazy-init="true"/>
知道我们没有在 bean 定义中使用任何属性或构造函数注入,如何注入 Target 属性 (fooOne,fooTwo,bar)?
通常我们应该有类似的东西:
<property name = "fooOne">
<bean id = "fooOne" class = "com.apress.prospring5.ch3.xml.Foo"/>
</property>
【问题讨论】:
-
“财产注入”到底是什么意思?这不是通常使用的术语。
-
我的意思是使用setter方法。
标签: java spring dependency-injection autowired