【发布时间】:2015-08-13 21:15:29
【问题描述】:
ApplicationContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean id="beanFactory" class="testSpring.BeanFactory" />
<bean id="a1" class="testSpring.A">
<property name="name" value="I am A one!"></property>
</bean>
<bean id="a2" class="testSpring.A">
<property name="name" value="I am A two!"></property>
</bean>
<bean id="b" class="testSpring.B">
<property name="name" value="I am B!"></property>
</bean>
</beans>
主要
public class Main
{
public static void main( String[] args )
{
System.out.println("Avvio applicazione: Main invocato");
AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"ApplicationContext.xml");
BeanFactory ai = applicationContext.getBean("beanFactory", BeanFactory.class);
}
}
A (B 豆也一样)
public class A {
private String name;
public A(){
}
@SuppressWarnings("restriction")
@PostConstruct
public void init(){
System.out.println("Bean A created, name: " + name);
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
}
BeanFactory
public class BeanFactory {
@Autowired
@Qualifier(value="a1")
private A a;
public void setA(A a){
this.a = a;
}
public void printAName(){
System.out.println("Classe AInstantiator: AInstantiator.printAName -> a.getName() = " + a.getName());
}
}
这是运行的结果:
Avvio applicazione: Main invocato
Bean A created, name: I am A one!
Bean A created, nome: I am A two!
Bean B created, name: I am B!
这怎么可能?!
1) 为什么创建二?我在@Qualifier a1 bean 中指定,而不是两者都指定!限定符注释不用于绑定同一类的特定bean?对吧?
2) 为什么要创建 Bean B?我没有将它与@Autowired 绑定。
如果我删除
@Autowired
@Qualifier(value="a1")
来自BeanFactory,结果是一样的!这是不可能的..我不明白。也许编译器崩溃了?请帮忙!
【问题讨论】:
-
听起来像你想要的Lazy-initialized beans。
-
@BeauGrantham 是正确的。
标签: java spring javabeans autowired