BeanFactoryPostProcessor 和 BeanPostProcessor

基本概念

BeanFactoryPostProcessor 是一个后置处理器,在Spring中,后置处理器大致可以分为两类:

  • BeanFactoryPostProcessor
  • BeanPostProcessor
    前者主要是用来处理 BeanDefinition,即一个 Bean 的配置完全被加载了,已经生成了 BeanDefinition,但是还没有生成具体的 Bean,此时 BeanFactoryPostProcessor 会介入,介入之后可以对 BeanDefinition 进行处理;而 BeanPostProcessor 则是在一个具体的 Bean 生成之后,才会介入,对已经生成的 Bean 进行修改。

BeanFactoryPostProcessor

简单实践

如果在 Bean 创建的过程中,当 BeanDefinition 创建完毕,Bean 尚未创建的时候,想要去修改 Bean 的属性,那么就可以通过 BeanFactoryPostProcessor 来实现,直接定义 BeanFactoryPostProcessor 即可,定义好的 BeanFactoryPostProcessor 会针对当前项目中的所有 Bean 生效:

/**
 * 这个后置处理器定义好之后,会对所有的 Bean 生效
 */
public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
	/**
	 * 这个接口就是用来处理 beanDefinition 的,此时各个对象的 beanDefinition 都已经收集好,但是还没有创建 Bean 对象
	 * 相当于我们在正式创建 Bean 对象之前,先把 BeanDefintion 中的属性值给篡改了,这样,将来创建出来的 Bean 对象的值就是修改后的属
	 *
	 * @param beanFactory the bean factory used by the application context
	 * @throws BeansException
	 */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("BeanFactoryPostProcessor执行了...");
        String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames){
            BeanDefinition bd = beanFactory.getBeanDefinition(beanDefinitionName);
            //创建一个 BeanDefinitionVisitor 对象,这个对象可以用来访问并修改 BeanDefinition 中的属性值
 			//假设我一会给一个 bean 设置属性值为 NB,如果我发现 bean 的属性名是 hok,我就将之改为 NB
            BeanDefinitionVisitor beanDefinitionVisitor = new BeanDefinitionVisitor(strVal -> {
                if ("hok".equals(strVal)) {
                    return "NB";
                }
                //对于其他的属性值,原封不动返回即可
                return strVal;
            });
            //更新 BeanDefinition 对象,其实就是将 visitor 中的属性值,重新赋值到原本的 BeanDefinition 上去
            beanDefinitionVisitor.visitBeanDefinition(bd);
        }
    }
}

最后将这个 Bean 注册到 Spring 容器中即可,注册成功之后,他就会生效,不需要任何额外的配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="org.example.demo.User" id="user">
        <property name="id" value="1" />
        <property name="name" value="hok" />
    </bean>
    <bean class="org.example.demo.CustomBeanFactoryPostProcessor" />
</beans>
public class User {
    private String name;
    private int id;

    public User() {
        System.out.println("user构造方法执行了...");
    }
    // set get...
}

启动类,使用 加载 xml 方式

public class App {
    public static void main(String[] args) {
        // 加载 xml 方式,默认的beanDefinition实现
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        User user = ctx.getBean(User.class);
        System.out.println("user = " + user);
    }
}

输出如下,发现 name 属性值确实被修改了
在这里插入图片描述
注意:上述对 BeanFactoryPostProcessor 的使用是基于 xml 方式来做的,如果想改成 java 配置的方式会发现属性改不了,原因这篇文章有写

BeanFactoryPostProcessor 典型应用

在整合 JDBC 的时候,经常要配置数据库密码 URL之类的,类似一个db.properties文件

db.username=root
db.password=root
db.url=jdbc:mysql:///$db$?serverTimezone=Asia/Shanghai

然后在 XML 文件中加载该配置并使用:

<context:property-placeholder location="classpath:db.properties"/>
<bean class="org.javaboy.demo.DataSource" id="dataSource">
 <property name="url" value="${db.url}"/>
 <property name="username" value="${db.username}"/>
 <property name="password" value="${db.password}"/>
</bean>

那么系统在读取配置文件的时候,首先读取到的 DataSource 中配置的各个属性的 value 就是 XML 文件中的 value,然后这个配置会经过一个BeanFactoryPostProcessor 后置处理器,在这个后置处理器中,会找到所有的 ${} 格式的 value,并将之替换为真正的值,后面再去创建 bean 的时候,用到的就是真实的值了。

context:property-placeholder 这种写法该如何理解?正常来说,我们向 Spring 容器中都是去注册 Bean 的,按理说配置应该是一个一个的 Bean 标签,但是!有时候对于某一些 Bean,我们希望能够有一些默认的配置,那么这些默认的配置就可以通过自定义标签来实现,
context:property-placeholder 这种写法实际上就是一个自定义标签,在这个标签中,会进行一些默认的 Bean 属性的配置,但是,一般来说,这些属性,如果想要自己去配置,也是可以的,比如 ignore-unresolvable

<context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/>

这个属性配置的含义表示,对于无法解析的 value,就不解析(默认情况下,如果遇到无法解析的 value,会抛出异常)。当然,如果我们明白了 context:property-placeholder 的本质(其实还是 Bean 的配置),那么也可以不使用这种自定义标签,而是直接自己手动去配置 Bean,像下面这样,等价于 context:property-placeholder

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
 <property name="location" value="classpath:db.properties"/>
 <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>

而从类的继承关系上可以看出,PropertySourcesPlaceholderConfigurer 类实现了 BeanFactoryPostProcessor 接口并重写了接口中的 postProcessBeanFactory 方法:
在这里插入图片描述

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	//首先这个 propertySources 实际上就是我们的各种配置的 properties 资源。整体上分为两类:localProperties 和 environmentProperties
	//localProperties 是属于开发者自定义的各种 properties,例如我们前面写的 db.properties 就属于这一类
	//environmentProperties 是系统的环境变量信息,即 Spring 会读取到当前电脑的环境变量,并将之注入到 propertySources 里边来
    if (this.propertySources == null) {
		 //第一次加载的时候,propertySources 为 null,此时就要去初始化,并为之赋值
        this.propertySources = new MutablePropertySources();
        //如果环境变量对象不为 null,那么就从中读取 properties 出来
        if (this.environment != null) {
            final PropertyResolver propertyResolver = this.environment;
            if (this.ignoreUnresolvablePlaceholders && this.environment instanceof ConfigurableEnvironment) {
                ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment)this.environment;
                PropertySourcesPropertyResolver resolver = new PropertySourcesPropertyResolver(configurableEnvironment.getPropertySources());
                resolver.setIgnoreUnresolvableNestedPlaceholders(true);
                propertyResolver = resolver;
            }
			//将加载到的环境变量的信息存入到 propertySources 里边来
            this.propertySources.addLast(new PropertySource<Environment>("environmentProperties", this.environment) {
                @Nullable
                public String getProperty(String key) {
                    return ((PropertyResolver)propertyResolver).getProperty(key);
                }
            });
        }

        try {
        	//这里就是去加载本地的 properties 配置
            PropertySource<?> localPropertySource = new PropertiesPropertySource("localProperties", this.mergeProperties());
            //是否本地覆盖,如果为 true,就表示使用本地配置覆盖掉环境变量中的信息(如果环境变量中有 key 和本地配置中的 key 重复了
 			//默认情况下,localOverride 变量值为 false,即本地的 properties 配置,不会覆盖环境变量中的配置
            if (this.localOverride) {
           		 //将本地的添加到 list 集合的最前面,这样将来读取的时候,就优先读取到本地配置,相当于本地配置覆盖掉了环境变量配置
                this.propertySources.addFirst(localPropertySource);
            } else {
                this.propertySources.addLast(localPropertySource);
            }
        } catch (IOException var5) {
            throw new BeanInitializationException("Could not load properties", var5);
        }
    }
	// 接下来在 processProperties 方法进一步处理:
    this.processProperties(beanFactory, (ConfigurablePropertyResolver)(new PropertySourcesPropertyResolver(this.propertySources)));
    this.appliedPropertySources = this.propertySources;
}
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, final ConfigurablePropertyResolver propertyResolver) throws BeansException {
    propertyResolver.setPlaceholderPrefix(this.placeholderPrefix);
    propertyResolver.setPlaceholderSuffix(this.placeholderSuffix);
    propertyResolver.setValueSeparator(this.valueSeparator);
    //这个解析器就是核心了,在这里将 ${xxx} 转为具体的值
    StringValueResolver valueResolver = (strVal) -> {
        String resolved = this.ignoreUnresolvablePlaceholders ? propertyResolver.resolvePlaceholders(strVal) : propertyResolver.resolveRequiredPlaceholders(strVal);
        if (this.trimValues) {
            resolved = resolved.trim();
        }
        return resolved.equals(this.nullValue) ? null : resolved;
    };
    //这个方法里边就是创建访问器,在访问器中,将 valueResolver 传入,对各个使用了占位符 ${xxx} 的 value 进行解析。
    this.doProcessProperties(beanFactoryToProcess, valueResolver);
}

BeanFactoryPostProcessor 和 BeanDefinitionRegistryPostProcessor

BeanDefinitionRegistryPostProcessor 本质上也是个BeanFactoryPostProcessor,从源码可以看到,多了个方法,说明这个类是为 BeanDefinitionRegistry 服务的,作为 BeanDefinitionRegistry 的后置处理器,它的执行时机比 BeanFactoryPostProcessor 稍早些

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
    void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

    default void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }
}

BeanPostProcessor

BeanPostProcessor 接口中存在两个方法,一个大的前提,就是两个方法都是在 Bean 创建成功之后执行的,具体到方法上,postProcessBeforeInitialization 是在 bean 的初始化方法 afterPropertiesSetinit-method 方法之前执行,而 postProcessAfterInitialization 则是在这两个初始化方法之后执行。

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

简单实践

来实践一下,接下来需要对 Book 对象修改其属性

public class CustomBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if ("book".equals(beanName)) {
            Book book = (Book) bean;
            book.setId(111);
            return book;
        }
       return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if ("book".equals(beanName)) {
            Book book = (Book) bean;
            book.setName("金瓶梅");
            book.setPrice(666d);
            return book;
        }
        //如果是其他类型的 bean,则直接返回对象即可
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }
}
public class Book {
  private String name;
  private Double price;
  private Integer id;
   // set get 方法
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean class="org.example.demo.Book" id="book" >
        <property name="id" value="0" />
        <property name="name" value="hok" />
        <property name="price" value="77d" />
    </bean>
    <bean class="org.example.demo.CustomBeanPostProcessor" />
</beans>

输出结果如下
在这里插入图片描述
注意:上面是使用 xml 形式,BeanPostProcessor 注解也是可以生效的

AOP 简单实践

Spring 中有非常多的功能是通过 BeanPostProcessor 来实现的,其中最为经典的是 AOP。AOP 需要先创建一个原始的 Bean,原始 Bean 创建成功之后,就是在 BeanPostProcessor 中,对原始 Bean 生成代理对象并返回。

在这里插入图片描述

  • 26
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值