本文來介紹下InitializingBean接口和DisposableBean接口的作用
文章目錄
1.InitializingBean
2.DisposableBean
3.案例示範
1.InitializingBean
該接口的作用是:允許一個bean在它的所有必須屬性被BeanFactory設定後,來執行初始化的工作,該接口中隻有一個方法,afterPropertiesSet
public interface InitializingBean {
/**
* Invoked by the containing {@code BeanFactory} after it has set all bean properties
* and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
* <p>This method allows the bean instance to perform validation of its overall
* configuration and final initialization when all bean properties have been set.
* @throws Exception in the event of misconfiguration (such as failure to set an
* essential property) or if initialization fails for any other reason
*/
void afterPropertiesSet() throws Exception;
}
2.DisposableBean
該接口的作用是:允許在容器銷毀該bean的時候獲得一次回調。DisposableBean接口也隻規定了一個方法:destroy
public interface DisposableBean {
/**
* Invoked by the containing {@code BeanFactory} on destruction of a bean.
* @throws Exception in case of shutdown errors. Exceptions will get logged
* but not rethrown to allow other beans to release their resources as well.
*/
void destroy() throws Exception;
}
3.案例示範
/**
* 實作InitializingBean和DisposableBean接口
* @author dengp
*
*/
public class User implements InitializingBean,DisposableBean{
private int id;
private String name;
private String beanName;
public User(){
System.out.println("User 被執行個體化");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("設定:"+name);
this.name = name;
}
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", beanName=" + beanName + "]";
}
@Override
public void destroy() throws Exception {
// TODO Auto-generated method stub
System.out.println("destory ....");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet....");
}
}
配置檔案
<?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.xsd">
<bean class="com.dpb.pojo.User" id="user" >
<property name="name" value="波波烤鴨"></property>
</bean>
</beans>
測試代碼
@Test
public void test1() {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = ac.getBean(User.class);
System.out.println(user);
ac.registerShutdownHook();
}
輸出結果:
User 被執行個體化
設定:波波烤鴨
afterPropertiesSet....
User [id=0, name=波波烤鴨, beanName=null]
destory ....
通過輸出能夠顯示spring初始化bean的時候,如果bean實作了InitializingBean接口,會自動調用afterPropertiesSet方法,在bean被銷毀的時候如果實作了DisposableBean接口會自動回調destroy方法後然後再銷毀