【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.
	 * 

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) () -> { 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或者标签中指定的初始化方法 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; } //后置处理器--前置方法 @Override public 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; } //后置处理器--后置方法 处理方式都是会遍历所有的后置处理器,调用前置或后置方法 @Override public 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;
    }

    @Override
    public 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
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("bean后置处理器:MyBeanPostProcessor......postProcessBeforeInitialization");
        return bean;
    }

    @Nullable
    @Override
    public 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;
    }

    @Bean
    public 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,Spring)