【问题标题】:I don't understand Autowired in Spring我不明白 Spring 中的 Autowired
【发布时间】: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,结果是一样的!这是不可能的..我不明白。也许编译器崩溃了?请帮忙!

【问题讨论】:

标签: java spring javabeans autowired


【解决方案1】:

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

如果你不想要,你需要设置:

lazy-init="true"

【讨论】:

    【解决方案2】:

    默认情况下,Bean 是急切创建的。如果你想推迟这个,你可以使用lazy-initialization

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 2021-05-13
      • 2011-02-17
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多