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

Oleksandr :

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?

Sundararaj Govindasamy :

What you are asking is already available in Spring 4.3.3

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();
    }

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=422020&siteId=1