Zed
Zed

Reputation: 5921

Multiple beans with the same implementation in Spring boot

I have a situation where I'm using one possible implementation for a particular bean, and it looks like this:

@Configuration
public class MyConfig {

    @Autowired
    private ApplicationContext context;

    @Bean
    public SomeInterface someInterface() {
        if (this.context.getEnvironment().getProperty("implementation") != null) {
            return new ImplementationOne();
        } else {
            return new ImplementationTwo();
        }
    }
}

This worked great so far, until a new requirement came in, to use an additional interface which for the moment only ImplementationTwo provides implementation, and it wouldn't make sense to use it with ImplementationOne:

    @Bean
    public SomeOtherInterface someOtherInterface() {
            return new ImplementationTwo();
    }

I guess this would work, but I'm wondering if this really make sense because in one scenario I could have both beans basically instantiating the same object. Does that make sense ? Is there maybe a better way to achieve the same thing?

Upvotes: 1

Views: 4640

Answers (2)

wet_waffle
wet_waffle

Reputation: 150

You can always define in each place where you're using particular bean a qualifier:

   @Bean
   public SomeInterface beanName1(){ //impl }

   @Bean
   public SomeInterface beanName2(){ //impl }

Usage:

 @Qualifier("beanName1") SomeInterface interface;

Also 'd need to allow multiple beans in your application.yml/properties file:

spring.main.allow-bean-definition-overriding=true

Upvotes: 2

janardhan sharma
janardhan sharma

Reputation: 335

I believe, if you have multiple implementations of a single interface, then you should go about specific bean names as below.

Here implementation1 will be the primary bean created and injected where ever we have the Interface1 dependency.

@Primary
@Bean
public Interface1 implementation1() {
    return new Implementation2();
}

@Bean
public Interface1 implementation2() {
    return new Implementation2();
}

If we need implementation2 injected we need @Resource annotation as below.

@Resource(name="implementation2")
Interface1 implementation2;

Upvotes: 1

Related Questions