spring容器對bean的生命週期管理主要在兩個時間點:bean的初始化完成(包括屬性值被徹底注入),bean的銷燬(程序結束,或者引用結束)
方式一:使用springXML配置中的init-method="init" destroy-method="destory" 這個兩個配置,能夠實現兩個時間點插入定製的操做。
方式二: 使用spring提供的2個接口:InitializingBean,DisposableBean
方式三:使用java註解:@PostConstruct @PreDestroy
三種方式執行的優先順序是:註解>接口>XML配置
具體代碼以下:
UserDao.javajava
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配置:spring
<bean name="userDao" class="com.xxw.dao.UserDao" init-method="init" destroy-method="destory"> <property name="name" value="Jame"/> </bean>
測試代碼app
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測試