Is it possible to set a bean name using annotation

2020-02-21 03:00发布

问题:

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?

回答1:

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

}