spring容器对bean的生命周期管理主要在两个时间点:bean的初始化完成(包括属性值被完全注入),bean的销毁(程序结束,或者引用结束)
方式一:使用springXML配置中的init-method="init"
destroy-method="destory" 这个两个配置,可以实现两个时间点插入定制的操作。
方式二:
使用spring提供的2个接口:InitializingBean,DisposableBean
方式三:使用java注解:@PostConstruct
@PreDestroy
三种方式执行的优先顺序是:注解>接口>XML配置
具体代码如下:
UserDao.java
1 import javax.annotation.PostConstruct; 2 import javax.annotation.PreDestroy; 3 4 import org.springframework.beans.factory.DisposableBean; 5 import org.springframework.beans.factory.InitializingBean; 6 /** 7 * 〈一句话功能简述〉<br> 8 * 〈功能详细描述〉 9 * 10 * @author xxw 11 * @see [相关类/方法](可选) 12 * @since [产品/模块版本] (可选) 13 */ 14 public class UserDao implements InitializingBean,DisposableBean{ 15 16 private String name; 17 //xml配置 18 public void init(){ 19 System.out.println("userDao init name =="+this.name); 20 } 21 //xml配置 22 public void destory(){ 23 System.out.println("userDao destory name =="+this.name); 24 } 25 //注解 26 @PostConstruct 27 public void test(){ 28 System.out.println("this is PostConstruct name =="+this.name); 29 } 30 //注解 31 @PreDestroy 32 public void dtest(){ 33 System.out.println("this is PreDestroy name=="+this.name); 34 } 35 36 //接口实现 37 /* (non-Javadoc) 38 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() 39 */ 40 public void afterPropertiesSet() throws Exception { 41 42 System.out.println("this is afterPropertiesSet name =="+this.name); 43 } 44 //接口实现 45 /* (non-Javadoc) 46 * @see org.springframework.beans.factory.DisposableBean#destroy() 47 */ 48 public void destroy() throws Exception { 49 System.out.println("this DisposableBean destroy"); 50 } 51 /** 52 * @return the name 53 */ 54 public String getName() { 55 return name; 56 } 57 /** 58 * @param name the name to set 59 */ 60 public void setName(String name) { 61 this.name = name; 62 } 63 }
xml配置:
<bean name="userDao" class="com.xxw.dao.UserDao" init-method="init" destroy-method="destory"> <property name="name" value="Jame"/> </bean>
测试代码
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @ContextConfiguration(locations = "classpath:applicationContext.xml") 3 public class UserDaoTest extends AbstractJUnit4SpringContextTests { 4 @Autowired 5 private UserDao userDao; 6 @Test 7 public void getUser2(){ 8 System.out.println("do nothing"); 9 } 10 }
输出结果:
this is PostConstruct name
==Jame//注解
this is
afterPropertiesSet name ==Jame//接口
userDao
init name ==Jame//xml配置
do
nothing
this is
PreDestroy name==Jame
this
DisposableBean destroy
userDao
destory name ==Jame