严格意义上来讲,这个不算是springboot的特有功能,仍然属于spring部分的功能。
先看下这个接口的定义:
/**
* Extension to the standard {@link BeanFactoryPostProcessor} SPI, allowing for
* the registration of further bean definitions <i>before</i> regular
* BeanFactoryPostProcessor detection kicks in. In particular,
* BeanDefinitionRegistryPostProcessor may register further bean definitions
* which in turn define BeanFactoryPostProcessor instances.
*
* @author Juergen Hoeller
* @since 3.0.1
* @see org.springframework.context.annotation.ConfigurationClassPostProcessor
*/
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
*/
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
即实现postProcessBeanDefinitionRegistry方法,可以修改增加BeanDefinition。
此特性可以用来动态生成bean,比如读取某个配置项,然后根据配置项动态生成bean。
举例:
public class Datasoure {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Configuration
public class DataConfig {
@Bean
public BeanDefinitionRegistryPostProcessor beanDefinitionRegistryPostProcessor(Environment env){
return new BeanDefinitionRegistryPostProcessor() {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
BeanDefinition beanDe = BeanDefinitionBuilder.rootBeanDefinition(Datasoure.class)
.addConstructorArgValue("datasoure1").getBeanDefinition();
registry.registerBeanDefinition("soure1", beanDe);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
};
}
}
以上postProcessBeanDefinitionRegistry方法中可以通过env来读取配置项,根据配置项来进行datasoure注册过程,此处代码未实现此种逻辑。