Spring源码深度解析之Spring扩展点BeanPostProcessor和BeanFactoryPostProcessor简述

通常,应用程序开发人员不需要为ApplicationContext实现类提供子类。 相反,可以通过插入特殊集成接口的实现来扩展Spring IoC容器。Spring提供了两个非常重要的扩展接口BeanPostProcessor和BeanFactoryPostProcessor

  • BeanFactoryPostProcessor 主要是在对象实例化前对beanDefinition中的元数据进行修改并且BeanDefinitionRegistryPostProcessor继承BeanFactoryPostProcessor ,它的实现类ConfigurationClassPostProcessor完成了对类的扫描。


    image.png
  • BeanPostProcessor 主要是在对象实例化之后完成属性注入和AOP


    image.png

    image.png

使用BeanPostProcessor自定义Bean

BeanPostProcessor接口定义了回调方法,你可以实现这些回调方法以提供自己的(或覆盖容器的默认值)实例化逻辑,依赖关系解析逻辑等。 如果你想在Spring容器完成实例化,配置和初始化bean之后实现一些自定义逻辑,则可以插入一个或多个自定义BeanPostProcessor实现。

你可以配置多个BeanPostProcessor实例,并且可以通过设置order属性来控制这些BeanPostProcessor实例的执行顺序。 仅当BeanPostProcessor实现Ordered接口时,才可以设置此属性。 如果你编写自己的BeanPostProcessor,则也应该考虑实现Ordered接口。
BeanPostProcessor实例在对象实例化后执行。 即,Spring IoC容器实例化一个对象实例,然后BeanPostProcessor实例完成其它工作。 如果要更改实际的bean定义(即定义bean的元数据),你需要使用BeanFactoryPostProcessor

以编程方式注册BeanPostProcessor实例
虽然建议的BeanPostProcessor注册方法是通过ApplicationContext自动检测(如前所述),但是你可以使用addBeanPostProcessor方法以编程方式将其注册到ConfigurableBeanFactory。 当你需要在注册之前评估条件逻辑,甚至需要跨层次结构的上下文复制Bean后处理器时,这将非常有用。 但是请注意,以编程方式添加的BeanPostProcessor实例不遵守Ordered接口。 在这里,注册的顺序决定了执行的顺序。 还要注意,以编程方式注册的BeanPostProcessor实例始终在通过自动检测注册的实例之前进行处理,而不考虑任何明确的顺序。

image.png

BeanPostProcessor实例和AOP自动代理
实现BeanPostProcessor接口的类是特殊的,并且容器对它们的处理方式有所不同。 它们直接引用的所有BeanPostProcessor实例和Bean在启动时都会实例化,作为ApplicationContext特殊启动阶段的一部分。 接下来,以排序方式注册所有BeanPostProcessor实例,并将其应用于容器中的所有其他bean。 因为AOP自动代理是作为BeanPostProcessor本身实现的,所以BeanPostProcessor实例或它们直接引用的bean都不适合进行自动代理,因此,没有编织的切面。

用JDK动态代理说明BeanPostProcessor的基本使用

public class TransactionHandler implements InvocationHandler {

    private Object target;

    public  Object getProxyInstance(Object target){
        this.target = target;
        return Proxy.newProxyInstance(this.getClass().getClassLoader() , target.getClass().getInterfaces() , this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("open Transaction");
        method.invoke(target , args);
        System.out.println("close Transaction");
        return null;
    }
}
@Component
public class AOPBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Object aopBean = bean;
        if ("indexServiceImpl".equals(beanName)){
            TransactionHandler transactionHandler = new TransactionHandler();
             aopBean = transactionHandler.getProxyInstance(bean);
        }
        return aopBean;
    }
}

public interface IndexService {
    void query();
}

@Component("indexServiceImpl")
public class IndexServiceImpl implements IndexService {
    @Override
    public void query() {
        System.out.println("query data");
    }
}
public class Test {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Apppconfig.class);
        IndexService indexService = (IndexService) applicationContext.getBean("indexServiceImpl");
        indexService.query();
    }
}

输出结果

open Transaction
query data
close Transaction

使用BeanFactoryPostProcessor自定义配置元数据

我们要看的下一个扩展点是org.springframework.beans.factory.config.BeanFactoryPostProcessor该接口的语义与BeanPostProcessor的语义相似,但有一个主要区别:BeanFactoryPostProcessor对Bean配置元数据进行操作。 也就是说,Spring IoC容器允许BeanFactoryPostProcessor读取配置元数据,并有可能在容器实例化除BeanFactoryPostProcessor实例以外的任何bean之前更改它。

你可以配置多个BeanFactoryPostProcessor实例,并且可以通过设置order属性来控制这些BeanFactoryPostProcessor实例的运行顺序。 但是,仅当BeanFactoryPostProcessor实现Ordered接口时才能设置此属性。 如果您编写自己的BeanFactoryPostProcessor,则也应该考虑实现Ordered接口。

如果要更改实际的bean实例(即从配置元数据创建的对象),则需要使用BeanPostProcessor(在前面的使用BeanPostProcessor自定义Bean中进行了介绍)。 从技术上讲,可以在BeanFactoryPostProcessor中使用Bean实例(例如,通过使用BeanFactory.getBean()),但这样做会导致过早的Bean实例化,从而违反了标准容器的生命周期。 这可能会导致负面影响,例如绕过bean后处理。

Bean工厂后处理器在ApplicationContext中声明时会自动执行,以便将更改应用于定义容器的配置元数据。 Spring包含许多预定义的bean工厂后处理器,例如PropertyOverrideConfigurer和PropertySourcesPlaceholderConfigurer。 您还可以使用自定义BeanFactoryPostProcessor,例如注册自定义属性编辑器。

ApplicationContext自动检测实现BeanFactoryPostProcessor接口(ConfigurationClassPostProcessor也是实现BeanFactoryPostProcessor,但是通常会比其他实现BeanFactoryPostProcessor先执行除了以编程方式手动放入的BeanFactoryPostProcessor,ConfigurationClassPostProcessor会把其他类扫描出来也包括实现BeanFactoryPostProcessor的类,ConfigurationClassPostProcessor的细节我会在后续源码分析里面进行讲解),并应用到到其中的所有Bean。 它在适当的时候将这些bean用作bean工厂的后处理器(这里的bean只是被扫描出来,还没有实例化)。

覆盖Bean中的默认值来举例说明BeanFactoryPostProcessor的使用

@Component("simplePostProcessor")
public class SimplePostProcessor {

    private String connectionString = "bollocks";
    private String password = "imaginecup";
    private String username = "Microsoft";


    public String getConnectionString() {
        return connectionString;
    }

    public void setConnectionString(String connectionString) {
        this.connectionString = connectionString;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "SimplePostProcessor{" +
                "connectionString='" + connectionString + '\'' +
                ", password='" + password + '\'' +
                ", username='" + username + '\'' +
                '}';
    }
}
@Component
public class ObscenityBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        ScannedGenericBeanDefinition scannedGenericBeanDefinition = (ScannedGenericBeanDefinition) beanFactory.getBeanDefinition("simplePostProcessor");
        MutablePropertyValues propertyValues = scannedGenericBeanDefinition.getPropertyValues();
        propertyValues.addPropertyValue("password" , "*****");
        propertyValues.addPropertyValue("username" , "*****");
    }

}
public class Test {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Apppconfig.class);
        System.out.println(applicationContext.getBean("simplePostProcessor"));
    }
}

输出结果

SimplePostProcessor{connectionString='bollocks', password='*****', username='*****'}

你可能感兴趣的:(Spring源码深度解析之Spring扩展点BeanPostProcessor和BeanFactoryPostProcessor简述)