Is it possible to set a bean name using annotations in Spring Framework?

Oleksandr picture Oleksandr · Oct 6, 2016 · Viewed 86.7k times · Source

I have a bean like this:

@Bean
public String myBean(){
    return "My bean";
}

I want to autowire it:

@Autowired
@Qualifier("myBean")
public void setMyBean(String myBean){
    this.myBean=myBean;
}

I need something like:

@Bean(name="myCustomBean")

Is it possible to use custom names names for beans out of the box? If it isn't possible out of the box then how to create such a bean?

Answer

Sundararaj Govindasamy picture Sundararaj Govindasamy · Oct 6, 2016

What you are asking is already available in Spring reference

By default, configuration classes use a @Bean method’s name as the name of the resulting bean. This functionality can be overridden, however, with the name attribute.

@Configuration
public class AppConfig {

    @Bean(name = "myFoo")
    public Foo foo() {
        return new Foo();
    }

}