BeanFactoryPostProcessor:Beans定义处理器(一个接口)
在Bean定义之后Bean实例创建之前,可以通过BeanFactoryPostProcessor.postProcessBeanFactory方法对所有的Bean定义进行修改或者是增加Bean定义。
BeanFactoryPostProcessor代码
@FunctionalInterface
public interface BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for overriding or adding
* properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
BeanFactoryPostProcessor的使用
-
创建一个类
-
使用该类实现BeanFactoryPostProcessor接口
-
把新创建的类注入到Spring容器
代码示例
TestBeanFactoryPostProcessor类(示例中,增加了一个BeanB的定义,BeanB是一个类的名称)
public class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
BeanDefinitionRegistry beanFactory1 = (BeanDefinitionRegistry) beanFactory;
GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
genericBeanDefinition.setBeanClass(BeanB.class);
genericBeanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
genericBeanDefinition.setAutowireCandidate(true);
beanFactory1.registerBeanDefinition("beanB", genericBeanDefinition);
System.out.println(1);
}
}
BeanB类
public class BeanB { }
把TestBeanFactoryPostProcessor注入到Spring
@Bean public TestBeanFactoryPostProcessor testBeanFactoryPostProcessor() {
return new TestBeanFactoryPostProcessor();
}
使用BeanB(开发中IDEA可能会检测到上下文中没有该Bean,会出现红线警告,不过不影响编译和使用)
@Autowired
private BeanB beanB;