千家信息网

Spring源码中BeanPostProcessor的原理是什么

发表于:2024-10-14 作者:千家信息网编辑
千家信息网最后更新 2024年10月14日,今天就跟大家聊聊有关Spring源码中BeanPostProcessor的原理是什么,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。前提概要Sp
千家信息网最后更新 2024年10月14日Spring源码中BeanPostProcessor的原理是什么

今天就跟大家聊聊有关Spring源码中BeanPostProcessor的原理是什么,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

前提概要

Spring具有很好的扩展性,但是这个扩展它的这个扩展性体现在哪里呢?而我们要说的BeanPostProcessor就是对Spring扩展性优秀的表现之一。

BeanPostProcessor的作用

  • 简单的说就是BeanPostProcessor提供了初始化前后回调的方法,我们所说的扩展就是在实例化前后对Bean进行扩展

  • BeanDefinition注册完成之后进行注册,在创建Bean过程中的实例化前后分别调用其中定义的方法

其操作对象为:已经实例化且进行了属性填充,待初始化的Bean实例

源码分析

public interface BeanPostProcessor {  /**  * 初始前调用  */   @Nullable   default Object postProcessBeforeInitialization(Object bean, String beanName)            throws BeansException {      return bean;   }   /**   * 初始化后调用   */   @Nullable   default Object postProcessAfterInitialization(Object bean, String beanName)            throws BeansException {      return bean;   }}
  • 上面就是BeanPostProcessor接口的定义,从方法名字也能看出这两个方法一个在初始化前调用一个在初始化后调用。

  • 注意的是,方法的返回值为原始实例或者包装后的实例。如果返回null会导致后续的BeanPostProcessor不生效(BeanPostProcessor是可以注册多个的)

如何使用

BeanPostProcessorDemo代码如下:

public class BeanPostProcessorDemo {    public static void main(String[] args) {        //创建基础容器        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();        //加载xml配置文件        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);        reader.loadBeanDefinitions("spring-bean-post-processor.xml");        //添加BeanPostProcessor        beanFactory.addBeanPostProcessor(new UserBeanPostProcessor());        User user = beanFactory.getBean(User.class);        System.out.println(user);    }}@Dataclass User{    private String userName;    private Integer age;    private String beforeMessage;    private String afterMessage;            public void initMethod(){        System.out.println("初始化:"+this);        this.setUserName("小明");        this.setAge(18);    }}class UserBeanPostProcessor implements BeanPostProcessor{    @Override    public Object postProcessBeforeInitialization(Object bean, String beanName)                 throws BeansException {        if (bean instanceof User){            System.out.println("初始化前:"+bean);            ((User) bean).setBeforeMessage("初始化前信息");        }        return bean;    }    @Override    public Object postProcessAfterInitialization(Object bean, String beanName) throws                 BeansException {        if (bean instanceof User){            System.out.println("初始化后:"+bean);            ((User) bean).setAfterMessage("初始化后信息");        }        return bean;    }}

其他的省略......

运行之后打印结果如下:

初始化前:User(userName=null, age=null, beforeMessage=null, afterMessage=null)初始化:User(userName=null, age=null, beforeMessage=初始化前信息, afterMessage=null)初始化后:User(userName=小明, age=18, beforeMessage=初始化前信息, afterMessage=null)User(userName=小明, age=18, beforeMessage=初始化前信息, afterMessage=初始化后信息)

上面的代码很简单就是创建基础的容器,因为我这个里面用的是BeanFactory,BeanFactory作为基础容器是这里我采用手动将BeanPostProcessor注册到容器中去的。 同时也可以采用扫描或者定义的方式生成到容器中。

下面分析打印结果:

  1. 初始化前:User(userName=null, age=null, beforeMessage=null, afterMessage=null) 该结果是postProcessBeforeInitialization方法中输出的内容,这个时候User实例还只是进行了实例化,还未进行到初始化步骤,所以所有的属性都为null,说明该方法确实是初始化执行的。--(此时的初始化指的是bean对象的init方法)

  2. 初始化:User(userName=null, age=null, beforeMessage=初始化前信息, afterMessage=null) 该结果为自定义的初始化方法initMethod方法中输出的内容,这个时候User实例真正初始化,而beforeMessage中中的值正是我们在postProcessBeforeInitialization设置的

  3. 初始化后:User(userName=小明, age=18, beforeMessage=初始化前信息, afterMessage=null) 该结果是postProcessAfterInitialization中输出内容,从打印结果可以看出它的确是在自定义initMethod后。

Spring的生命周期

Spring中Bean总体上来说可以分为四个周期:实例化、属性赋值、初始化、销毁。而BeanPostProcessor则是在初始化阶段的前后执行。

  • 首先看AbstractAutowireCapableBeanFactorydoCreateBean方法,该方法实际就是创建指定Bean的方法。

    • 其中三个重要的方法调用如下:createBeanInstance、populateBean、initializeBean

    • 这三个方法分别代表了Spring Bean中的实例化、属性赋值和初始化三个生命周期。

BeanPostProcessor是在初始化前后调用所以我们查看initializeBean中的方法详情即可。该方法详情如下:

protected Object initializeBean(String beanName, Object bean, @Nullable                                                                 RootBeanDefinition mbd) {   //处理BeanNameAware、BeanClassLoaderAware、BeanFactoryAware   if (System.getSecurityManager() != null) {         AccessController.doPrivileged((PrivilegedAction) () -> {         invokeAwareMethods(beanName, bean);         return null;      }, getAccessControlContext());   }   else {      invokeAwareMethods(beanName, bean);   }   //处理BeanPostProcessor   Object wrappedBean = bean;   if (mbd == null || !mbd.isSynthetic()) {      //回调postProcessBeforeInitialization方法      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean,                                                                                                                                 beanName);   }   try {      //处理InitializingBean和BeanDefinition中指定的initMethod      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()) {      //回调postProcessAfterInitialization方法      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean,                                                                                                                            beanName);   }   return wrappedBean;}

从上面的源码可以看出首先是处理部分Aware相关接口,然后接着就是处理BeanPostProcessor中的postProcessBeforeInitialization方法,该方法详情如下:

public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)      throws BeansException {   Object result = existingBean;   //依次处理BeanPostProcessor   for (BeanPostProcessor processor : getBeanPostProcessors()) {      Object current = processor.postProcessBeforeInitialization(result, beanName);      //如果放回null,则直接返回后续BeanPostProcessor中的           // postProcessBeforeInitialization不再执行      if (current == null) {         return result;      }      result = current;   }   return result;}

该方法就是执行postProcessBeforeInitialization回调的详情内容,从该实现可以知道,BeanPostProcessor可以有多个,而且会按照顺序依次处理。如果只要其中的任意一个返回null,则后续的BeanPostProcessor的postProcessBeforeInitialization将不会再处理了。

接着就是执行初始化方法,即invokeInitMethods方法被调用。

protected void invokeInitMethods(String beanName, Object bean, @Nullable         RootBeanDefinition mbd)      throws Throwable {   boolean isInitializingBean = (bean instanceof InitializingBean);   if (isInitializingBean && (mbd == null ||                   !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {      if (logger.isTraceEnabled()) {         logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName +                    "'");      }      //如果当前Bean实现了InitializingBean接口则会执行它的afterPropertiesSet()方法      if (System.getSecurityManager() != null) {         try {            AccessController.doPrivileged((PrivilegedExceptionAction) () -> {               ((InitializingBean) bean).afterPropertiesSet();               return null;            }, getAccessControlContext());         }         catch (PrivilegedActionException pae) {            throw pae.getException();         }      }      else {         ((InitializingBean) bean).afterPropertiesSet();      }   }   //如果在BeanDefinition中定义了initMethod则执行初始化方法   if (mbd != null && bean.getClass() != NullBean.class) {      String initMethodName = mbd.getInitMethodName();      if (StringUtils.hasLength(initMethodName) &&            !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&            !mbd.isExternallyManagedInitMethod(initMethodName)) {         invokeCustomInitMethod(beanName, bean, mbd);      }   }}
  • 从上面代码也进一步验证了BeanPostProcessor中的postProcessBeforeInitialization方法的确是在初始化前调用。

  • 当invokeInitMethods执行之后接着就执行applyBeanPostProcessorsAfterInitialization方法。

@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;}

该方法与applyBeanPostProcessorsBeforeInitialization几乎就是相同的,不同的在于它执行的是postProcessAfterInitialization。至此Spring Bean的初始化也就完成了

???? @PostConstruct的支持

通过上面了解了Spring Bean生命周期中初始化的过程,但是实际上Spring对于JSR250也支持,例如对@PostConstruct注解的支持,但是在之前的源码中并没有发现Spring Bean的初始化过程中有所体现。

这里面的秘密就是我们的BeanPostProcessor了。

在Spring中有一个CommonAnnotationBeanPostProcessor类,这个类的注释中有说到这个类就是用来对JSR250及其他一些规范的支持。

下面我就通过这个类的源码来说明Spring是如何通过BeanPostProcessor来实现对@PostContruct的支持。

从上图中我们可以看出,CommonAnnotationBeanPostProcessor并没有直接对BeanPostProcessor有所实现,它继承InitDestroyAnnotationBeanPostProcessor该类,而对@PostConstruct的实现主要在该类中。

而对BeanPostProcessor的实现代码如下:

@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {   //生命周期元数据封装   LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());   try {      //执行InitMethods      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;}@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {   return bean;}

对BeanPostProcessor的实现主要在before方法中,该方法主要就是两部分内容,第一部分主要是信息封装到LifecycleMetadata中,便于后面第二步的执行相关初始化方法。

通过上面的方法实现我们知道了,Spring对JSR250的实现借助于BeanPostProcessor来实现的。

public class BeanPostProcessorDemo2 {    public static void main(String[] args) {        //创建基础容器        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();        //构建BeanDefinition并注册        AbstractBeanDefinition beanDefinition =                         BeanDefinitionBuilder.genericBeanDefinition(Person.class)                .getBeanDefinition();        beanFactory.registerBeanDefinition("person",beanDefinition);        //注册CommonAnnotationBeanPostProcessor        CommonAnnotationBeanPostProcessor commonAnnotationBeanPostProcessor                         = new CommonAnnotationBeanPostProcessor();        beanFactory.addBeanPostProcessor(commonAnnotationBeanPostProcessor);        //获取Bean        Person person = beanFactory.getBean(Person.class);        System.out.println(person);    }}class Person{    @PostConstruct    public void annotationInitMethod(){        System.out.println("@PostConstruct");    }}

上面的代码比较简单,我们定义一个Person并使用@PostConstruct标记出它的初始化方法,然后我们创建BeanFactory,并创建Person的BeanDefinition将其注册到BeanFactory(与读取配置文件一样),然后我们创建CommonAnnotationBeanPostProcessor并将其添加到BeanFactory中。

  • 最后打印结果打印出@PostConstruct。如果我们将下面这句代码注释。

  • beanFactory.addBeanPostProcessor(commonAnnotationBeanPostProcessor);

  • 再次执行可以发现,@PostConstruct将会失效,且最后不会打印出结果。

???? 顺序性

BeanPostProcessor是可以注册多个的,在AbstractBeanFactory内部通过List变量beanPostProcessors来存储BeanPostProcessor。而在执行时是按照List中BeanPostProcessor的顺序一个个执行的,所以我们在想容器中添加BeanPostProcessor时需要注意顺序。如果我们不是通过手动添加(大多数时候不是)时,而是在代码或者配置文件中定义多个BeanPostProcessor时,我们可以通过实现Ordered接口来控制它的顺序。

BeanPostProcessor依赖的Bean不会执行BeanPostProcessor BeanPostProcessor依赖的Bean是不会执行BeanPostProcessor的,这是因为在创建BeanPostProcessor之所依赖的Bean就需要完成初始化,而这个时候BeanPostProcessor都还未完初始化完成。


此外我们需要了解点:@PostConstruct 执行点(beforeInitialization) 要早于 afterProperitesSet(invokeInitMethod-1) 早于对应的Bean定义的initMethod(invokeinitiMethod-2)方法的执行。

实例代码如下:

public class App3 {    public static void main(String[] args) {        AnnotationConfigApplicationContext context = new                 AnnotationConfigApplicationContext();        context.scan("com.buydeem.beanpostprocessor");        context.register(App3.class);        context.refresh();    }}@Componentclass ClassA{}@Componentclass ClassB{}@Componentclass MyBeanPostProcessor implements BeanPostProcessor{    @Autowired    private ClassA classA;    @Override    public Object postProcessBeforeInitialization(Object bean, String beanName)                 throws BeansException {        System.out.println("MyBeanPostProcessor"+bean);        return bean;    }}

注意最后ClassA是不会打印出来的,而ClassB是会被打印出来。因为MyBeanPostProcessor依赖ClassA实例

总结

Spring中BeanPostProcessor的子接口或实现类有很多种,例如。

InstantiationAwareBeanPostProcessorMergedBeanDefinitionPostProcessorDestructionAwareBeanPostProcessor等等

这些接口分别处在Spring Bean生命周期的不同阶段,而他们的功能与BeanPostProcessor都类似,都是为了给Spring Bean各个声明周期提供扩展点。

看完上述内容,你们对Spring源码中BeanPostProcessor的原理是什么有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

0