单例bean什么时候初始化?

当bean被设置为单例非懒加载时,在spring容器创建时就已经初始化

例如

public class TestService{

    public TestService(){
        super();
        System.out.println("-----------------testService创建完成-----------------------");
    }
}
<bean id="testService" class="com.bjsxt.test1.TestService"></bean>
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
System.out.println("-------------------开始获取testService-----------------------------");
Object testA = applicationContext.getBean("testService");

输出

-----------------testService创建完成-----------------------
-------------------开始获取testService-----------------------------
com.bjsxt.test1.TestService@4439f31e

当bean被设置为单例懒加载时,在第一次访问的时候初始化(如果该Bean被其他需要实例化的Bean引用到,Spring也会忽略延迟实例化的设置)

例如

public class TestController {
    private TestService testService;

    public TestService getTestService() {
        return testService;
    }

    public void setTestService(TestService testService) {
        this.testService = testService;
    }
}
public class TestService{

    public TestService(){
        super();
        System.out.println("-----------------testService创建完成-----------------------");
    }
}
<bean id="testController" class="com.bjsxt.test1.TestController"></bean>
<bean id="testService" class="com.bjsxt.test1.TestService" lazy-init="true"></bean>
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
System.out.println("-------------------开始获取testService-----------------------------");
Object testA = applicationContext.getBean("testService");
System.out.println(testA);

输出

-----------------testService创建完成-----------------------
-------------------开始获取testService-----------------------------
com.bjsxt.test1.TestService@1b604f19
本人工作时间不长,如果有写的不对的地方,欢迎批评。

你可能感兴趣的:(bean初始化)