验证

依赖

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. <version>1.18.16</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework</groupId>
  8. <artifactId>spring-context</artifactId>
  9. <version>5.3.1</version>
  10. </dependency>

结构

  1. top.parak.springlearn
  2. ├───config
  3. └───Config
  4. ├───common
  5. └───KHighnessExecutingLog
  6. ├───life
  7. └───KHighnessAwareBeanPostProcessor
  8. └───KHighnessBeanFactoryPostProcessor
  9. └───KHighnessBeanPostProcessor
  10. └───service
  11. └───UserInterface
  12. └───UserService
  13. └───KHighnessApplication

编码

日志输出记录类

  1. package top.parak.springlearn.common;
  2. import java.time.LocalDateTime;
  3. import java.time.format.DateTimeFormatter;
  4. import java.util.concurrent.atomic.AtomicLong;
  5. /**
  6. * @author KHighness
  7. * @since 2021-05-06
  8. */
  9. public class KHighnessExecutingLog {
  10. private final static AtomicLong COUNTER = new AtomicLong();
  11. private final static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
  12. public static void info(String message) {
  13. System.out.println(FORMATTER.format(LocalDateTime.now()) + " [" + COUNTER.incrementAndGet() + "] => " + message);
  14. }
  15. }

用户业务接口

  1. package top.parak.springlearn.service;
  2. /**
  3. * @author KHighness
  4. * @since 2021-04-01
  5. */
  6. @FunctionalInterface
  7. public interface UserInterface {
  8. public void test();
  9. }

用户业务接口实现类

  1. package top.parak.springlearn.service;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.*;
  4. import org.springframework.context.*;
  5. import org.springframework.core.env.Environment;
  6. import org.springframework.core.io.ResourceLoader;
  7. import org.springframework.stereotype.Component;
  8. import org.springframework.util.StringValueResolver;
  9. import top.parak.springlearn.common.KHighnessExecutingLog;
  10. import javax.annotation.PostConstruct;
  11. import javax.annotation.PreDestroy;
  12. /**
  13. * @author KHighness
  14. * @since 2021-04-01
  15. */
  16. @Component
  17. public class UserService implements
  18. /* 业务接口 */ UserInterface,
  19. /* Bean接口 */ BeanNameAware, BeanClassLoaderAware, BeanFactoryAware,
  20. /* 环境接口 */ EnvironmentAware, EmbeddedValueResolverAware, ResourceLoaderAware, MessageSourceAware, ApplicationEventPublisherAware, ApplicationContextAware,
  21. /* 后置接口 */ InitializingBean, DisposableBean {
  22. private String name;
  23. public UserService() {
  24. KHighnessExecutingLog.info("构造函数: UserService.UserService() ");
  25. }
  26. public void setName(String name) {
  27. this.name = name;
  28. KHighnessExecutingLog.info("set函数: UserService.setName() ");
  29. }
  30. public void initMethod() {
  31. KHighnessExecutingLog.info("自定义初始化: UserService.initMethod()");
  32. }
  33. public void destroyMethod() {
  34. KHighnessExecutingLog.info("自定义销毁: UserService.destroyMethod()");
  35. }
  36. /**
  37. * 传入bean名称
  38. * @see BeanNameAware
  39. */
  40. @Override
  41. public void setBeanName(String s) {
  42. KHighnessExecutingLog.info("传入bean名称: BeanNameAware.setBeanName()");
  43. }
  44. /**
  45. * 传入bean类加载器
  46. * @see BeanClassLoaderAware
  47. */
  48. @Override
  49. public void setBeanClassLoader(ClassLoader classLoader) {
  50. KHighnessExecutingLog.info("传入bean类加载器: BeanClassLoaderAware.setBeanClassLoader()");
  51. }
  52. /**
  53. * 传入bean工厂
  54. * @see BeanFactoryAware
  55. */
  56. @Override
  57. public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
  58. KHighnessExecutingLog.info("传入bean工厂: BeanFactoryAware.setBeanFactory()");
  59. }
  60. /**
  61. * 传入运行时环境
  62. * @see EnvironmentAware
  63. */
  64. @Override
  65. public void setEnvironment(Environment environment) {
  66. KHighnessExecutingLog.info("传入运行时环境: EnvironmentAware.setEnvironment()");
  67. }
  68. /**
  69. * 传入文件解析器
  70. * @see EmbeddedValueResolverAware
  71. */
  72. @Override
  73. public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
  74. KHighnessExecutingLog.info("传入文件解析器: EmbeddedValueResolverAware.setEmbeddedValueResolver()");
  75. }
  76. /**
  77. * 传入资源加载器
  78. * @see ResourceLoaderAware
  79. */
  80. @Override
  81. public void setResourceLoader(ResourceLoader resourceLoader) {
  82. KHighnessExecutingLog.info("传入资源加载器: ResourceLoaderAware.setResourceLoader()");
  83. }
  84. /**
  85. * 传入事件发布器
  86. * @see ApplicationEventPublisherAware
  87. */
  88. @Override
  89. public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
  90. KHighnessExecutingLog.info("传入事件发布器: ApplicationEventPublisherAware.setApplicationEventPublisher()");
  91. }
  92. /**
  93. * 传入语言国际化
  94. * @see MessageSourceAware
  95. */
  96. @Override
  97. public void setMessageSource(MessageSource messageSource) {
  98. KHighnessExecutingLog.info("传入语言国际化: MessageSourceAware.setMessageSource()");
  99. }
  100. /**
  101. * 传入应用上下文
  102. * @see ApplicationContextAware
  103. */
  104. @Override
  105. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  106. KHighnessExecutingLog.info("传入应用上下文: ApplicationContextAware.setApplicationContext()");
  107. }
  108. /**
  109. * 初始化
  110. * <p>如名,属性设置之后执行</p>
  111. * @see InitializingBean
  112. */
  113. @Override
  114. public void afterPropertiesSet() throws Exception {
  115. KHighnessExecutingLog.info("初始化: InitializingBean.afterPropertiesSet()");
  116. }
  117. /**
  118. * 构造之后
  119. */
  120. @PostConstruct
  121. public void postConstruct() {
  122. KHighnessExecutingLog.info("构造之后: @PostConstruct postConstruct()");
  123. }
  124. /**
  125. * 销毁之前
  126. */
  127. @PreDestroy
  128. public void preDestroy() {
  129. KHighnessExecutingLog.info("销毁之前: @PreDestroy preDestroy()");
  130. }
  131. /**
  132. * 销毁bean
  133. * @see DisposableBean
  134. */
  135. @Override
  136. public void destroy() throws Exception {
  137. KHighnessExecutingLog.info("销毁bean: DisposableBean.destroy()");
  138. }
  139. /**
  140. * 实现业务接口
  141. * @see UserInterface
  142. */
  143. @Override
  144. public void test() {
  145. KHighnessExecutingLog.info("业务逻辑: UserInterface.test() " + this.name);
  146. }
  147. }

后置处理器

  1. package top.parak.springlearn.life;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
  4. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
  5. import org.springframework.stereotype.Component;
  6. import top.parak.springlearn.common.KHighnessExecutingLog;
  7. /**
  8. * @author KHighness
  9. * @since 2021-05-06
  10. */
  11. @Component
  12. public class KHighnessBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
  13. @Override
  14. public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
  15. KHighnessExecutingLog.info("实例化前: BeanFactoryPostProcessor.postProcessBeanFactory()");
  16. }
  17. }
  1. package top.parak.springlearn.life;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.config.BeanPostProcessor;
  4. import org.springframework.stereotype.Component;
  5. import top.parak.springlearn.common.KHighnessExecutingLog;
  6. /**
  7. * @author KHighness
  8. * @since 2021-05-06
  9. */
  10. @Component
  11. public class KHighnessBeanPostProcessor implements BeanPostProcessor {
  12. @Override
  13. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  14. KHighnessExecutingLog.info("初始化前: BeanPostProcessor.postProcessBeforeInitialization()");
  15. return null;
  16. }
  17. @Override
  18. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  19. KHighnessExecutingLog.info("初始化后: BeanPostProcessor.postProcessAfterInitialization()");
  20. return null;
  21. }
  22. }
  1. package top.parak.springlearn.life;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
  4. import org.springframework.stereotype.Component;
  5. import top.parak.springlearn.common.KHighnessExecutingLog;
  6. import top.parak.springlearn.service.UserService;
  7. import javax.annotation.PostConstruct;
  8. import java.lang.reflect.*;
  9. /**
  10. * @author KHighness
  11. * @since 2021-04-01
  12. */
  13. @Component
  14. public class UserServiceBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
  15. @Override
  16. public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
  17. if (beanClass.equals(UserService.class)) {
  18. KHighnessExecutingLog.info("实例化前: UserServiceBeanPostProcessor.postProcessBeforeInstantiation()");
  19. }
  20. return null;
  21. }
  22. /**
  23. * 返回false则终止bean属性注入
  24. */
  25. @Override
  26. public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
  27. if (bean.getClass().equals(UserService.class)) {
  28. KHighnessExecutingLog.info("实例化后: UserServiceBeanPostProcessor.postProcessAfterInstantiation() ");
  29. }
  30. return true;
  31. }
  32. @Override
  33. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  34. if (beanName.equals("userService")) {
  35. KHighnessExecutingLog.info("初始化前: UserServiceBeanPostProcessor.postProcessBeforeInitialization()");
  36. for (Method method : bean.getClass().getMethods()) {
  37. if (method.isAnnotationPresent(PostConstruct.class)) {
  38. try {
  39. method.invoke(bean);
  40. } catch (IllegalAccessException | InvocationTargetException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }
  46. return null;
  47. }
  48. @Override
  49. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  50. if (beanName.equals("userService")) {
  51. KHighnessExecutingLog.info("初始化后: UserServiceBeanPostProcessor.postProcessAfterInitialization() ");
  52. // 模拟动态代理AOP
  53. return Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), (proxy, method, args) -> {
  54. KHighnessExecutingLog.info("动态代理: Proxy.newProxyInstance()");
  55. method.invoke(bean, args);
  56. return null;
  57. });
  58. }
  59. return null;
  60. }
  61. }

配置类

  1. package top.parak.springlearn.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.ComponentScan;
  4. import org.springframework.context.annotation.Configuration;
  5. import top.parak.springlearn.service.UserService;
  6. /**
  7. * @author KHighness
  8. * @since 2021-05-06
  9. */
  10. @Configuration
  11. @ComponentScan("top.parak.springlearn")
  12. public class Config {
  13. @Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
  14. public UserService userService() {
  15. UserService userService = new UserService();
  16. userService.setName("KHighness");
  17. return userService;
  18. }
  19. }

测试类

  1. package top.parak.springlearn;
  2. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  3. import top.parak.springlearn.config.Config;
  4. import top.parak.springlearn.service.UserInterface;
  5. /**
  6. * @author KHighness
  7. * @since 2021-03-30
  8. */
  9. public class KHighnessApplication {
  10. public static void main(String[] args) {
  11. AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
  12. UserInterface userInterface = (UserInterface) applicationContext.getBean("userService");
  13. userInterface.test();
  14. applicationContext.close();
  15. }
  16. }

输出

  1. 2021-05-14 14:37:37.085 [1] => 实例化前: BeanFactoryPostProcessor.postProcessBeanFactory()
  2. 2021-05-14 14:37:37.118 [2] => 实例化前: InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()
  3. 2021-05-14 14:37:37.128 [3] => 构造函数: UserService.UserService()
  4. 2021-05-14 14:37:37.129 [4] => set函数: UserService.setName()
  5. 2021-05-14 14:37:37.131 [5] => 实例化后: InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation()
  6. 2021-05-14 14:37:37.136 [6] => 传入bean名称: BeanNameAware.setBeanName()
  7. 2021-05-14 14:37:37.136 [7] => 传入bean类加载器: BeanClassLoaderAware.setBeanClassLoader()
  8. 2021-05-14 14:37:37.136 [8] => 传入bean工厂: BeanFactoryAware.setBeanFactory()
  9. 2021-05-14 14:37:37.137 [9] => 传入运行时环境: EnvironmentAware.setEnvironment()
  10. 2021-05-14 14:37:37.137 [10] => 传入文件解析器: EmbeddedValueResolverAware.setEmbeddedValueResolver()
  11. 2021-05-14 14:37:37.137 [11] => 传入资源加载器: ResourceLoaderAware.setResourceLoader()
  12. 2021-05-14 14:37:37.137 [12] => 传入事件发布器: ApplicationEventPublisherAware.setApplicationEventPublisher()
  13. 2021-05-14 14:37:37.137 [13] => 传入语言国际化: MessageSourceAware.setMessageSource()
  14. 2021-05-14 14:37:37.137 [14] => 传入应用上下文: ApplicationContextAware.setApplicationContext()
  15. 2021-05-14 14:37:37.137 [15] => 初始化前: InstantiationAwareBeanPostProcessor.postProcessBeforeInitialization()
  16. 2021-05-14 14:37:37.137 [16] => 构造之后: @PostConstruct postConstruct()
  17. 2021-05-14 14:37:37.137 [17] => 初始化: InitializingBean.afterPropertiesSet()
  18. 2021-05-14 14:37:37.138 [18] => 自定义初始化: UserService.initMethod()
  19. 2021-05-14 14:37:37.138 [19] => 初始化后: InstantiationAwareBeanPostProcessor.postProcessAfterInitialization()
  20. 2021-05-14 14:37:37.140 [20] => 初始化后: BeanPostProcessor.postProcessAfterInitialization()
  21. 2021-05-14 14:37:37.153 [21] => 动态代理: Proxy.newProxyInstance()
  22. 2021-05-14 14:37:37.153 [22] => 业务逻辑: UserInterface.test() KHighness
  23. 2021-05-14 14:37:37.154 [23] => 销毁之前: @PreDestroy preDestroy()
  24. 2021-05-14 14:37:37.154 [24] => 销毁bean: DisposableBean.destroy()
  25. 2021-05-14 14:37:37.154 [25] => 自定义销毁: UserService.destroyMethod()

总结

  • 实例化
    1. 实例化前:BeanFactoryPostProcessor#postProcessBeanFactory()
    2. 实例化前:InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation()
    3. 执行bean的构造函数
    4. 实例化后:InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation()
    5. 为bean注入属性
  • Bean接口回调
    1. 传入bean名称:BeanNameAware#setBeanName()
    2. 传入bean类加载器:BeanClassLoaderAware#setBeanClassLoader()
    3. 传入bean工厂:BeanFactoryAware#setBeanFactory()
  • Spring接口回调
    1. 传入运行时环境:EnvironmentAware#setEnvironment()
    2. 传入文件解析器:EmbeddedValueResolverAware#setEmbeddedValueResolver()
    3. 传入资源加载器:ResourceLoaderAware#setResourceLoader()
    4. 传入事件发布器:ApplicationEventPublisherAware#setApplicationEventPublisher()
    5. 传入语言国家化:MessageSourceAware#setMessageSourceAware()
    6. 传入应用上下文:ApplicationContextAware#setApplicaionAware()
  • 初始化
    1. 初始化前:InstantiationAwareBeanPostProcessor#postProcessBeforeInitialization()
    2. 构造之后:@PostConstruct标注的方法
    3. 初始化:InitializingBean#afterPropertiesSet()
    4. 自定义初始化:bean指定的initMethod
    5. 初始化后:InstantiationAwareBeanPostProcessor#postProcessAfterIntialization()
    6. 初始化后:BeanPostProcessor#postProcessAfterInitialization()
  • 销毁
    1. 销毁之前:@PreDestroy标注的方法
    2. 销毁bean:DisposableBean#destroy()
    3. 自定义销毁:bean指定的destroyMethod

参考

[1] 🚀 深究Spring中Bean的生命周期:https://www.cnblogs.com/javazhiyin/p/10905294.html
[2] 🚢 Spring Bean的生命周期:https://www.cnblogs.com/zrtqsk/p/3735273.html