3

In Spring XML, I can use the alias element to assign one or more aliases to a bean. I'm wondering if there is a Spring Boot programmatic way to do the same?

The use case is I have legacy code that needs a JMS TopicConnectionFactory. Using Spring Boot's ActiveMQ auto configuration, I get a TopicConnectionFactory automatically. However, the legacy code uses a static string to lookup the bean name, so I need to create an alias that links the legacy code bean lookup to the Spring Boot bean.

I have tried looking at BeanDefinitionCustomizer but it doesn't have a way to set alias or bean name.

Mike
  • 4,722
  • 1
  • 27
  • 40
  • 2
    Possible duplicate of [Spring Bean Alias in JavaConfig](https://stackoverflow.com/questions/27107133/spring-bean-alias-in-javaconfig) – lealceldeiro Jul 24 '18 at 15:50
  • Google [gives](https://www.google.com.cu/search?q=create+an+alias+for+a+bean+in+spring+boot&oq=create+an+alias+for+a+bean+in+spring+boo) a good results for this. Have you tried anything without success? – lealceldeiro Jul 24 '18 at 15:54
  • 1
    @lealceldeiro The linked question doesn't provide an answer for this use case. Specifically, the OP is **not** defining the actual bean originally; he's trying to provide aliases for an *existing* bean. – chrylis -cautiouslyoptimistic- Jul 24 '18 at 15:58
  • @lealceldeiro As mentioned, that SO article doesn't apply because I don't control the Bean definition. And yes, I have tried Google with no luck as they all suggest the XML method or Bean annotation which won't work for me. – Mike Jul 24 '18 at 16:05
  • @Mike OK, I just retracted my dupe close vote :) – lealceldeiro Jul 24 '18 at 16:22
  • @chrylis Actually he is controlling the bean (he could simply redeclare the Spring Boot automatically created `ConnectionFactory` and that way provide the needed alias). He only wants an alias, for another bean which he isn't controlling. He is, in a way, controlling the creation of the `ConnectionFactory`. – M. Deinum Jul 25 '18 at 05:22
  • @M.Deinum Of course he *could* duplicate the Boot bean. The question is how to get an alias without resorting to that. – chrylis -cautiouslyoptimistic- Jul 25 '18 at 05:55

1 Answers1

2

Ok, turns out there is a way to do this once you have access to a ConfigurableListableBeanFactory:

@Autowired
private ConfigurableListableBeanFactory beanFactory;

@Bean
public BeanPostProcessor jmsTopicConnFactoryAliasCreator()
{
  return new BeanPostProcessor()
  {
     @Override
     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
     {
        if(bean instanceof TopicConnectionFactory)
        {
           beanFactory.registerAlias(beanName, "<LEGACY_BEAN_LOOKUP_NAME>");
        }
        return bean;
     }
  };
}
Mike
  • 4,722
  • 1
  • 27
  • 40