Spring的bean工厂后处理器和Bean后处理器
Spring的bean工厂后处理器和Bean后处理器
一、基本原理
1.1原理一
Spring 的后处理器是 Spring 对外开发的重要扩展点,允许我们介入到 Bean 的整个实例化流程中来,以达到动态注册
BeanDefinition,动态修改 BeanDefinition,以及动态修改 Bean 的作用。Spring 主要有两种后处理器:
-
BeanFactoryPostProcessor:Bean 工厂后处理器,在 BeanDefinitionMap 填充完毕,Bean 实例化之前执行;
-
BeanPostProcessor:Bean后处理器,一般在Bean实例化之后,填充到单例池 singletonObjects之前执行。
1.2原理二
BeanFactoryPostProcessor 是一个接口规范,实现了该接口的类只要交由 Spring 容器管理的话,那么 Spring 就会回调该接口的方法,用于对 BeanDefinition 注册和修改的功能。
public interface BeanFactoryPostProcessor {
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory);
}
二、实验
2.1验证原理二
先定义一个类然后实现接口BeanFactoryPostProcessor,重写其方法postProcessBeanFactory
package com.itheima.processor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
System.out.println("BeanFactoryMap填充完毕,回调改方法");
}
}
将这个类在applicationContext.xml文件中配置成为bean:
<bean class="com.itheima.processor.MyBeanFactoryPostProcessor"></bean>
结果:
综上所述,原理二得证。
2.2实验二通过ConfigurableListableBeanFactory获取到BeanDefinition,然后修改权限名
package com.itheima.processor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
System.out.println("BeanFactoryMap填充完毕,回调改方法");
BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition("userService");
// 修改全限制名
beanDefinition.setBeanClassName("com.itheima.service.impl.UserServiceImpl2");
}
}
结果:
本文地址:https://www.yitenyun.com/5020.html
上一篇:struct pid
下一篇:认识服务器-web服务器









