1.lazy-init:延迟加载 ,提高效率
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
延迟加载 要是没有这个属性,那么在new出ClassPathXmlApplicationContext时候就会加载,加上lazy-init 后就可以在用到的时候再加载
也可以用这种方式:
<beans default-lazy-init="true">
<!-- no beans will be pre-instantiated... -->
</beans>
表示所有的bean都是lazy-init;
2.生命周期
<bean id="userservice" class="org.sh.spring.Services.UserServices" init-method="init" destroy-method="destory" autowire="byName"><!--
<constructor-arg>
<ref bean="u"/>
</constructor-arg>
-->
<!--<property name="impl" ref="u"></property>-->
</bean>
添加init和destory方法
package org.sh.spring.Services;
import org.sh.spring.DAO.IUserDAO;
import org.sh.spring.model.User;
public class UserServices implements IUserDAO {
private IUserDAO impl;
public void init() {
System.out.println("init******");
}
public IUserDAO getImpl() {
return impl;
}
public void setImpl(IUserDAO impl) {
this.impl = impl;
}
public UserServices() {
System.out.println("**********这里");
}
@Override
public void save(User user) {
impl.save(user);
}
public void destory() {
System.out.println("destory******");
}
}
测试:
public void testSave() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserServices ud = (UserServices)ctx.getBean("userservice");
//System.out.println(ud.getImpl());
ctx.destroy();
}
结果:
init******
2014-4-16 21:48:33 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@1d225a7: display name [org.springframework.context.support.ClassPathXmlApplicationContext@1d225a7]; startup date [Wed Apr 16 21:48:33 CST 2014]; root of context hierarchy
2014-4-16 21:48:33 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@69d02b: defining beans [impl,u2,userservice]; root of factory hierarchy
destory******
从结果中可以看出 只调用inint和destory一次
将UserSdervices 实例化两次 再进行测试:
public void testSave() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserServices ud = (UserServices)ctx.getBean("userservice");
UserServices ud1 = (UserServices)ctx.getBean("userservice");
//System.out.println(ud.getImpl());
ctx.destroy();
}
如果把scope改为prototype
<bean id="userservice" class="org.sh.spring.Services.UserServices" init-method="init" destroy-method="destory" autowire="byName" scope="prototype">
测试结果:
init******
讲UserServices实例化两次
结果:
**********这里
init******
**********这里
init******
可以看出当scope属性为prototype时 不会调用destory方法,每次实例化都会调用init,prototype不会干预生命周期的,所以最好不和prototype一起用