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 bean 相同)
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 中指定,而不是两者!限定符注释不是用来绑定(bind)同一类的特定bean吗?对吗?
2) 为什么要创建Bean B?我不将它与@Autowired 绑定(bind)。
如果我删除
@Autowired
@Qualifier(value="a1")
来自BeanFactory,结果是一样的!这不可能。。我不明白。也许编译器崩溃了?请帮忙!
最佳答案
默认情况下,bean 会立即初始化,这意味着容器 "eagerly create and configure all singleton beans as part of the initialization process" 。简单地说,无论是否有任何 Autowiring 或其他依赖项注入(inject),@PostConstruct 方法都会在启动时调用。
如果您想要其他方式,您需要设置:
lazy-init="true"
关于java - 我不明白 Spring 中的 Autowired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31998565/