几种自定义Spring生命周期的初始化和销毁方法

Bean 的生命周期指的是 Bean 的创建、初始化、销毁的过程。Spring 提供了一些方法,可以让开发自定义实现在生命周期过程中执行一些额外操作。 1、在注解 @Bean 中指定初始化和销毁时执行的方法...

Bean 的生命周期指的是 Bean 的创建、初始化、销毁的过程。Spring 提供了一些方法,可以让开发自定义实现在生命周期过程中执行一些额外操作。

1、在注解 @Bean 中指定初始化和销毁时执行的方法名。

@Component
public class Cat {
  public Cat() {
    System.out.println("new Cat()");
  }
  void initMethod() {
    System.out.println("调用init初始化***** initMethod");
  }
  void destroyMethod() {
    System.out.println("调用destroy销毁***** destroyMethod");
  }
}
@Component
public class LifeCylceConfig {
  @Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
  Cat cat() {
    return new Cat();
  }
}

2、实现初始化和销毁接口 InitializingBean、DisposableBean

@Component
public class Cat implements InitializingBean, DisposableBean {
  @Override
  public void afterPropertiesSet() throws Exception {
    System.out.println("调用初始化----- afterPropertiesSet");
  }
  @Override
  public void destroy() throws Exception {
    System.out.println("调用销毁----- destroy");
  }
}

3、使用注解 @PostConstruct、@PreDestroy 标注初始化和销毁时需要执行的方法。

@Component
public class Cat {
  @PostConstruct
  void postConstruct() {
    System.out.println("调用注解的初始化===== postConstruct");
  }
  @PreDestroy
  void preDestroy() {
    System.out.println("调用注解的销毁===== destroy");
  }
}

4、实现接口 BeanPostProcessor,来在 Bean 初始化完成前后执行操作。

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("调用实例化前的后置处理器###### postProcessBeforeInitialization:"+beanName);
    return bean;
  }
  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("调用实例化后的后置处理器###### postProcessAfterInitialization:"+beanName);
    return bean;
  }
}

需要注意的是BeanPostProcessor.postProcessAfterInitialization()并非关闭容器时才执行的销毁方法,它在完成初始化 Bean 之后就会执行。

上面4种方式在启动容器和关闭容器时的执行顺序如下

  1. 初始化构造器 new Cat()
  2. BeanPostProcessor.postProcessBeforeInitialization()
  3. @PostConstruct
  4. InitializingBean.afterPropertiesSet()
  5. initMethod()
  6. BeanPostProcessor.postProcessAfterInitialization()
    =====================开始关闭容器=====================
  7. @PreDestroy
  8. DisposableBean.destroy()
  9. destroyMethod()
  • 发表于 2019-08-04 12:20
  • 阅读 ( 248 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除