Spring Bean 生命周期顺序验证

看到一篇写的很好的 Spring Bean 生命周期的博客:一文读懂 Spring Bean 的生命周期,在此写个简单的 Bean 进行验证。

1. 创建Springboot项目

基于 springboot 的2.1.8.RELEASE 创建一个简单项目,只添加 spring-aop 包以引入spring依赖。


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.8.RELEASEversion>
        <relativePath/>
    parent>

    <groupId>com.xxx.springtestgroupId>
    <artifactId>sprint-testartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
    properties>

    <dependencies>
    	
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-aopartifactId>
        dependency>
    dependencies>

project>

2. 定义 TestBean

我们定义一个名为类型为TestBean,名为testBean的测试 bean。

package com.xxx.springtest.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringValueResolver;

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

/**
 * 测试验证 bean,实现了各个 *Aware 接口和 InitializingBean#afterPropertiesSet、DisposableBean#destroy 接口,
 * 此外,除添加了由 @PostConstruct 和 @PreDestroy 注解标注的方法外,
 * 还添加了自定义初始化 init()方法(该方法名在用 @Bean 声明 testBean 时设置)。
 */
public class TestBean implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, EnvironmentAware,
        EmbeddedValueResolverAware, ResourceLoaderAware, ApplicationEventPublisherAware, MessageSourceAware,
        ApplicationContextAware, InitializingBean, DisposableBean {

	public TestBean() {
		System.out.println("========== TestBean 构造方法执行 ==========");
	}
	
    /* ==================== Aware start ==================== */

    @Override
    public void setBeanName(String s) {
        System.out.println("4. BeanNameAware#setBeanName");
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        System.out.println("5. BeanClassLoaderAware#setBeanClassLoader");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("6. BeanFactoryAware#setBeanFactory");
    }

    @Override
    public void setEnvironment(Environment environment) {
        System.out.println("7. EnvironmentAware#setEnvironment");
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        System.out.println("8. EmbeddedValueResolverAware#setEmbeddedValueResolver");
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        System.out.println("9. ResourceLoaderAware#setResourceLoader");
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        System.out.println("10. ApplicationEventPublisherAware#setApplicationEventPublisher");
    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
        System.out.println("11. MessageSourceAware#setMessageSource");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("12. ApplicationContextAware#setApplicationContext");
    }
    /* ==================== Aware end ==================== */

    @PostConstruct
    public void postConstruct() {
        System.out.println("14. TestInitDestroyBean#postConstruct");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("15. InitializingBean#afterPropertiesSet");
    }

    /** 自定义初始化方法 */
    public void customInit() {
        System.out.println("16. TestInitDestroyBean#customInit");
    }

    /* ==================== 停止系统程序 ==================== */

    @PreDestroy
    public void preDestroy() {
        System.out.println("18. TestInitDestroyBean#preDestroy");
    }

    @Override
    public void destroy() {
        System.out.println("19. TestInitDestroyBean#destroy");
    }

    /** 自定义销毁方法 */
    public void customDestroy() {
        System.out.println("20. TestInitDestroyBean#customDestroy");
    }
}

3. 实现 BeanFactoryPostProcessor

package com.xxx.springtest.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * 自定义 BeanFactoryPostProcessor,该方法最先执行。
 */
@Component
public class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        System.out.println("0. BeanFactoryPostProcessor#postProcessBeanFactory");
    }
}

4. InstantiationAwareBeanPostProcessor

package com.xxx.springtest.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 自定义 InstantiationAwareBeanPostProcessor 处理。
 * 该接口的方法在实例化(调用默认构造方法)之前和之后执行。
 */
@Component
public class TestInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if ("testBean".equals(beanName)) {
            System.out.println("1. InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if ("testBean".equals(beanName)) {
            System.out.println("2. InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if ("testBean".equals(beanName)) {
            System.out.println("3. InstantiationAwareBeanPostProcessor#postProcessProperties");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessProperties(pvs, bean, beanName);
    }
}

5. 实现 BeanPostProcessor

package com.xxx.springtest.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 自定义 BeanPostProcessor 处理。
 * 两个方法分别在自定义初始化方法之前和之后执行。
 */
@Component
public class TestBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if ("testBean".equals(beanName)) {
            System.out.println("13. BeanPostProcessor#postProcessBeforeInitialization");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if ("testBean".equals(beanName)) {
            System.out.println("17. BeanPostProcessor#postProcessAfterInitialization");
        }
        return bean;
    }

}

6. 配置 testBean

package com.xxx.springtest.lifecycle;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Bean 生命周期测试 Configuration
 */
@Configuration
public class TestBeanLifecycleConfig {

    @Bean(initMethod = "customInit", destroyMethod = "customDestroy")
    public TestBean testBean() {
        return new TestBean();
    }
}

7. 创建启动类

package com.xxx.springtest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = {"com.xxx.springtest"})
public class SprintTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SprintTestApplication.class, args);
    }
}

运行并查看执行顺序

Spring Bean 生命周期顺序验证_第1张图片

源码

https://gitee.com/liuweibing/spring-test-lifecycle

你可能感兴趣的:(Java实践,spring,springboot)