@postconstruct注解_Spring注解驱动开发之七——BeanPostProcessor 执行原理、在spring 中的应用...

f88cd89249cee6fe0077ab34453611a5.png

本文包含以下内容:

  1. BeanPostProcessor 执行原理

    1. 断点查看 

    2. 总结运行过程中的执行原理
  2. BeanPostProcessor 在spring 中的应用

    1. ApplicationContextAwareProcessor 帮助组件注入IOC 容器

    2. InitDestroyAnnotationBeanPostProcessor 用于处理 @PostConstruct 、@PreDestroy 注解

    3. BeanValidationPostProcessor 数据校验

1.BeanPostProcessor 执行原理

1)断点查看代码 1.在MyBeanPostProcessor添加断点,运行测试方法通过观察栈,查看执行流程

09b0a7d1a0119f2000af1ee33955d86c.png

下方长长的英文是调试中右下角的窗口:

38f6b74f2e5ac969a09c70d2bdb011d5.png

2. :84, AnnotationConfigApplicationContext 初始化容器
public AnnotationConfigApplicationContext(Class>... annotatedClasses) {    this();    register(annotatedClasses);    refresh();  }
3. refresh:543, AbstractApplicationContext  调用refresh() 函数 ,实例化所有剩余的单例
// Instantiate all remaining (non-lazy-init) singletons.        finishBeanFactoryInitialization(beanFactory);
4 .finishBeanFactoryInitialization:867, AbstractApplicationContext 
// Instantiate all remaining (non-lazy-init) singletons.    beanFactory.preInstantiateSingletons();
preInstantiateSingletons:761, DefaultListableBeanFactory,具体通过getBean函数进行初始化剩余的Bean
getBean(beanName);
5. doGetBean:302, AbstractBeanFactory 这一步 通过getSingleton  获取单实例, 通过初始化createBean 方法创建Bean
// Create bean instance.        if (mbd.isSingleton()) {          sharedInstance = getSingleton(beanName, new ObjectFactory() {            @Override            public Object getObject() throws BeansException {              try {                return createBean(beanName, mbd, args);              }              catch (BeansException ex) {                // Explicitly remove instance from singleton cache: It might have been put there                // eagerly by the creation process, to allow for circular reference resolution.                // Also remove any beans that received a temporary reference to the bean.                destroySingleton(beanName);                throw ex;              }            }          });          bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);        }
6. createBean:483, AbstractAutowireCapableBeanFactory,调用初始化,获取Bean 实例
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
7. doCreateBean:555, AbstractAutowireCapableBeanFactory 进入到具体创建Bean 中 通过populateBean() 进行填充Bean 操作
Object exposedObject = bean;    try {      populateBean(beanName, mbd, instanceWrapper);      if (exposedObject != null) {        exposedObject = initializeBean(beanName, exposedObject, mbd);      }    }
8.最后可以看到 initializeBean:1620, AbstractAutowireCapableBeanFactory 中 执行 applyBeanPostProcessorsBeforeInitialization 和 applyBeanPostProcessorsAfterInitialization 进行 postProcessBeforeInitialization() 函数和postProcessAfterInitialization() 函数的调用;中间调用 invokeInitMethods(beanName, wrappedBean, mbd) ;进行 初始化 函数的调用
Object wrappedBean = bean;    if (mbd == null || !mbd.isSynthetic()) {      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);    }    try {      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);    }
9. applyBeanPostProcessorsBeforeInitialization:409,AbstractAutowireCapableBeanFactory 最后通过 getBeanPostProcessors() 扫描所有的  BeanPostProcessor  直到遇到null 进行返回退出循环
@Override  public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)      throws BeansException {    Object result = existingBean;    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {      result = beanProcessor.postProcessBeforeInitialization(result, beanName);      if (result == null) {        return result;      }    }    return result;  }
2) 总结 运行过程中的执行原理通过查看断点调试结果, 可以看到,创建单例容器Bean 通过
populateBean() 函数进行填充,invokeInitMethods(beanName, wrappedBean, mbd);

函数进行初始化,然后前后有applyBeanPostProcessorsBeforeInitialization 和applyBeanPostProcessorsAfterInitialization 进行对所有的BeanPostProcessor 扫描执行。

2.BeanPostProcessor 在spring 中的应用

在spring 中大量使用BeanPostProcessor  ,进行处理,下面举例3个进行断点、代码测试:1).ApplicationContextAwareProcessor 帮助组件注入IOC 容器在Dog 中实现 implements ApplicationContextAware 接口,编写, setApplicationContext 将容器保存至属性方法中
@Componentpublic class Dog implements ApplicationContextAware {  private ApplicationContext applicationContext;  public Dog(){    System.out.println("dog constructor...");  }  @Override  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {    // TODO Auto-generated method stub    this.applicationContext = applicationContext;  }}
1. postProcessBeforeInitialization:97,ApplicationContextAwareProcessor 可以看到 通过 postProcessBeforeInitialization 函数进行将容器进行赋值

2.通过invokeAwareInterfaces判断Bean 的类型进行类型转换,并进行赋值

private void invokeAwareInterfaces(Object bean) {    if (bean instanceof Aware) {      if (bean instanceof EnvironmentAware) {        ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());      }      if (bean instanceof EmbeddedValueResolverAware) {        ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);      }      if (bean instanceof ResourceLoaderAware) {        ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);      }      if (bean instanceof ApplicationEventPublisherAware) {        ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);      }      if (bean instanceof MessageSourceAware) {        ((MessageSourceAware) bean).setMessageSource(this.applicationContext);      }      if (bean instanceof ApplicationContextAware) {        ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);      }    }  }
2).InitDestroyAnnotationBeanPostProcessor 用于处理 @PostConstruct 、@PreDestroy 注解。查看 InitDestroyAnnotationBeanPostProcessor  源码, postProcessBeforeInitialization 函数代码,如下:
@Override  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {    LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());    try {      metadata.invokeInitMethods(bean, beanName);    }    catch (InvocationTargetException ex) {      throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());    }    catch (Throwable ex) {      throw new BeanCreationException(beanName, "Failed to invoke init method", ex);    }    return bean;  }
使用 findLifecycleMetadata(bean.getClass()); 获取所有的生命周期函数,通过 metadata.invokeInitMethods(bean, beanName); 进行代理调用对应的生命周期函数
public void invokeInitMethods(Object target, String beanName) throws Throwable {   Collection initMethodsToIterate =         (this.checkedInitMethods != null ? this.checkedInitMethods : this.initMethods);   if (!initMethodsToIterate.isEmpty()) {      boolean debug = logger.isDebugEnabled();      for (LifecycleElement element : initMethodsToIterate) {         if (debug) {            logger.debug("Invoking init method on bean '" + beanName + "': " + element.getMethod());         }         element.invoke(target);      }   }}
3).BeanValidationPostProcessor 数据校验用于进行数据校验,查看 BeanValidationPostProcessor 的源码 postProcessBeforeInitialization 和 postProcessAfterInitialization 代码如下,进行 doValidate()函数进行数据校验。
@Override  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {    if (!this.afterInitialization) {      doValidate(bean);    }    return bean;  }  @Override  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {    if (this.afterInitialization) {      doValidate(bean);    }    return bean;  }

-END-

f3b40aa3625dff44845978ae62ec4ac0.png

可以关注我的公众号,免费获取价值1980元学习资料

点击“在看”,学多少都不会忘~

8744d74aa3b2b1c0dd8bfb2dffc736a2.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值