spring容器创建对象的时间又两种情况:
情况一:当程序加载Spring 容器时就会调用默认的构造函数为bean创建对象
- 首先,我们创建一个类
public class HelloWorldScope {
public HelloWorldScope() {
System.out.println(“This is the Constructor!”);
}
public void hello() {
System.out.println(“Hello World!”);
}
}
2 . 配置spring容器
- 编写测试代码
/**
* 1.加载spring容器
* 2.spring容器调用默认的构造函数为bean创建对象
* 3.利用context.getBean把对象取出来
*
* 说明:该形式更加安全,如果spring的配置文件中有错误,
* 在启动spring容器的时候就会报错
*/
@Test
public void testScope_Lazy_init_false() {
ApplicationContext context = new ClassPathXmlApplicationContext(“applicationContext.xml”);
HelloWorldScope helloWorldScope = (HelloWorldScope) context.getBean(“helloWorldScope”);
HelloWorldScope helloWorldScope2 = (HelloWorldScope) context.getBean(“helloWorldScope”);
}
通过设置断点调试程序可知,当程序执行第一条语句加载spring容器:ApplicationContext context = …时,spring容器就会执行类中的构造函数为bean创建一个对象
情况二:当执行context.getBean时,spring容器为该bean创建对象
-
与情况一类相同
-
配置spring容器(与情况一种相比,增加了Lazy-init=“true”)
<bean id="helloWorldScope"
class="com.yangguang.spring.helloworld2.HelloWorldScope"
scope="prototype"
lazy-init="true">
</bean>
- 编写测试代码:(与情况一相同)
/**
* 1.启动spring容器
* 2.执行context.getBean
* 3.spring容器为该bean创建对象
*/
@Test
public void testScope_Lazy_init_true() {
ApplicationContext context = new ClassPathXmlApplicationContext(“applicationContext.xml”);
HelloWorldScope helloWorldScope = (HelloWorldScope) context.getBean(“helloWorldScope”);
HelloWorldScope helloWorldScope2 = (HelloWorldScope) context.getBean(“helloWorldScope”);
}
情况二中经过设置断点调试,发现程序先启动加载pring容器,然后调用context.getBean(),这时spring容器才为该bean创建对象
总结:推荐使用情况一种的这种方法。该形式更加安全,如果spring的配置文件中有错误,在启动spring容器的时候就会报错