我不懂春天的Autowired

时间:2015-08-13 21:15:29

标签: java spring javabeans autowired

的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,而不是两者都是!限定符注释不是用于绑定同一个类的特定bean吗?正确?

2)为什么要创建Bean B?我不会将其与@Autowired绑定。

如果我删除

 @Autowired 
 @Qualifier(value="a1")

来自BeanFactory,结果是一样的!这是不可能的......我不明白。也许编译器崩溃了?求救!

2 个答案:

答案 0 :(得分:2)

默认情况下,bean会被急切地初始化,这意味着容器"eagerly create and configure all singleton beans as part of the initialization process"。简单地说,无论是否进行任何自动装配或其他依赖注入,都会在启动时调用@PostConstruct方法。

如果您不需要,则需要设置:

lazy-init="true"

答案 1 :(得分:0)

默认情况下,热切地创建了Bean。如果您想延迟此操作,可以使用lazy-initialization