Spring中的后置处理器BeanPostProcessor讲解一
1、概念
Spring允许自定义一个后置处理器来对对象初始化前后进行操作。
2、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;
}
3、适用场景
如:需要统计某个方法调用量
4、撸代码
package com.test.spring.pojo;
public class User {
private String id;
private String name;
public User() {
System.out.println("\033[32;4m" + "User被实例化。" + "\033[0m");
}
public void init() {
System.out.println("\033[32;4m" + "init方法被执行。" + "\033[0m");
}
}
package com.test.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class PostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("\033[32;4m" + "before--实例化的bean对象:"+bean+"\t"+beanName + "\033[0m");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("\033[32;4m" + "after...实例化的bean对象:"+bean+"\t"+beanName + "\033[0m");
return bean;
}
}
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.test.spring.pojo.User" id="user" init-method="init"> </bean>
<!-- 注册处理器 -->
<bean class="com.test.spring.PostProcessor"></bean>
</beans>
4、多个后置处理器
Spring默认情况下,会根据配置文件的从上到下依次调用或者是通过实现接口Ordered来指定执行顺序(默认值为 0,优先级最高,值越大优先级越低)。