6

How to alias a bean outside the bean definition using Java config in Spring Boot?

2
  • ''outside the bean definition" do you mean, bean is already defined and you are not allowed to change that? Mar 1, 2019 at 6:10
  • @AtulDwivedi The bean is already defined in another project(jar) and I'm using it in my project, now I have a requirement to alias the same bean.
    – Prajwel
    Mar 1, 2019 at 6:12

2 Answers 2

6

I have this as well, and solved it like this:

@Component
public class AliasConfiguration implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        beanFactory.registerAlias("originalBeanName", "newAlias");
        beanFactory.registerAlias("originalBeanName", "newAlias2");
        beanFactory.registerAlias("otherOriginalBeanName", "newAlias3");
    }
}
0

You want to alias a bean which is already defined somewhere else, this feature is not supported in spring yet.

Along with that aliasing a bean is not allowed in @Component, @Service and @Repository.

Either you can alias a bean while defining in XML configuration or while using @Bean(name = {"alias1", "alias2"}). But as you mentioned in you case bean is already defined in another JAR, it's not possible to alias it.

A similar(not exactly similar) issue is open to spring-framework.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.