如何控制Spring bean的生命周期

先了解下Spring bean的生命周期:创建 ------ 初始化 ------ 销毁,这对读懂Spring源码十分有帮助。

控制Spring bean的生命周期有3种方式,下面分别用代码展示

  • 方式一:@Bean 注解上手动指定bean的初始化方法和销毁方法
@Configuration
@ComponentScan("org.xiaobuisme.example.cap7")
public class Cap7MainConfig {

    /**
     * 方式一:在@Bean 注解上手动指定初始化方法和销毁方法
     *
     * @return
     */
    @Bean(initMethod = "init", destroyMethod = "destroy")
    public Bike bike() {
        return new Bike();
    }
}

public class Bike {
    public Bike() {
        System.out.println("bike constructor.......");
    }

    public void init() {
        System.out.println("bike init ........");
    }

    public void destroy() {
        System.out.println("bike destroy........");
    }
}
  • 方式二:让bean类实现Spring的InitializingBean接口和DisposableBean接口
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * 方式二:实现spring的 spring的InitializingBean 和 DisposableBean
 */
@Component
public class Train implements InitializingBean, DisposableBean {
    public Train() {
        System.out.println("Train....constructor........");
    }

    // 在容器关闭时使用
    @Override
    public void destroy() throws Exception {
        System.out.println("train......destroy......");
    }

    // 在容器创建时使用
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("train....afterPropertiesSet.......");
    }
}
  • 方式三:使用JSR250规则定义的规范的两个注解实现@PostConstruct 和 @PreDestroy
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 方式三:使用java规范的注解 @PostConstruct 和 @PreDestroy
 */
@Component
public class Jeep {
    public Jeep() {
        System.out.println("Jeep....constructor.....");
    }

    @PostConstruct
    public void init() {
        System.out.println("Jeep.....init.......");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("Jeep.....destroy......");
    }
}
  • 方式四:使用后置处理器 BeanPostProcessor 在初始化前后做一些事
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 后置处理器:初始化前后处理工作
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization ......" + beanName + "------>" + bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization ......" + beanName + "------>" + bean);
        return bean;
    }
}

验证打印一下


import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.xiaobuisme.example.cap7.Cap7MainConfig;

/**
 * Spring的生命周期
 */
public class Cap7Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext anno = new AnnotationConfigApplicationContext(Cap7MainConfig.class);
        System.out.println("容器创建完成.........");
        /**
         * 执行如下语句:
         * bike constructor.......
         * bike init ........
         * 容器创建完成.........
         */
        
        anno.close();
        /**
         * 执行如下语句:
         * bike destroy........
         */
    }
}

打印结果如下: 

postProcessBeforeInitialization ......org.springframework.context.event.internalEventListenerProcessor------>org.springframework.context.event.EventListenerMethodProcessor@71248c21
postProcessAfterInitialization ......org.springframework.context.event.internalEventListenerProcessor------>org.springframework.context.event.EventListenerMethodProcessor@71248c21
postProcessBeforeInitialization ......org.springframework.context.event.internalEventListenerFactory------>org.springframework.context.event.DefaultEventListenerFactory@6166e06f
postProcessAfterInitialization ......org.springframework.context.event.internalEventListenerFactory------>org.springframework.context.event.DefaultEventListenerFactory@6166e06f
postProcessBeforeInitialization ......cap7MainConfig------>org.xiaobuisme.example.cap7.Cap7MainConfig$$EnhancerBySpringCGLIB$$a256f7f7@49e202ad
postProcessAfterInitialization ......cap7MainConfig------>org.xiaobuisme.example.cap7.Cap7MainConfig$$EnhancerBySpringCGLIB$$a256f7f7@49e202ad
Jeep....constructor.....
postProcessBeforeInitialization ......jeep------>org.xiaobuisme.example.cap7.Jeep@6e38921c
Jeep.....init.......
postProcessAfterInitialization ......jeep------>org.xiaobuisme.example.cap7.Jeep@6e38921c
Train....constructor........
postProcessBeforeInitialization ......train------>org.xiaobuisme.example.cap7.Train@49070868
train....afterPropertiesSet.......
postProcessAfterInitialization ......train------>org.xiaobuisme.example.cap7.Train@49070868
bike constructor.......
postProcessBeforeInitialization ......bike------>org.xiaobuisme.example.cap7.Bike@58134517
bike init ........
postProcessAfterInitialization ......bike------>org.xiaobuisme.example.cap7.Bike@58134517
容器创建完成.........
bike destroy........
train......destroy......
Jeep.....destroy......

你可能感兴趣的:(spring,java)