找回密码
 立即注册
首页 业界区 业界 Bean生命周期的扩展点:Bean Post Processor

Bean生命周期的扩展点:Bean Post Processor

遏筒煽 4 天前
摘要:在本篇文章中,我们将深入探讨Spring框架中的重要组件——BeanPostProcessor。首先,我们将了解其设计理念和目标,然后通过实际的例子学习如何基础使用它,如何通过BeanPostProcessor改变Bean的初始化结果以及如何利用它修改Bean的属性。
本文分享自华为云社区《Spring高手之路6——Bean生命周期的扩展点:BeanPostProcessor》,作者:砖业洋__ 。
1. 探索Spring的后置处理器(BeanPostProcessor)

1.1 BeanPostProcessor的设计理念

BeanPostProcessor的设计目标主要是提供一种扩展机制,让开发者可以在Spring Bean的初始化阶段进行自定义操作。这种设计理念主要体现了Spring的一种重要原则,即“开放封闭原则”。开放封闭原则强调软件实体(类、模块、函数等等)应该对于扩展是开放的,对于修改是封闭的。在这里,Spring容器对于Bean的创建、初始化、销毁等生命周期进行了管理,但同时开放了BeanPostProcessor这种扩展点,让开发者可以在不修改Spring源码的情况下,实现对Spring Bean生命周期的自定义操作,这种设计理念大大提升了Spring的灵活性和可扩展性。
BeanPostProcessor不是Spring Bean生命周期的一部分,但它是在Spring Bean生命周期中起重要作用的组件。
1.2 BeanPostProcessor的文档说明

我们来看看这个方法的文档注释,从图中可以看到,BeanPostProcessor 接口定义了两个方法,postProcessBeforeInitialization和postProcessAfterInitialization
1.png
postProcessBeforeInitialization方法会在任何bean初始化回调(如InitializingBean的afterPropertiesSet方法或者自定义的init-method)之前被调用。也就是说,这个方法会在bean的属性已经设置完毕,但还未进行初始化时被调用。
postProcessAfterInitialization方法在任何bean初始化回调(比如InitializingBean的afterPropertiesSet或者自定义的初始化方法)之后被调用。这个时候,bean的属性值已经被填充完毕。返回的bean实例可能是原始bean的一个包装。
2.png
2. BeanPostProcessor的使用

2.1 BeanPostProcessor的基础使用示例

全部代码如下:
首先定义两个简单的Bean:Lion和Elephant
Lion.java
  1. package com.example.demo.bean;
  2. public class Lion {
  3. private String name;
  4. public String getName() {
  5. return name;
  6. }
  7. public void setName(String name) {
  8. this.name = name;
  9. }
  10. }
复制代码
Elephant.java
  1. package com.example.demo.bean;
  2. public class Elephant {
  3. private String name;
  4. public String getName() {
  5. return name;
  6. }
  7. public void setName(String name) {
  8. this.name = name;
  9. }
  10. }
复制代码
然后定义一个简单的BeanPostProcessor,它只是打印出被处理的Bean的名字:
  1. package com.example.demo.processor;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.config.BeanPostProcessor;
  4. public class MyBeanPostProcessor implements BeanPostProcessor {
  5. @Override
  6. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  7. System.out.println("Before initialization: " + beanName);
  8. return bean;
  9. }
  10. @Override
  11. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  12. System.out.println("After initialization: " + beanName);
  13. return bean;
  14. }
  15. }
复制代码
接着我们定义一个配置类,其中包含对Lion、Elephant类和MyBeanPostProcessor类的Bean定义:
  1. package com.example.demo.configuration;
  2. import com.example.demo.bean.Elephant;
  3. import com.example.demo.bean.Lion;
  4. import com.example.demo.processor.MyBeanPostProcessor;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. @Configuration
  8. public class AnimalConfig {
  9. @Bean
  10. public Lion lion() {
  11. return new Lion();
  12. }
  13. @Bean
  14. public Elephant elephant() {
  15. return new Elephant();
  16. }
  17. @Bean
  18. public MyBeanPostProcessor myBeanPostProcessor() {
  19. return new MyBeanPostProcessor();
  20. }
  21. }
复制代码
最后,我们在主程序中创建ApplicationContext对象:
  1. import org.springframework.context.ApplicationContext;
  2. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  3. public class Main {
  4. public static void main(String[] args) {
  5. ApplicationContext context = new AnnotationConfigApplicationContext(AnimalConfig.class);
  6. ((AnnotationConfigApplicationContext)context).close();
  7. }
  8. }
复制代码
运行结果:
3.png
以上代码在执行时,将先创建Lion和Elephant对象,然后在初始化过程中和初始化后调用postProcessBeforeInitialization和postProcessAfterInitialization方法,打印出被处理的Bean的名字。
细心的小伙伴可能观察到这里有红色日志
信息: Bean 'animalConfig' of type [com.example.demo.configuration.AnimalConfig$$EnhancerBySpringCGLIB$$ee4adc7e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

在Spring中,BeanPostProcessor是被特殊处理的,它们会在其他普通Bean之前被实例化和初始化,这样设计的原因是BeanPostProcessor的存在可以影响其他Bean的创建和初始化过程。 Spring应用上下文中可以存在多个BeanPostProcessor,Spring本身就提供了很多内置的BeanPostProcessor。

但是,如果在初始化BeanPostProcessor的过程中需要依赖其他的Bean,那么这些被依赖的Bean会先于后置处理器进行初始化。然而,由于这些被依赖的Bean是在该BeanPostProcessor初始化完成之前就已经进行了初始化,它们就会错过这个BeanPostProcessor的处理。在这个例子中,MyBeanPostProcessor就是这样的一个BeanPostProcessor,而"animalConfig"是它所依赖的Bean。所以这个日志信息就是说,'animalConfig'这个Bean在初始化的时候,没有被所有的BeanPostProcessor处理,这里它无法得到MyBeanPostProcessor的处理。

我们只需要把实例化过程直接交给Spring容器来管理,而不是在配置类中手动进行实例化,就可以消除这个提示信息,也就是在MyBeanPostProcessor上加@Component即可。

在第3节的例子中就使用了@Component处理这个MyBeanPostProcessor,这个提示就消失了。
2.2 利用BeanPostProcessor修改Bean的初始化结果的返回值

还是上面的例子,我们只修改一下MyBeanPostProcessor 类的方法后再次运行
  1. package com.example.demo.processor;
  2. import com.example.demo.bean.Elephant;
  3. import com.example.demo.bean.Lion;
  4. import org.springframework.beans.BeansException;
  5. import org.springframework.beans.factory.config.BeanPostProcessor;
  6. public class MyBeanPostProcessor implements BeanPostProcessor {
  7. @Override
  8. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  9. System.out.println("Before initialization: " + bean);
  10. if (bean instanceof Lion) {
  11. return new Elephant();
  12. }
  13. return bean;
  14. }
  15. @Override
  16. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  17. System.out.println("After initialization: " + bean);
  18. return bean;
  19. }
  20. }
复制代码
运行结果:
4.png
BeanPostProcessor的两个方法都可以返回任意的Object,这意味着我们可以在这两个方法中更改返回的bean。例如,如果我们让postProcessBeforeInitialization方法在接收到Lion实例时返回一个新的Elephant实例,那么我们将会看到Lion实例变成了Elephant实例。
那既然BeanPostProcessor的两个方法都可以返回任意的Object,那我搞点破坏返回null会怎么样,会不会因为初始化bean为null而导致异常呢?
答案是不会的,我们来看一下:
  1. package com.example.demo.processor;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.config.BeanPostProcessor;
  4. public class MyBeanPostProcessor implements BeanPostProcessor {
  5. @Override
  6. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  7. System.out.println("Before initialization: " + bean);
  8. return null;
  9. }
  10. @Override
  11. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  12. System.out.println("After initialization: " + bean);
  13. return bean;
  14. }
  15. }
复制代码
我们运行看结果
5.png
结果发现还是正常初始化的bean类型,不会有任何改变,我们继续调试看看是为什么
6.png
我们通过堆栈帧看到调用postProcessBeforeInitialization方法的上一个方法是applyBeanPostProcessorsBeforeInitialization,双击点开看一看这个方法
7.png
从我这个调试图中可以看到,如果postProcessBeforeInitialization返回null,Spring仍然用原始的bean进行后续的处理,同样的逻辑在postProcessAfterInitialization也是一样。这就是为什么我们在BeanPostProcessor类的方法中返回null,原始bean实例还是存在的原因。
2.3 通过BeanPostProcessor实现Bean属性的动态修改

来看看是怎么拦截 bean 的初始化的
全部代码如下:
首先,我们定义一个Lion类:
  1. public class Lion {
  2. private String name;
  3. public Lion() {
  4. this.name = "Default Lion";
  5. }
  6. public Lion(String name) {
  7. this.name = name;
  8. }
  9. public String getName() {
  10. return name;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. @Override
  16. public String toString() {
  17. return "Lion{" + "name='" + name + '\'' + '}';
  18. }
  19. }
复制代码
接下来,我们定义一个BeanPostProcessor,我们称之为MyBeanPostProcessor :
  1. package com.example.demo.processor;
  2. import com.example.demo.bean.Lion;
  3. import org.springframework.beans.BeansException;
  4. import org.springframework.beans.factory.config.BeanPostProcessor;
  5. public class MyBeanPostProcessor implements BeanPostProcessor {
  6. @Override
  7. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  8. System.out.println("Bean的初始化之前:" + bean);
  9. return bean;
  10. }
  11. @Override
  12. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  13. System.out.println("Bean的初始化之后:" + bean);
  14. if (bean instanceof Lion) {
  15. ((Lion) bean).setName("Simba");
  16. }
  17. return bean;
  18. }
  19. }
复制代码
然后我们定义一个配置类,其中包含对Lion类的Bean定义和对MyBeanPostProcessor 类的Bean定义:
  1. package com.example.demo.configuration;
  2. import com.example.demo.bean.Lion;
  3. import com.example.demo.processor.MyBeanPostProcessor;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. @Configuration
  7. public class AnimalConfig {
  8. @Bean
  9. public Lion lion() {
  10. return new Lion();
  11. }
  12. @Bean
  13. public MyBeanPostProcessor myBeanPostProcessor() {
  14. return new MyBeanPostProcessor();
  15. }
  16. }
复制代码
最后,我们在主程序中创建ApplicationContext对象,并获取Lion对象:
  1. package com.example.demo;
  2. import com.example.demo.bean.Lion;
  3. import com.example.demo.configuration.AnimalConfig;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  6. public class DemoApplication {
  7. public static void main(String[] args) {
  8. ApplicationContext context = new AnnotationConfigApplicationContext(AnimalConfig.class);
  9. Lion lion = context.getBean("lion", Lion.class);
  10. System.out.println(lion);
  11. ((AnnotationConfigApplicationContext)context).close();
  12. }
  13. }
复制代码
运行结果:
8.png
上面代码在执行时,先创建一个Lion对象,然后在初始化过程中和初始化后调用postProcessBeforeInitialization和postProcessAfterInitialization方法,修改Lion的名字为"Simba",最后在主程序中输出Lion对象,显示其名字为"Simba"。
3. 深度剖析BeanPostProcessor的执行时机

3.1 后置处理器在Bean生命周期中的作用及执行时机

在这个例子中,我们将创建一个名为Lion和Elephant 的Bean,它会展示属性赋值和生命周期的各个步骤的执行顺序。同时,我们还将创建一个BeanPostProcessor来打印消息并显示它的执行时机。
全部代码如下:
首先,我们定义我们的Lion:
  1. package com.example.demo.bean;
  2. import org.springframework.beans.factory.DisposableBean;
  3. import org.springframework.beans.factory.InitializingBean;
  4. import javax.annotation.PostConstruct;
  5. import javax.annotation.PreDestroy;
  6. import javax.annotation.Resource;
  7. public class Lion implements InitializingBean, DisposableBean {
  8. private String name;
  9. private Elephant elephant;
  10. public Lion() {
  11. System.out.println("1. Bean Constructor Method Invoked!");
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. System.out.println("2. Bean Setter Method Invoked! name: " + name);
  19. }
  20. /**
  21.      * setter注入
  22.      * @param elephant
  23.      */
  24. @Resource
  25. public void setElephant(Elephant elephant) {
  26. this.elephant = elephant;
  27. System.out.println("2. Bean Setter Method Invoked! elephant: " + elephant);
  28. }
  29. @PostConstruct
  30. public void postConstruct() {
  31. System.out.println("4. @PostConstruct Method Invoked!");
  32. }
  33. @Override
  34. public void afterPropertiesSet() throws Exception {
  35. System.out.println("5. afterPropertiesSet Method Invoked!");
  36. }
  37. public void customInitMethod() {
  38. System.out.println("6. customInitMethod Method Invoked!");
  39. }
  40. @PreDestroy
  41. public void preDestroy() {
  42. System.out.println("8. @PreDestroy Method Invoked!");
  43. }
  44. @Override
  45. public void destroy() throws Exception {
  46. System.out.println("9. destroy Method Invoked!");
  47. }
  48. public void customDestroyMethod() {
  49. System.out.println("10. customDestroyMethod Method Invoked!");
  50. }
  51. }
复制代码
创建Lion所依赖的Elephant
  1. package com.example.demo.bean;
  2. import org.springframework.stereotype.Component;
  3. @Component
  4. public class Elephant {
  5. private String name;
  6. public String getName() {
  7. return name;
  8. }
  9. public void setName(String name) {
  10. this.name = name;
  11. }
  12. }
复制代码
然后,我们定义一个简单的BeanPostProcessor:
  1. package com.example.demo.processor;
  2. import com.example.demo.bean.Lion;
  3. import org.springframework.beans.BeansException;
  4. import org.springframework.beans.factory.config.BeanPostProcessor;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. public class MyBeanPostProcessor implements BeanPostProcessor {
  8. @Override
  9. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  10. if(bean instanceof Lion) {
  11. System.out.println("3. postProcessBeforeInitialization Method Invoked!");
  12. }
  13. return bean;
  14. }
  15. @Override
  16. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  17. if(bean instanceof Lion) {
  18. System.out.println("7. postProcessAfterInitialization Method Invoked!");
  19. }
  20. return bean;
  21. }
  22. }
复制代码
创建一个配置类AnimalConfig
  1. package com.example.demo.configuration;
  2. import com.example.demo.bean.Lion;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. @Configuration
  6. public class AnimalConfig {
  7. @Bean(initMethod = "customInitMethod", destroyMethod = "customDestroyMethod")
  8. public Lion lion() {
  9. Lion lion = new Lion();
  10. lion.setName("my lion");
  11. return lion;
  12. }
  13. }
复制代码
主程序:
  1. package com.example.demo;
  2. import com.example.demo.bean.Lion;
  3. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  4. public class DemoApplication {
  5. public static void main(String[] args) {
  6. System.out.println("容器初始化之前...");
  7. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.example");
  8. System.out.println("容器初始化完成");
  9. Lion bean = context.getBean(Lion.class);
  10. bean.setName("oh!!! My Bean set new name");
  11. System.out.println("容器准备关闭...");
  12. context.close();
  13. System.out.println("容器已经关闭");
  14. }
  15. }
复制代码
控制台上看到所有的方法调用都按照预期的顺序进行,这可以更好地理解Bean属性赋值和生命周期以及BeanPostProcessor的作用。
9.png
根据打印日志我们可以分析出

  • 首先,Bean Constructor Method Invoked! 表明 Lion 的构造器被调用,创建了一个新的 Lion 实例。
  • 接着,Bean Setter Method Invoked! name: my lion 和 Bean Setter Method Invoked! elephant: com.example.demo.bean.Elephant@7364985f 说明 Spring 对 Lion 实例的依赖注入。在这一步,Spring 调用了 Lion 的 setter 方法,为 name 属性设置了值 “my lion”,同时为 elephant 属性注入了一个 Elephant 实例。
  • 然后,postProcessBeforeInitialization Method Invoked! 说明 MyBeanPostProcessor 的 postProcessBeforeInitialization 方法被调用,这是在初始化 Lion 实例之前。
  • @PostConstruct Method Invoked! 说明 @PostConstruct 注解的方法被调用,这是在 Bean 初始化之后,但是在 Spring 执行任何进一步初始化之前。
  • afterPropertiesSet Method Invoked! 说明 Spring 调用了 InitializingBean 的 afterPropertiesSet 方法
  • customInitMethod Method Invoked! 表示调用了 Lion 实例的 init-method 方法。
  • postProcessAfterInitialization Method Invoked! 说明 MyBeanPostProcessor 的 postProcessAfterInitialization 方法被调用,这是在初始化 Lion 实例之后。
    然后 Spring 完成了整个初始化过程。
  • 主程序中手动调用了 Lion 实例的 setter 方法,因此在 Bean Setter Method Invoked! name: oh!!! My Bean set new name 可见,name 属性被设置了新的值 "oh!!! My Bean set new name"。
    当容器准备关闭时:
  • @PreDestroy Method Invoked! 说明 @PreDestroy 注解的方法被调用,这是在 Bean 销毁之前。
  • destroy Method Invoked! 表示 Lion 实例开始销毁。在这一步,Spring 调用了 DisposableBean 的 destroy 方法。
  • customDestroyMethod Method Invoked! 表示 Lion 实例开始销毁,调用了Lion 实例的 destroy-method 方法。
最后,Spring 完成了整个销毁过程,容器关闭。
这个日志提供了 Spring Bean 生命周期的完整视图,显示了从创建到销毁过程中的所有步骤。
注意:DisposableBean 的 destroy 方法和 destroy-method 方法调用,这个销毁过程不意味着bean实例就被立即从内存中删除了,Java的垃圾收集机制决定了对象什么时候被从内存中删除。Spring容器无法强制进行这个操作,比如解除bean之间的关联和清理缓存,这并不是Spring在销毁bean时会做的,而是由Java的垃圾回收器在一个对象不再被引用时做的事情。
BeanPostProcessor 的执行顺序是在 Spring Bean 的生命周期中非常重要的一部分。例如,如果一个 Bean 实现了 InitializingBean 接口,那么 afterPropertiesSet 方法会在所有的 BeanPostProcessor 的 postProcessBeforeInitialization 方法之后调用,以确保所有的前置处理都完成了。同样,BeanPostProcessor 的 postProcessAfterInitialization 方法会在所有的初始化回调方法之后调用,以确保 Bean 已经完全初始化了。
我们可以注册多个 BeanPostProcessor。在这种情况下,Spring 会按照它们的 Ordered 接口或者 @Order 注解指定的顺序来调用这些后置处理器。如果没有指定顺序,那么它们的执行顺序是不确定的。
3.2 图解:Bean生命周期与后置处理器的交互时序

综合上面的执行结果,我们来总结一下,下面是Spring Bean生命周期的时序图,它详细地描绘了Spring Bean从实例化到准备使用的整个过程,包括Bean的实例化、属性赋值、生命周期方法的执行和后置处理器的调用。
10.png
 
点击关注,第一时间了解华为云新鲜技术~

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册