方法一:
1 初始化bean
a 使用bean的init-method属性调用相应的方法初始化
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {
public void init() {
// do some initialization work
}
}
b 使用org.springframework.beans.factory.InitializingBean接口的void afterPropertiesSet() throws Exception;方法初始化
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
2 销毁bean
a 使用bean的destroy-method属性调用相应的方法销毁
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {
public void cleanup() {
// do some destruction work (like releasing pooled connections)
}
}
b 使用org.springframework.beans.factory.DisposableBean接口的void destroy() throws Exception;方法销毁
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements DisposableBean {
public void destroy() {
// do some destruction work (like releasing pooled connections)
}
}
说明:使用bean的属性调用方法的时候将增加代码的耦合度
方法二:
使用beans的default-init-method(default-destroymethod)属性回调创建(销毁)bean的方法。当创建一个新的bean的时候,IOC容器就会在适当的时候调用init方法
public class DefaultBlogService implements BlogService {
private BlogDao blogDao;
public void setBlogDao(BlogDao blogDao) {
this.blogDao = blogDao;
}
// this is (unsurprisingly) the initialization callback method
public void init() {
if (this.blogDao == null) {
throw new IllegalStateException("The [blogDao] property must be set.");
}
}
}
<beans default-init-method="init">
<bean id="blogService" class="com.foo.DefaultBlogService">
<property name="blogDao" ref="blogDao" />
</bean>
</beans>
方法三:
使用注解的方式@PostConstruct and @PreDestroy
特别说明:当以上三种方法在同一个bean中都配置后,三种初始化(销毁)方法都会执行。其中执行顺序是首先是注解方式,然后是实现接口方式,最后是在beans中配置的。