Spring动态添加Bean
Spring动态添加Bean,需要使用到BeanDefinitionRegistryPostProcessor
public class DataSourcesBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {private final List customerKeys;public DataSourcesBeanFactoryPostProcessor(Environment springEnvironment) {parseCustomerKeys(springEnvironment.getProperty("customerKeys"));}@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {for (String customerKey : customerKeys) {String dataSourceName = "dataSource_" + customerKey;BeanDefinitionBuilder definitionBuilder =BeanDefinitionBuilder.genericBeanDefinition(JndiObjectFactoryBean.class);definitionBuilder.addPropertyValue("jndiName", "jdbc/" + dataSourceName);registry.registerBeanDefinition(dataSourceName, definitionBuilder.getBeanDefinition());}}@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {// we actually only add new beans, but do not post process the existing definitions}private static List parseCustomerKeys(String rawCustomerKeys) {if (StringUtils.isEmpty(rawCustomerKeys)){throw new IllegalArgumentException("Property 'customerKeys' is undefined.");}return Collections.unmodifiableList(Arrays.asList(StringUtils.split(rawCustomerKeys, ",")));}
}
参考:How to Create Your Own 'Dynamic' Bean Definitions in Spring
如果能拿到ApplicationContext对象,则还可以通过这种方式来注册Bean对象
context.getBeanFactory().registerSingleton(beanName, singletonObject)
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!