后置处理Bean
01 基础信息
1. 全称 : BeanPostProcessor
2. 作用 : 对Spring工厂所创建的对象,进行在加工
3. 会对 Spring 工厂中的所有对象进行加工
02 运行原理
两个参数
Object bean
:刚刚创建好的对象String beanName
: 对象的id
值
返回值
- 加工好的对象
方法一
- 作用:Spring创建完成对象之后,进行注入之后,可以运行 **Before方法 **进行加工
Object postProcessBeforeInitialization(Object bean, String beanName)
方法二
- 作用:Spring执行完对象的初始化操作,可以运行 **After方法 **进行加工
Object postProcessAfterInitialization(Object bean, String beanName)
03 开发步骤
3.1 实现BeanPostProcessor
package com.spring.test;
import com.spring.model.Address;
import com.spring.model.User;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("---------加工-------------");
if(bean instanceof com.spring.model.User){
User user = (User) bean;
user.setAddress(new Address("甘肃省张掖市"));
user.setName("佩奇");
}
System.out.println("---------加工完成----------------");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}
3.2 在Spring的配置文件中进行配置
<bean id="myBeanPostProcessor" class="com.spring.test.MyBeanPostProcessor"></bean>