spring的bean工厂后置处理器的回调时期是在bean实例化之前,把我们的spring配置文件解析完成之后,把bean工厂初始化之后,调用bean工厂后置处理器之后才调用bean的创建过程。我们可以对bean的定义进行修改。
spring5.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="user" class="com.video.spring.User"></bean>
<bean id="b" class="com.video.spring.MyBeanFactoryPostProcessor"></bean>
</beans>
import lombok.Data;
@Data
public class User {
private int id;
private String name;
public User() {
System.out.println("user 构造方法");
}
public void init1() {
System.out.println("User init1");
}
public void destory1() {
System.out.println("User destory1");
}
}
MyBeanFactoryPostProcessor
BeanFactoryPostProcessor :实现BeanFactoryPostProcessor , bean工厂后置处理器
Ordered : 实现Ordered ,bean工厂后置处理器执行顺序,数字越小,越先执行
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanFactoryPostProcessor 101010");
AbstractBeanDefinition abstractBeanDefinition = (AbstractBeanDefinition) beanFactory.getBeanDefinition("user");
//设置user创建之前,执行init方法
abstractBeanDefinition.setInitMethodName("init1");
abstractBeanDefinition.setDestroyMethodName("destory1");
//给user属性赋值
MutablePropertyValues mutablePropertyValues = abstractBeanDefinition.getPropertyValues();
//给user的name属性赋值为beanfactory modify name
mutablePropertyValues.addPropertyValue("name", "beanfactory modify name");
}
@Override
public int getOrder() {
return 10;
}
}
网友评论