使用 Spring Boot 创建 bean 别名

在 Spring XML 中,我可以使用alias元素为 bean 分配一个或多个别名。我想知道是否有 Spring Boot 编程方式来做同样的事情?

用例是我有需要 JMS 的遗留代码TopicConnectionFactory。使用 Spring Boot 的 ActiveMQ 自动配置,我TopicConnectionFactory自动获得了一个。但是,遗留代码使用静态字符串来查找 bean 名称,因此我需要创建一个别名,将遗留代码 bean 查找链接到 Spring Boot bean。

我试过查看,BeanDefinitionCustomizer但它没有办法设置别名或 bean 名称。


千巷猫影
浏览 316回答 1
1回答

慕田峪4524236

好的,事实证明,一旦您可以访问 a ,就有一种方法可以做到这一点ConfigurableListableBeanFactory:@Autowiredprivate ConfigurableListableBeanFactory beanFactory;@Beanpublic BeanPostProcessor jmsTopicConnFactoryAliasCreator(){&nbsp; return new BeanPostProcessor()&nbsp; {&nbsp; &nbsp; &nbsp;@Override&nbsp; &nbsp; &nbsp;public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; if(bean instanceof TopicConnectionFactory)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;beanFactory.registerAlias(beanName, "<LEGACY_BEAN_LOOKUP_NAME>");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return bean;&nbsp; &nbsp; &nbsp;}&nbsp; };}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java