看到一篇写的很好的 Spring Bean 生命周期的博客:一文读懂 Spring Bean 的生命周期,在此写个简单的 Bean 进行验证。
1. 创建Springboot项目
基于 springboot 的2.1.8.RELEASE
创建一个简单项目,只添加 spring-aop 包以引入spring依赖。
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.8.RELEASE</version><relativePath/></parent><groupId>com.xxx.springtest</groupId><artifactId>sprint-test</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><!-- 只添加一个 aop 包以引入spring依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></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 ==================== */@Overridepublic void setBeanName(String s) {System.out.println("4. BeanNameAware#setBeanName");}@Overridepublic void setBeanClassLoader(ClassLoader classLoader) {System.out.println("5. BeanClassLoaderAware#setBeanClassLoader");}@Overridepublic void setBeanFactory(BeanFactory beanFactory) throws BeansException {System.out.println("6. BeanFactoryAware#setBeanFactory");}@Overridepublic void setEnvironment(Environment environment) {System.out.println("7. EnvironmentAware#setEnvironment");}@Overridepublic void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {System.out.println("8. EmbeddedValueResolverAware#setEmbeddedValueResolver");}@Overridepublic void setResourceLoader(ResourceLoader resourceLoader) {System.out.println("9. ResourceLoaderAware#setResourceLoader");}@Overridepublic void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {System.out.println("10. ApplicationEventPublisherAware#setApplicationEventPublisher");}@Overridepublic void setMessageSource(MessageSource messageSource) {System.out.println("11. MessageSourceAware#setMessageSource");}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {System.out.println("12. ApplicationContextAware#setApplicationContext");}/* ==================== Aware end ==================== */@PostConstructpublic void postConstruct() {System.out.println("14. TestInitDestroyBean#postConstruct");}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("15. InitializingBean#afterPropertiesSet");}/** 自定义初始化方法 */public void customInit() {System.out.println("16. TestInitDestroyBean#customInit");}/* ==================== 停止系统程序 ==================== */@PreDestroypublic void preDestroy() {System.out.println("18. TestInitDestroyBean#preDestroy");}@Overridepublic 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 {@Overridepublic 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 {@Overridepublic Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {if ("testBean".equals(beanName)) {System.out.println("1. InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation");}return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);}@Overridepublic boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {if ("testBean".equals(beanName)) {System.out.println("2. InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation");}return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);}@Overridepublic 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 {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {if ("testBean".equals(beanName)) {System.out.println("13. BeanPostProcessor#postProcessBeforeInitialization");}return bean;}@Overridepublic 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);}
}
运行并查看执行顺序
源码
https://gitee.com/liuweibing/spring-test-lifecycle