【Spring注解系列11】Spring后置处理器BeanPostProcessor用法与原理

拼搏现实的明天。 2022-02-24 11:40 385阅读 0赞

1.BeanPostProcessor原理

先说,bean的后置处理器BeanPostProcessor接口中两个方法:

  • postProcessBeforeInitialization:在初始化之前工作
  • postProcessAfterInitialization:在初始化之后工作

BeanPostProcessor原理

  • populateBean(beanName, mbd, instanceWrapper);//给bean进行属性赋值
  • 调用initializeBean方法,执行后置处理器和指定的初始化方法。(详细过程见下面源码)
  • 后置处理器BeanPostProcessor执行过程是,遍历得到容器中所有的BeanPostProcessor;挨个执行beforeInitialization,一但返回null,跳出for循环,不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization

核心执行方法initializeBean:

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean

initializeBean

{

applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);

invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化

applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

}

  1. /**
  2. * Initialize the given bean instance, applying factory callbacks
  3. * as well as init methods and bean post processors.
  4. * <p>Called from {@link #createBean} for traditionally defined beans,
  5. * and from {@link #initializeBean} for existing bean instances.
  6. * @param beanName the bean name in the factory (for debugging purposes)
  7. * @param bean the new bean instance we may need to initialize
  8. * @param mbd the bean definition that the bean was created with
  9. * (can also be {@code null}, if given an existing bean instance)
  10. * @return the initialized bean instance (potentially wrapped)
  11. * @see BeanNameAware
  12. * @see BeanClassLoaderAware
  13. * @see BeanFactoryAware
  14. * @see #applyBeanPostProcessorsBeforeInitialization
  15. * @see #invokeInitMethods
  16. * @see #applyBeanPostProcessorsAfterInitialization
  17. */
  18. protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
  19. if (System.getSecurityManager() != null) {
  20. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  21. invokeAwareMethods(beanName, bean);
  22. return null;
  23. }, getAccessControlContext());
  24. }
  25. else {
  26. //调用实现XXAware接口的方法
  27. invokeAwareMethods(beanName, bean);
  28. }
  29. Object wrappedBean = bean;
  30. if (mbd == null || !mbd.isSynthetic()) {
  31. //后置处理器--前置方法
  32. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  33. }
  34. try {
  35. //调用@bean或者<bean>标签中指定的初始化方法
  36. invokeInitMethods(beanName, wrappedBean, mbd);
  37. }
  38. catch (Throwable ex) {
  39. throw new BeanCreationException(
  40. (mbd != null ? mbd.getResourceDescription() : null),
  41. beanName, "Invocation of init method failed", ex);
  42. }
  43. if (mbd == null || !mbd.isSynthetic()) {
  44. //后置处理器--后置方法
  45. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  46. }
  47. return wrappedBean;
  48. }
  49. //后置处理器--前置方法
  50. @Override
  51. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
  52. throws BeansException {
  53. Object result = existingBean;
  54. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  55. Object current = processor.postProcessBeforeInitialization(result, beanName);
  56. if (current == null) {
  57. return result;
  58. }
  59. result = current;
  60. }
  61. return result;
  62. }
  63. //后置处理器--后置方法 处理方式都是会遍历所有的后置处理器,调用前置或后置方法
  64. @Override
  65. public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
  66. throws BeansException {
  67. Object result = existingBean;
  68. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  69. Object current = processor.postProcessAfterInitialization(result, beanName);
  70. if (current == null) {
  71. return result;
  72. }
  73. result = current;
  74. }
  75. return result;
  76. }

2.BeanPostProcessor 后置处理器在Spring底层中有那些应用

Spring底层对 BeanPostProcessor 的使用;

bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async,xxx BeanPostProcessor;

3.BeanPostProcessor 使用

  1. public class BeanLife {
  2. private String name;
  3. public String getName() {
  4. return name;
  5. }
  6. public void setName(String name) {
  7. this.name = name;
  8. }
  9. @Override
  10. public String toString() {
  11. return "BeanLife{" +
  12. "name='" + name + '\'' +
  13. '}';
  14. }
  15. public BeanLife() {
  16. System.out.println("构造方法:BeanLife--->construct...");
  17. }
  18. }
  19. /**
  20. * @author tuchuanbiao
  21. * @Date 2019/4/3 19:58
  22. *
  23. * 后置处理器:初始化前后进行处理工作
  24. * 将后置处理器加入到容器中
  25. *
  26. * 这里采用@Bean方式注入,也可以直接使用@Component
  27. */
  28. //@Component //一定要将后置处理器注入到容器中
  29. public class MyBeanPostProcessor implements BeanPostProcessor {
  30. @Nullable
  31. @Override
  32. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  33. System.out.println("bean后置处理器:MyBeanPostProcessor......postProcessBeforeInitialization");
  34. return bean;
  35. }
  36. @Nullable
  37. @Override
  38. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  39. System.out.println("bean后置处理器:MyBeanPostProcessor......postProcessAfterInitialization");
  40. return bean;
  41. }
  42. }
  43. @Configuration
  44. public class BeanLifeCycleConfig {
  45. @Bean(value = "beanLife")
  46. public BeanLife life() {
  47. BeanLife beanLife = new BeanLife();
  48. beanLife.setName("张三");
  49. System.out.println(beanLife);
  50. return beanLife;
  51. }
  52. @Bean
  53. public MyBeanPostProcessor myBeanPostProcessor(){
  54. return new MyBeanPostProcessor();
  55. }
  56. }
  57. //测试类
  58. public class BeanLifeCycleTest {
  59. public static void main(String[] args) {
  60. AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanLifeCycleConfig.class);
  61. System.out.println("applicationContext ..... 初始化结束");
  62. System.out.println("applicationContext ..... 准备关闭");
  63. applicationContext.close();
  64. System.out.println("applicationContext ..... 已关闭");
  65. }
  66. }
  67. 运行结果:
  68. 构造方法:BeanLife--->construct...
  69. BeanLife{name='张三'}
  70. bean后置处理器:MyBeanPostProcessor......postProcessBeforeInitialization
  71. bean后置处理器:MyBeanPostProcessor......postProcessAfterInitialization
  72. applicationContext ..... 初始化结束
  73. applicationContext ..... 准备关闭
  74. applicationContext ..... 已关闭

发表评论

表情:
评论列表 (有 0 条评论,385人围观)

还没有评论,来说两句吧...

相关阅读