项目启动过程中,利用spring框架,进行初始化
Spring容器会做出如下保证,bean会在装载了所有的依赖以后,立刻就开始执行初始化回调。这样的话,初始化回调只会在直接的bean引用装载好后调用, 而此时AOP拦截器还没有应用到bean上。
首先,目标的bean会先完全初始化,
初始化执行时机
然后,AOP代理和拦截链才能应用。

如果目标bean和代理是分开定义的,那么开发者的代码甚至可以跳过AOP而直接和引用的bean交互

一、实现框架接口

实现InitializingBeanDisposableBean接口,让容器里管理Bean的生命周期。容器会在调用afterPropertiesSet() 之后和destroy()之前会允许bean在初始化销毁bean时执行某些操作

缺点:依赖于框架具体接口

初始化方法回调

初始化时执行
org.springframework.beans.factory.InitializingBean接口允许bean在所有的必要的依赖配置完成后执行bean的初始化, InitializingBean 接口中指定使用如下方法:

  1. void afterPropertiesSet() throws Exception;
  2. <bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
  3. public class AnotherExampleBean implements InitializingBean {
  4. public void afterPropertiesSet() {
  5. // do some initialization work
  6. }
  7. }

销毁方法回调

实现org.springframework.beans.factory.DisposableBean接口的Bean就能让容器通过回调来销毁bean所引用的资源。 DisposableBean 接口指定一个方法

  1. void destroy() throws Exception;
  2. <bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
  3. public class AnotherExampleBean implements DisposableBean {
  4. public void destroy() {
  5. // do some destruction work (like releasing pooled connections)
  6. }
  7. }

二、注解方式

初始化前执行
使用JSR-250 @PostConstruct@PreDestroy注解
此种方式通常被认为是在现代Spring应用程序中接收生命周期回调的最佳实践。 使用这些注解意味着您的bean不会耦合到特定于Spring的接口

  1. public class CachingMovieLister {
  2. @PostConstruct
  3. public void populateMovieCache() {
  4. // populates the movie cache upon initialization...
  5. }
  6. @PreDestroy
  7. public void clearMovieCache() {
  8. // clears the movie cache upon destruction...
  9. }
  10. }

三、XML配置方法

如果不想使用注解,同时,还想解除与框架具体接口的依赖。
使用init-methoddestroy-method定义对象元数据。

初始化

  1. <bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
  2. public class ExampleBean {
  3. public void init() {
  4. // do some initialization work
  5. }
  6. }

销毁方法

  1. <bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
  2. public class ExampleBean {
  3. public void cleanup() {
  4. // do some destruction work (like releasing pooled connections)
  5. }
  6. }

全局配置初始化方法

延伸了解。如果项目中,所有初始化方法,都使用init,则可以按照下面进行配置。

  1. <beans default-init-method="init">
  2. <bean id="blogService" class="com.something.DefaultBlogService">
  3. <property name="blogDao" ref="blogDao" />
  4. </bean>
  5. </beans>

四、混合使用调用顺序

为同一个bean配置的多个生命周期机制具有不同的初始化方法,如下所示:

  1. 1. 包含@PostConstruct注解的方法
  2. 2. InitializingBean 接口中的afterPropertiesSet() 方法
  3. 3. 自定义的init() 方法

Destroy方法以相同的顺序调用:

  1. 1. 包含@PreDestroy注解的方法
  2. 2. DisposableBean接口中的destroy() 方法
  3. 3. 自定义的destroy() 方法