Spring提供了很多扩展接口,BeanPostProcessor接口和InstantiationAwareBeanPostProcessor接口就是其中两个。

BeanPostProcessor

BeanPostProcessor接口作用是:如果我们需要在Spring容器完成Bean的实例化、配置和其他的初始化前后添加一些自己的逻辑处理,我们就可以定义一个或者多个BeanPostProcessor接口的实现,然后注册到容器中。

Spring中Bean的实例化过程图示:

由上图可以看到,Spring中的BeanPostProcessor在实例化过程处于的位置,BeanPostProcessor接口有两个方法需要实现:postProcessBeforeInitialization和postProcessAfterInitialization,

Java代码

  1. import org.springframework.beans.factory.config.BeanPostProcessor;
  2. public class MyBeanPostProcessor implements BeanPostProcessor {
  3. public MyBeanPostProcessor() {
  4. super();
  5. System.out.println("这是BeanPostProcessor实现类构造器!!");
  6. }
  7. @Override
  8. public Object postProcessAfterInitialization(Object bean, String arg1)
  9. throws BeansException {
  10. System.out.println("bean处理器:bean创建之后..");
  11. return bean;
  12. }
  13. @Override
  14. public Object postProcessBeforeInitialization(Object bean, String arg1)
  15. throws BeansException {
  16. System.out.println("bean处理器:bean创建之前..");
  17. return bean;
  18. }
  19. }

BeanPostProcessor接口定义如下:

Java代码

  1. public interface BeanPostProcessor {
  2. /**
  3. * Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
  4. * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
  5. * or a custom init-method). The bean will already be populated with property values.
  6. */
  7. //实例化、依赖注入完毕,在调用显示的初始化之前完成一些定制的初始化任务
  8. Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
  9. /**
  10. * Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
  11. * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
  12. * or a custom init-method). The bean will already be populated with property values.
  13. */
  14. //实例化、依赖注入、初始化完毕时执行
  15. Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
  16. }

由方法名字也可以看出,前者在实例化及依赖注入完成后、在任何初始化代码(比如配置文件中的init-method)调用之前调用;后者在初始化代码调用之后调用。

注意:

1、接口中的两个方法都要将传入的bean返回,而不能返回null,如果返回的是null那么我们通过getBean方法将得不到目标。

2、BeanFactory和ApplicationContext对待bean后置处理器稍有不同。ApplicationContext会自动检测在配置文件中实现了BeanPostProcessor接口的所有bean,并把它们注册为后置处理器,然后在容器创建bean的适当时候调用它,因此部署一个后置处理器同部署其他的bean并没有什么区别。而使用BeanFactory实现的时候,bean 后置处理器必须通过代码显式地去注册,在IoC容器继承体系中的ConfigurableBeanFactory接口中定义了注册方法:

Java代码

  1. /**
  2. * Add a new BeanPostProcessor that will get applied to beans created
  3. * by this factory. To be invoked during factory configuration.
  4. * <p>Note: Post-processors submitted here will be applied in the order of
  5. * registration; any ordering semantics expressed through implementing the
  6. * {@link org.springframework.core.Ordered} interface will be ignored. Note
  7. * that autodetected post-processors (e.g. as beans in an ApplicationContext)
  8. * will always be applied after programmatically registered ones.
  9. * @param beanPostProcessor the post-processor to register
  10. */
  11. void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);

另外,不要将BeanPostProcessor标记为延迟初始化。因为如果这样做,Spring容器将不会注册它们,自定义逻辑也就无法得到应用。假如你在<beans />元素的定义中使用了'default-lazy-init'属性,请确信你的各个BeanPostProcessor标记为'lazy-init="false"'。

InstantiationAwareBeanPostProcessor

InstantiationAwareBeanPostProcessor是BeanPostProcessor的子接口,可以在Bean生命周期的另外两个时期提供扩展的回调接口,即实例化Bean之前(调用postProcessBeforeInstantiation方法)和实例化Bean之后(调用postProcessAfterInstantiation方法),该接口定义如下:

Java代码

  1. package org.springframework.beans.factory.config;
  2. import java.beans.PropertyDescriptor;
  3. import org.springframework.beans.BeansException;
  4. import org.springframework.beans.PropertyValues;
  5. public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
  6. Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;
  7. boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;
  8. PropertyValues postProcessPropertyValues(
  9. PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
  10. throws BeansException;
  11. }

其使用方法与上面介绍的BeanPostProcessor接口类似,只时回调时机不同。

如果是使用ApplicationContext来生成并管理Bean的话则稍有不同,使用ApplicationContext来生成及管理Bean实例的话,在执行BeanFactoryAware的setBeanFactory()阶段后,若Bean类上有实现org.springframework.context.ApplicationContextAware接口,则执行其setApplicationContext()方法,接着才执行BeanPostProcessors的ProcessBeforeInitialization()及之后的流程。

Spring中BeanPostProcessor相关推荐

  1. 【Spring】Spring中BeanPostProcessor

    1.概述 转载:Spring中BeanPostProcessor 对文章:SpringBoot : 定制化Bean的利器:BeanPostProcessor & BeanFactoryPost ...

  2. Spring中BeanPostProcessor 执行过程

    1.刷新容器 2.在refresh()方法中 执行 // Instantiate all remaining (non-lazy-init) singletons. // 初始化剩下的非延迟加载(no ...

  3. Spring中的后置处理器BeanPostProcessor讲解

    Spring中提供了很多PostProcessor供开发者进行拓展,例如:BeanPostProcessor.BeanFactoryPostProcessor.BeanValidationPostPr ...

  4. 9种设计模式在Spring中的运用,一定要非常熟练!

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 作者:iCoding91 https://blog.csdn.ne ...

  5. 一文读懂Spring中的AOP机制

    一.前言 这一篇我们来说一下 Spring 中的 AOP 机制,为啥说完注解的原理然后又要说 AOP 机制呢? 1.标记日志打印的自定义注解 @Target({ElementType.METHOD}) ...

  6. Spring 中的各种注解,光会用可不够哦!

    来源:https://digdeep.cnblogs.com/digdeep/p/4525567.html 1. Java中的注解 2. 使用 元注解 来自定义注解 和 处理自定义注解 3. spri ...

  7. spring中那些让你爱不释手的代码技巧

    紧接上文<spring中这些能升华代码的技巧,可能会让你爱不释手>.本文继续总结我认为spring中还不错的知识点,希望对您有所帮助. 一. @Conditional的强大之处 不知道你们 ...

  8. spring中这些能升华代码的技巧,可能会让你爱不释手

    前言 最近越来越多的读者认可我的文章,还是件挺让人高兴的事情.有些读者私信我说希望后面多分享spring方面的文章,这样能够在实际工作中派上用场.正好我对spring源码有过一定的研究,并结合我这几年 ...

  9. 【Spring源码】Spring中的AOP底层原理分析

    AOP中的几个概念 Advisor 和 Advice Advice,我们通常都会把他翻译为通知,其实很不好理解,其实他还有另外一个意思,就是"建议",我觉得把Advice理解为&q ...

最新文章

  1. Halcon算子翻译——while
  2. Linux下两个进程可以同时打开同一个文件,这时如下描述错误的是:
  3. 如何在SQL Server中使用触发器
  4. Oracle数据库实用脚本
  5. apache起步命令加-k参数和不加的区别
  6. pdf转换成可在线浏览的电子杂志zmaker_pdf
  7. 一位程序员 8 年的物联网奋斗史
  8. 《深入浅出统计学》笔记二--第二章:集中趋势的量度,第三章:分散性与变异性的量度
  9. 掩膜裁剪tif步骤_ENVI中掩膜掩膜操作及影像分类教程
  10. “奋斗者”号下潜10909米:我们为什么要做深海探索?
  11. 游戏建模:模型场景制作过程分享
  12. 冷静 仔细 认真 分析
  13. Java集合(一):集合的概念
  14. Tailscale组成局域网(以文明6联机为例)
  15. 无力回天...机关算尽,还是死在上线之中.............
  16. 3.5mm耳机、麦克风的插座、插头定义
  17. Windows 系统错代码
  18. 【备战2020】高考数学全套知识点
  19. 2022年全国职业技能大赛网络安全竞赛试题B模块自己解析思路(2)
  20. VsCode插件之vscode-icons

热门文章

  1. C语言二叉搜索树返回key的树级(附完整源码)
  2. QT绘制堆叠水平条形图
  3. QT的QParameter类的使用
  4. c++STL容器的Vector
  5. mysql5.5 配置_MySQL5.5 安装配置方法教程
  6. android自定义url协议,Android自定义URL方案…?
  7. MapReduce原理与设计思想(转载:http://blog.jobbole.com/80619/)
  8. Oracle数据库表信息,序列,视图等导出,导入。(数据库备份和恢复)
  9. 用 Freemarker 生成 word 文档
  10. 2进程之间的关系:进程组,会话,守护进程