Spring5源码分析BeanDefinitionRegistryPostProcessor
上一篇:
BeanDefinitionRegistryPostProcessor可以完成新的BeanDefinition注册,对已有BeanDefinition进行修改等操作
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor { /**
* Modify the application context"s internal bean definition registry after its
* standard initialization. All regular bean definitions will have been loaded,
* but no beans will have been instantiated yet. This allows for adding further
* bean definitions before the next post-processing phase kicks in.
* @param registry the bean definition registry used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*
* 在Spring的标准初始化完成之后,此时所有的符合Spring规则的BeanDefinition已经全部完成加载,但是还没有任何一个Bean被初始化,
* Spring允许在下一个post-processing开始处理之前通过此接口添加更多的BeanDefinition
*/
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
写一个类实现BeanDefinitionRegistryPostProcessor 往容器中手动注册一个BeanDefinition
@Componentpublic class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("MyBeanDefinitionRegistryPostProcessor postProcessBeanDefinitionRegistry");
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(ProcessorCity.class);
registry.registerBeanDefinition("city",beanDefinitionBuilder.getBeanDefinition());
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
//暂时不实现此方法,等看到BeanFactoryPostProcessor的时候再来
}
}
代码往容器中注册了ProcessorCity类
@Getter@Setter
public class ProcessorCity {
private String cityName = "重庆";
}
测试类
public class ProcessorMain { public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ProcessorConfig.class);
ProcessorCity city = ac.getBean(ProcessorCity.class);
System.out.println(city.getCityName());
}
}
输出
因为这里可以任意往里面添加BeanDefinition,甚至可以让自己一个类去批量注入类,比如自己定义注解去实现特定的扫描或者过滤,进行批量注册
修改BeanDefinition
在PostProcessor的postProcessBeanDefinitionRegistry方法中使用registry.getBeanDefinition()得到某一个BeanDefinition,然后可以修改它的任何属性,甚至可以将要真正创建Bean对应的Class文件都修改了。
下一篇:Spring5源码分析-BeanFactoryPostProcessor
以上是 Spring5源码分析BeanDefinitionRegistryPostProcessor 的全部内容, 来源链接: utcz.com/z/510724.html