title: “spring Bean创建流程及扩展点”
date: 2019-09-26
tags: [“spring”]
categories: 后台
springBean创建流程
扩展点
ImportBeanDefinitionRegistrar 与ImportSelector
实现接口可以添加自定义的beanDefinition,例:
@Component
public class RpcClientSelector implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Map<String, Object> map = importingClassMetadata.getAnnotationAttributes(EnableRpcClient.class.getName());
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(RpcScanner.class);
beanDefinitionBuilder.addPropertyValue("basePackage", map.get("basePackage"));
registry.registerBeanDefinition(RpcScanner.class.getName(), beanDefinitionBuilder.getBeanDefinition());
}
}
BeanDefinitionBuilder.rootBeanDefinition(clazz); 如果clazz 实现了FactoryBean那么创建的bean 的类型不是clazz本身,而是getObject() 方法返回的对象类型
@Component
public class RpcClientSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
Set<String> strings = importingClassMetadata.getMetaAnnotationTypes(RpcClient.class.getName());
Set<String> strings1 = importingClassMetadata.getAnnotationTypes();
return new String[]{"com.jianganwei.rpcclient.selector.RpcScanner"};
}
}
BeanFactoryPostProcessor
添加修改bean
@Component
public class MyConfigBean implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory (
ConfigurableListableBeanFactory beanFactory)
throws BeansException {
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(MyBean.class);
bd.getPropertyValues().add("strProp", "my string property");
((DefaultListableBeanFactory) beanFactory)
.registerBeanDefinition("myBeanName", bd);
}
}
BeanPostProcessor
bean的初始化过程(初始化,之前初始化之后)
总结
通过上面的扩展点可以动态修改bean然后注入到代码中,注入动态代理后的bean都是基于这些扩展点完成的。