验证
依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
结构
top.parak.springlearn
├───config
│ └───Config
├───common
│ └───KHighnessExecutingLog
├───life
│ └───KHighnessAwareBeanPostProcessor
│ └───KHighnessBeanFactoryPostProcessor
│ └───KHighnessBeanPostProcessor
└───service
│ └───UserInterface
│ └───UserService
└───KHighnessApplication
编码
日志输出记录类
package top.parak.springlearn.common;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author KHighness
* @since 2021-05-06
*/
public class KHighnessExecutingLog {
private final static AtomicLong COUNTER = new AtomicLong();
private final static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
public static void info(String message) {
System.out.println(FORMATTER.format(LocalDateTime.now()) + " [" + COUNTER.incrementAndGet() + "] => " + message);
}
}
用户业务接口
package top.parak.springlearn.service;
/**
* @author KHighness
* @since 2021-04-01
*/
@FunctionalInterface
public interface UserInterface {
public void test();
}
用户业务接口实现类
package top.parak.springlearn.service;
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.stereotype.Component;
import org.springframework.util.StringValueResolver;
import top.parak.springlearn.common.KHighnessExecutingLog;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* @author KHighness
* @since 2021-04-01
*/
@Component
public class UserService implements
/* 业务接口 */ UserInterface,
/* Bean接口 */ BeanNameAware, BeanClassLoaderAware, BeanFactoryAware,
/* 环境接口 */ EnvironmentAware, EmbeddedValueResolverAware, ResourceLoaderAware, MessageSourceAware, ApplicationEventPublisherAware, ApplicationContextAware,
/* 后置接口 */ InitializingBean, DisposableBean {
private String name;
public UserService() {
KHighnessExecutingLog.info("构造函数: UserService.UserService() ");
}
public void setName(String name) {
this.name = name;
KHighnessExecutingLog.info("set函数: UserService.setName() ");
}
public void initMethod() {
KHighnessExecutingLog.info("自定义初始化: UserService.initMethod()");
}
public void destroyMethod() {
KHighnessExecutingLog.info("自定义销毁: UserService.destroyMethod()");
}
/**
* 传入bean名称
* @see BeanNameAware
*/
@Override
public void setBeanName(String s) {
KHighnessExecutingLog.info("传入bean名称: BeanNameAware.setBeanName()");
}
/**
* 传入bean类加载器
* @see BeanClassLoaderAware
*/
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
KHighnessExecutingLog.info("传入bean类加载器: BeanClassLoaderAware.setBeanClassLoader()");
}
/**
* 传入bean工厂
* @see BeanFactoryAware
*/
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
KHighnessExecutingLog.info("传入bean工厂: BeanFactoryAware.setBeanFactory()");
}
/**
* 传入运行时环境
* @see EnvironmentAware
*/
@Override
public void setEnvironment(Environment environment) {
KHighnessExecutingLog.info("传入运行时环境: EnvironmentAware.setEnvironment()");
}
/**
* 传入文件解析器
* @see EmbeddedValueResolverAware
*/
@Override
public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
KHighnessExecutingLog.info("传入文件解析器: EmbeddedValueResolverAware.setEmbeddedValueResolver()");
}
/**
* 传入资源加载器
* @see ResourceLoaderAware
*/
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
KHighnessExecutingLog.info("传入资源加载器: ResourceLoaderAware.setResourceLoader()");
}
/**
* 传入事件发布器
* @see ApplicationEventPublisherAware
*/
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
KHighnessExecutingLog.info("传入事件发布器: ApplicationEventPublisherAware.setApplicationEventPublisher()");
}
/**
* 传入语言国际化
* @see MessageSourceAware
*/
@Override
public void setMessageSource(MessageSource messageSource) {
KHighnessExecutingLog.info("传入语言国际化: MessageSourceAware.setMessageSource()");
}
/**
* 传入应用上下文
* @see ApplicationContextAware
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
KHighnessExecutingLog.info("传入应用上下文: ApplicationContextAware.setApplicationContext()");
}
/**
* 初始化
* <p>如名,属性设置之后执行</p>
* @see InitializingBean
*/
@Override
public void afterPropertiesSet() throws Exception {
KHighnessExecutingLog.info("初始化: InitializingBean.afterPropertiesSet()");
}
/**
* 构造之后
*/
@PostConstruct
public void postConstruct() {
KHighnessExecutingLog.info("构造之后: @PostConstruct postConstruct()");
}
/**
* 销毁之前
*/
@PreDestroy
public void preDestroy() {
KHighnessExecutingLog.info("销毁之前: @PreDestroy preDestroy()");
}
/**
* 销毁bean
* @see DisposableBean
*/
@Override
public void destroy() throws Exception {
KHighnessExecutingLog.info("销毁bean: DisposableBean.destroy()");
}
/**
* 实现业务接口
* @see UserInterface
*/
@Override
public void test() {
KHighnessExecutingLog.info("业务逻辑: UserInterface.test() " + this.name);
}
}
后置处理器
package top.parak.springlearn.life;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
import top.parak.springlearn.common.KHighnessExecutingLog;
/**
* @author KHighness
* @since 2021-05-06
*/
@Component
public class KHighnessBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
KHighnessExecutingLog.info("实例化前: BeanFactoryPostProcessor.postProcessBeanFactory()");
}
}
package top.parak.springlearn.life;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import top.parak.springlearn.common.KHighnessExecutingLog;
/**
* @author KHighness
* @since 2021-05-06
*/
@Component
public class KHighnessBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
KHighnessExecutingLog.info("初始化前: BeanPostProcessor.postProcessBeforeInitialization()");
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
KHighnessExecutingLog.info("初始化后: BeanPostProcessor.postProcessAfterInitialization()");
return null;
}
}
package top.parak.springlearn.life;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;
import top.parak.springlearn.common.KHighnessExecutingLog;
import top.parak.springlearn.service.UserService;
import javax.annotation.PostConstruct;
import java.lang.reflect.*;
/**
* @author KHighness
* @since 2021-04-01
*/
@Component
public class UserServiceBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (beanClass.equals(UserService.class)) {
KHighnessExecutingLog.info("实例化前: UserServiceBeanPostProcessor.postProcessBeforeInstantiation()");
}
return null;
}
/**
* 返回false则终止bean属性注入
*/
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if (bean.getClass().equals(UserService.class)) {
KHighnessExecutingLog.info("实例化后: UserServiceBeanPostProcessor.postProcessAfterInstantiation() ");
}
return true;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("userService")) {
KHighnessExecutingLog.info("初始化前: UserServiceBeanPostProcessor.postProcessBeforeInitialization()");
for (Method method : bean.getClass().getMethods()) {
if (method.isAnnotationPresent(PostConstruct.class)) {
try {
method.invoke(bean);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("userService")) {
KHighnessExecutingLog.info("初始化后: UserServiceBeanPostProcessor.postProcessAfterInitialization() ");
// 模拟动态代理AOP
return Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), (proxy, method, args) -> {
KHighnessExecutingLog.info("动态代理: Proxy.newProxyInstance()");
method.invoke(bean, args);
return null;
});
}
return null;
}
}
配置类
package top.parak.springlearn.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import top.parak.springlearn.service.UserService;
/**
* @author KHighness
* @since 2021-05-06
*/
@Configuration
@ComponentScan("top.parak.springlearn")
public class Config {
@Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
public UserService userService() {
UserService userService = new UserService();
userService.setName("KHighness");
return userService;
}
}
测试类
package top.parak.springlearn;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import top.parak.springlearn.config.Config;
import top.parak.springlearn.service.UserInterface;
/**
* @author KHighness
* @since 2021-03-30
*/
public class KHighnessApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
UserInterface userInterface = (UserInterface) applicationContext.getBean("userService");
userInterface.test();
applicationContext.close();
}
}
输出
2021-05-14 14:37:37.085 [1] => 实例化前: BeanFactoryPostProcessor.postProcessBeanFactory()
2021-05-14 14:37:37.118 [2] => 实例化前: InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()
2021-05-14 14:37:37.128 [3] => 构造函数: UserService.UserService()
2021-05-14 14:37:37.129 [4] => set函数: UserService.setName()
2021-05-14 14:37:37.131 [5] => 实例化后: InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation()
2021-05-14 14:37:37.136 [6] => 传入bean名称: BeanNameAware.setBeanName()
2021-05-14 14:37:37.136 [7] => 传入bean类加载器: BeanClassLoaderAware.setBeanClassLoader()
2021-05-14 14:37:37.136 [8] => 传入bean工厂: BeanFactoryAware.setBeanFactory()
2021-05-14 14:37:37.137 [9] => 传入运行时环境: EnvironmentAware.setEnvironment()
2021-05-14 14:37:37.137 [10] => 传入文件解析器: EmbeddedValueResolverAware.setEmbeddedValueResolver()
2021-05-14 14:37:37.137 [11] => 传入资源加载器: ResourceLoaderAware.setResourceLoader()
2021-05-14 14:37:37.137 [12] => 传入事件发布器: ApplicationEventPublisherAware.setApplicationEventPublisher()
2021-05-14 14:37:37.137 [13] => 传入语言国际化: MessageSourceAware.setMessageSource()
2021-05-14 14:37:37.137 [14] => 传入应用上下文: ApplicationContextAware.setApplicationContext()
2021-05-14 14:37:37.137 [15] => 初始化前: InstantiationAwareBeanPostProcessor.postProcessBeforeInitialization()
2021-05-14 14:37:37.137 [16] => 构造之后: @PostConstruct postConstruct()
2021-05-14 14:37:37.137 [17] => 初始化: InitializingBean.afterPropertiesSet()
2021-05-14 14:37:37.138 [18] => 自定义初始化: UserService.initMethod()
2021-05-14 14:37:37.138 [19] => 初始化后: InstantiationAwareBeanPostProcessor.postProcessAfterInitialization()
2021-05-14 14:37:37.140 [20] => 初始化后: BeanPostProcessor.postProcessAfterInitialization()
2021-05-14 14:37:37.153 [21] => 动态代理: Proxy.newProxyInstance()
2021-05-14 14:37:37.153 [22] => 业务逻辑: UserInterface.test() KHighness
2021-05-14 14:37:37.154 [23] => 销毁之前: @PreDestroy preDestroy()
2021-05-14 14:37:37.154 [24] => 销毁bean: DisposableBean.destroy()
2021-05-14 14:37:37.154 [25] => 自定义销毁: UserService.destroyMethod()
总结
- 实例化
- 实例化前:BeanFactoryPostProcessor#postProcessBeanFactory()
- 实例化前:InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation()
- 执行bean的构造函数
- 实例化后:InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation()
- 为bean注入属性
- Bean接口回调
- 传入bean名称:BeanNameAware#setBeanName()
- 传入bean类加载器:BeanClassLoaderAware#setBeanClassLoader()
- 传入bean工厂:BeanFactoryAware#setBeanFactory()
- Spring接口回调
- 传入运行时环境:EnvironmentAware#setEnvironment()
- 传入文件解析器:EmbeddedValueResolverAware#setEmbeddedValueResolver()
- 传入资源加载器:ResourceLoaderAware#setResourceLoader()
- 传入事件发布器:ApplicationEventPublisherAware#setApplicationEventPublisher()
- 传入语言国家化:MessageSourceAware#setMessageSourceAware()
- 传入应用上下文:ApplicationContextAware#setApplicaionAware()
- 初始化
- 初始化前:InstantiationAwareBeanPostProcessor#postProcessBeforeInitialization()
- 构造之后:@PostConstruct标注的方法
- 初始化:InitializingBean#afterPropertiesSet()
- 自定义初始化:bean指定的initMethod
- 初始化后:InstantiationAwareBeanPostProcessor#postProcessAfterIntialization()
- 初始化后:BeanPostProcessor#postProcessAfterInitialization()
- 销毁
- 销毁之前:@PreDestroy标注的方法
- 销毁bean:DisposableBean#destroy()
- 自定义销毁:bean指定的destroyMethod
参考
[1] 🚀 深究Spring中Bean的生命周期:https://www.cnblogs.com/javazhiyin/p/10905294.html
[2] 🚢 Spring Bean的生命周期:https://www.cnblogs.com/zrtqsk/p/3735273.html