欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring中的BeanPostProcessor

程序员文章站 2022-07-14 16:06:22
...
/**
 *   实现BeanPostProcessor的类常用功能都有哪些
 *      InitDestroyAnnotationBeanPostProcessor:init和destroy方法的后处理,包括@PostConstruct和@PreDestroy注解
 *      AutowiredAnnotationBeanPostProcessor:处理含有@Autowired注解的参数注入
 *      ApplicationContextAwareProcessor:处理postProcessBeforeInitialization方法
 *      AsyncAnnotationBeanPostProcessor:处理@Async注解
 *      BeanValidationPostProcessor:参数校验
 *
 */

 

类实现BeanPostProcessor接口,并重写postProcessBeforeInitialization和postProcessAfterInitialization方法,将类注册到IOC容器中,这两个方法会在每一个组建被创建时都被调用

postProcessBeforeInitialization:在构造方法之后,初始化方法执行之前被调用
postProcessAfterInitialization:在初始化方法执行之后被调用

下面是具体的代码

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    //bean是当前组建,beanName是当前组建在容器中的id
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization->" + bean + "->" + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization->" + bean + "->" + beanName);
        return bean;
    }
}

当这个容器被注册到容器中时,方法被调用的顺序如下面

Construct->postProcessBeforeInitialization->Init->postProcessAfterInitialization->Destroy

原理:

下面是源码中调用方法的顺序:

    /**
     * populateBean(实例化bean并为其赋值)
     * {
     *     applyBeanPostProcessorsBeforeInitialization
     *     invokeInitMethods(反射调用初始化方法)
     *     applyBeanPostProcessorsAfterInitialization
     * }
     */