【spring框架】bean的生命周期

生命周期:
a)lazy-init(不重要)
指的是在容器进行初始化的时候它不进行初始化

ApplicationContext实现的默认行为就是在启动时将所有singleton bean提前进行实例化。提前实例化意味着作为初始化过程的一部分,ApplicationContext实例会创建并配置所有的singleton bean。通常情况下这是件好事,因为这样在配置中的任何错误就会即刻被发现(否则的话可能要花几个小时甚至几天)。

有时候这种默认处理可能并不是你想要的。如果你不想让一个singleton bean在ApplicationContext初始化时被提前实例化,那么可以将bean设置为延迟实例化。一个延迟初始化bean将告诉IoC 容器是在启动时还是在第一次被用到时实例化。

在XML配置文件中,延迟初始化将通过<bean/>元素中的lazy-init属性来进行控制。例如:
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
<bean name="not.lazy" class="com.foo.AnotherBean"/>

只有在你的应用频繁启动,而且每次启动的时候特别慢,就可以用这个。


b)init-method destroy-methd 不要和 prototype一起用(了解)
我们在UserService方法中添加init与destory方法:
package cn.edu.hpu.service;


import cn.edu.hpu.dao.UserDao;
import cn.edu.hpu.dao.Impl.UserDaoImpl;
import cn.edu.hpu.model.User;


public class UserService {


	private UserDao userDao;
	
	public void init(){
		System.out.println("init");
	}
	
	public UserDao getUserDao() {
		return userDao;
	}


	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}


	public void add(User u){
		this.userDao.save(u);
	}
	
	public void destroy(){
		System.out.println("destroy");
	}
	
}

在beans.xml中配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


  <bean id="u" class="cn.edu.hpu.dao.Impl.UserDaoImpl">
     <property name="daoId" value="1"></property>
  </bean>
	
  <bean id="userService" class="cn.edu.hpu.service.UserService" init-method="init" destroy-method="destroy">
  	 <property name="userDao" ref="u"></property>
  </bean>
  
</beans>
一旦我们的容器对这个bean进行初始化的时候会首先调用init-method属性指定的方法,容器关闭的时候会调用destroy-method属性指定的方法。


测试:
package cn.edu.hpu.service;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import cn.edu.hpu.dao.UserDao;
import cn.edu.hpu.model.User;


public class UserServiceTest {
	
	@Test
	public void testAdd() throws Exception{
		ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
		
		UserService userService=(UserService)ctx.getBean("userService");
		ctx.destroy();
	}
}
测试结果:
init
destroy
发现调用了初始化方法和结束方法。

注意:不要和scope="prototype" 一起用,会影响。具体为什么现在不必考虑。

转载请注明出处:http://blog.csdn.net/acmman

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值