美文网首页
Opptunity to create an object fo

Opptunity to create an object fo

作者: 薛云龙 | 来源:发表于2016-10-15 14:48 被阅读7次

单例模式下:
测试类

   public void test1(){
 //启动spring容器 
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); 
//在这里输出一句话,这里刚刚好启动了spring容器 
System.out.println("invoke!!!!"); 
//得到helloSpring对象 
helloSpring helloSpring=(helloSpring) applicationContext.getBean("hello"); 
//调用相应的方法 helloSpring.hello(); }

如此,输出结果为:
new instance
invoke!!!
hello spring!
所以,spring默认创建对象是在启动spring的时候。

当然,我们还可以调用这个对象的时候,才创建这个对象:
添加一个属性: lazy-init 该属性的默认值为default。相当于false。

<bean class="cn.ansel.domain.helloSpring" id="hello" lazy-init="true"></bean>

spring创建对象的时机的意义:
当我们使用ssh整合的时候,tomcat启动时就创建配置文件中的所有bean对象的,如果有某些类或者配置文件的书写有误,这时候,spring容器就会报错,那么自然spring容器也就启动不起来了。这种情况可以避免,我们到了后面真正要调用该类的时候才报错。当然这种做法,会把一些类过早的加载到内存中。 当我们选择在调用某个类的时候,spring容器才帮我们创建这个类,首先我们可以解决第一种情况出现的问题,节省了内存但是这时候,类和配置文件中许多隐藏的错误,在调用的时候才发现,这时候添加了查错的压力。

相关文章

网友评论

      本文标题:Opptunity to create an object fo

      本文链接:https://www.haomeiwen.com/subject/jtznyttx.html