Search code examples
javaspringspring-mvcspring-annotationsspring-bean

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


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?


Solution

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