您可以使用 aBeanFactoryPostProcessor
来加载配置。
例如,如果您有一个 LocationService,它将配置位置作为 String[]:
public class XmlBeanDefinitionReaderPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory);
ResourceLoader resourceLoader = new DefaultResourceLoader();
reader.setResourceLoader(new DefaultResourceLoader());
reader.setEntityResolver(new ResourceEntityResolver(resourceLoader));
reader.setEnvironment(new StandardEnvironment());
LocationService locationService = (LocationService) beanFactory.getBean("locationService");
reader.loadBeanDefinitions(locationService.getLocations());
}
}
不完全一样,因为读者不知道已经加载的 bean 并且可能是别名或 bean 名称 colisions。
请注意,您LocationService
不应使用Autorwire
,AOP Transactional Proxies
和通常暗示使用BeanPostProcessors
.
其他重用相同的选项XmlBeanDefinitionReader
是覆盖postProcessBeanFactory
方法XmlWebApplicationContext
:
public class CustomWebApplicationContext extends XmlWebApplicationContext {
private XmlBeanDefinitionReader reader;
@Override
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
this.reader = reader;
super.loadBeanDefinitions(reader);
}
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
LocationService locationService = (LocationService) beanFactory.getBean("locationService");
this.reader.loadBeanDefinitions(locationService.getLocations());
super.postProcessBeanFactory(beanFactory);
}
}