wjans
wjans

Reputation: 10115

Spring boot not complaining about two beans with the same name

I'm having the following configuration where I have two Spring beans with the same name from two different configuration classes.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfiguration {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration 
public class OtherRestTemplateConfiguration {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

And I am injecting (and using) this bean like this:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class SomeComponent {

    @Autowired
    private RestTemplate restTemplate;

}

Now, my question is: why is Spring not complaining about having multiple beans with the same name? I would expect an exception here and having to add a @Primary annotation to make sure that the correct one is being used.

On a side note: even if I add @Primary it is still not always injecting the correct one.

Upvotes: 12

Views: 18608

Answers (2)

rocky
rocky

Reputation: 5004

One of the beans is overriding other one because you use same name. If different names were used as @paweł-głowacz suggested, then in case of using

@Autowired
private RestTemplate myRestTemplate;

spring will complain because it finds two beans with same RestTemplate type and doesnt know which to use. Then you apply @Primary to one of them.

More explanation here: more info

Upvotes: 7

Paweł Głowacz
Paweł Głowacz

Reputation: 3046

You need to name that beans so:

@Configuration
public class RestTemplateConfiguration {

    @Bean(name="bean1")
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

And

@Configuration 
public class OtherRestTemplateConfiguration {

    @Bean(name="bean2")
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Upvotes: 0

Related Questions