欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2025/3/20 48 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【Spring注解系列11】Spring后置处理器BeanPostProcessor用法与原理 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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);

}

/*** Initialize the given bean instance, applying factory callbacks* as well as init methods and bean post processors.* <p>Called from {@link #createBean} for traditionally defined beans,* and from {@link #initializeBean} for existing bean instances.* @param beanName the bean name in the factory (for debugging purposes)* @param bean the new bean instance we may need to initialize* @param mbd the bean definition that the bean was created with* (can also be {@code null}, if given an existing bean instance)* @return the initialized bean instance (potentially wrapped)* @see BeanNameAware* @see BeanClassLoaderAware* @see BeanFactoryAware* @see #applyBeanPostProcessorsBeforeInitialization* @see #invokeInitMethods* @see #applyBeanPostProcessorsAfterInitialization*/protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {if (System.getSecurityManager() != null) {AccessController.doPrivileged((PrivilegedAction<Object>) () -> {invokeAwareMethods(beanName, bean);return null;}, getAccessControlContext());}else {//调用实现XXAware接口的方法invokeAwareMethods(beanName, bean);}Object wrappedBean = bean;if (mbd == null || !mbd.isSynthetic()) {//后置处理器--前置方法wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);}try {//调用@bean或者<bean>标签中指定的初始化方法invokeInitMethods(beanName, wrappedBean, mbd);}catch (Throwable ex) {throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null),beanName, "Invocation of init method failed", ex);}if (mbd == null || !mbd.isSynthetic()) {//后置处理器--后置方法wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);}return wrappedBean;}//后置处理器--前置方法@Overridepublic Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)throws BeansException {Object result = existingBean;for (BeanPostProcessor processor : getBeanPostProcessors()) {Object current = processor.postProcessBeforeInitialization(result, beanName);if (current == null) {return result;}result = current;}return result;}//后置处理器--后置方法 处理方式都是会遍历所有的后置处理器,调用前置或后置方法@Overridepublic Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)throws BeansException {Object result = existingBean;for (BeanPostProcessor processor : getBeanPostProcessors()) {Object current = processor.postProcessAfterInitialization(result, beanName);if (current == null) {return result;}result = current;}return result;}

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

Spring底层对 BeanPostProcessor 的使用;

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

 

3.BeanPostProcessor 使用

 

public class BeanLife {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "BeanLife{" +"name='" + name + '\'' +'}';}public BeanLife() {System.out.println("构造方法:BeanLife--->construct...");}}/*** @author tuchuanbiao* @Date 2019/4/3 19:58** 后置处理器:初始化前后进行处理工作* 将后置处理器加入到容器中** 这里采用@Bean方式注入,也可以直接使用@Component*/ //@Component //一定要将后置处理器注入到容器中 public class MyBeanPostProcessor implements BeanPostProcessor {@Nullable@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {System.out.println("bean后置处理器:MyBeanPostProcessor......postProcessBeforeInitialization");return bean;}@Nullable@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {System.out.println("bean后置处理器:MyBeanPostProcessor......postProcessAfterInitialization");return bean;} }@Configuration public class BeanLifeCycleConfig {@Bean(value = "beanLife")public BeanLife life() {BeanLife beanLife = new BeanLife();beanLife.setName("张三");System.out.println(beanLife);return beanLife;}@Beanpublic MyBeanPostProcessor myBeanPostProcessor(){return new MyBeanPostProcessor();} }//测试类public class BeanLifeCycleTest {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanLifeCycleConfig.class);System.out.println("applicationContext ..... 初始化结束");System.out.println("applicationContext ..... 准备关闭");applicationContext.close();System.out.println("applicationContext ..... 已关闭");}}运行结果: 构造方法:BeanLife--->construct... BeanLife{name='张三'} bean后置处理器:MyBeanPostProcessor......postProcessBeforeInitialization bean后置处理器:MyBeanPostProcessor......postProcessAfterInitialization applicationContext ..... 初始化结束 applicationContext ..... 准备关闭 applicationContext ..... 已关闭

 

总结

以上是生活随笔为你收集整理的【Spring注解系列11】Spring后置处理器BeanPostProcessor用法与原理的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。