1.Spring的延迟初始化bean(用处不大,应用频繁启动时可以使用) ApplicationContext实现的默认行为就是在启动时将所有singleton bean提前进行实例化。提前实例化意味着作为初始化过程的一部分,ApplicationContext实例会创建并配置所有的singleton bean。通常情况下这是件好事,因为这样在配置中的任何错误就会即刻被发现(否则的话可能要花几个小时甚至几天)。
有时候这种默认处理可能并不是你想要的。如果你不想让一个singleton bean在ApplicationContext初始化时被提前实例化,那么可以将bean设置为延迟实例化。一个延迟初始化bean将告诉IoC 容器是在启动时还是在第一次被用到时实例化。
在XML配置文件中,延迟初始化将通过元素中的lazy-init属性来进行控制。例如:
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/> <bean name="not.lazy" class="com.foo.AnotherBean"/>当ApplicationContext实现加载上述配置时,设置为lazy的bean将不会在ApplicationContext启动时提前被实例化,而not.lazy却会被提前实例化。
需要说明的是,如果一个bean被设置为延迟初始化,而另一个非延迟初始化的singleton bean依赖于它,那么当ApplicationContext提前实例化singleton bean时,它必须也确保所有上述singleton 依赖bean也被预先初始化,当然也包括设置为延迟实例化的bean。因此,如果Ioc容器在启动的时候创建了那些设置为延迟实例化的bean的实例,你也不要觉得奇怪,因为那些延迟初始化的bean可能在配置的某个地方被注入到了一个非延迟初始化singleton bean里面。
在容器层次上通过在元素上使用’default-lazy-init’属性来控制延迟初始化也是可能的。如下面的配置:
<beans default-lazy-init="true"> <!-- no beans will be pre-instantiated... --> </beans>2.Spring的生命周期
容器初始化时调用init,关闭时调用destroy。
<bean id="userService" class="com.service.UserService" autowire="byType" init-method="init" destroy-method="destroy"> </bean>在web环境中会自动调用destroy。但ApplicationContext类中是没有这个方法的,用ClassPathXmlApplicationContext 手动调用destroy方法。
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); UserService service = (UserService) ctx.getBean("userService"); ctx.destroy();init-method和destroy-method不要和scope=“prototype”一起用。
UserService service = (UserService) ctx.getBean("userService"); UserService service2 = (UserService) ctx.getBean("userService");虽然会声明两个对象,但控制台只输出两个init。
数据源连接池在XML配置时经常指定destroy-method(通过property节点进行简单属性注入),保证不用时所有连接关闭。