嚴格意義上來講,這個不算是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;
}
即實現(xiàn)postProcessBeanDefinitionRegistry方法,可以修改增加BeanDefinition。
此特性可以用來動態(tài)生成bean,比如讀取某個配置項,然后根據(jù)配置項動態(tài)生成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來讀取配置項,根據(jù)配置項來進行datasoure注冊過程,此處代碼未實現(xiàn)此種邏輯。