zoukankan      html  css  js  c++  java
  • 几种自定义Spring生命周期的初始化和销毁方法

    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()
  • 相关阅读:
    IO多路复用
    Elasticsearch之打分机制、集群搭建、脑裂问题
    Elasticsearch之-映射管理,ik分词器
    Elasticsearch之高亮查询,聚合查询
    Elasticsearch之索引、文档、组合查询、排序查询、filter过滤操作
    Go 数组、切片、Maps
    Go if-else语句、for循环、switch语句
    Go 函数、包、mode模式
    毕业设计-1.05
    毕业设计-1.04
  • 原文地址:https://www.cnblogs.com/bigshark/p/11296917.html
Copyright © 2011-2022 走看看