项目启动过程中,利用spring框架,进行初始化
Spring容器会做出如下保证,bean会在装载了所有的依赖以后,立刻就开始执行初始化回调。这样的话,初始化回调只会在直接的bean引用装载好后调用, 而此时AOP拦截器还没有应用到bean上。
首先,目标的bean会先完全初始化,
初始化执行时机
然后,AOP代理和拦截链才能应用。
如果目标bean和代理是分开定义的,那么开发者的代码甚至可以跳过AOP而直接和引用的bean交互
一、实现框架接口
实现InitializingBean
和 DisposableBean
接口,让容器里管理Bean的生命周期。容器会在调用afterPropertiesSet()
之后和destroy()
之前会允许bean在初始化和销毁bean时执行某些操作
缺点:依赖于框架具体接口
初始化方法回调
(初始化时执行)
org.springframework.beans.factory.InitializingBean接口允许bean在所有的必要的依赖配置完成后执行bean的初始化, InitializingBean 接口中指定使用如下方法:
void afterPropertiesSet() throws Exception;
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
销毁方法回调
实现org.springframework.beans.factory.DisposableBean接口的Bean就能让容器通过回调来销毁bean所引用的资源。 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)
}
}
二、注解方式
(初始化前执行)
使用JSR-250 @PostConstruct
和 @PreDestroy
注解
此种方式通常被认为是在现代Spring应用程序中接收生命周期回调的最佳实践。 使用这些注解意味着您的bean不会耦合到特定于Spring的接口。
public class CachingMovieLister {
@PostConstruct
public void populateMovieCache() {
// populates the movie cache upon initialization...
}
@PreDestroy
public void clearMovieCache() {
// clears the movie cache upon destruction...
}
}
三、XML配置方法
如果不想使用注解,同时,还想解除与框架具体接口的依赖。
使用init-method
和 destroy-method
定义对象元数据。
初始化
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {
public void init() {
// do some initialization work
}
}
销毁方法
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {
public void cleanup() {
// do some destruction work (like releasing pooled connections)
}
}
全局配置初始化方法
延伸了解。如果项目中,所有初始化方法,都使用init,则可以按照下面进行配置。
<beans default-init-method="init">
<bean id="blogService" class="com.something.DefaultBlogService">
<property name="blogDao" ref="blogDao" />
</bean>
</beans>
四、混合使用调用顺序
为同一个bean配置的多个生命周期机制具有不同的初始化方法,如下所示:
1. 包含@PostConstruct注解的方法
2. 在InitializingBean 接口中的afterPropertiesSet() 方法
3. 自定义的init() 方法
Destroy方法以相同的顺序调用:
1. 包含@PreDestroy注解的方法
2. 在DisposableBean接口中的destroy() 方法
3. 自定义的destroy() 方法