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

100,129

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

}
Share:
100,129
Oleksandr
Author by

Oleksandr

Updated on July 09, 2022

Comments

  • Oleksandr
    Oleksandr almost 2 years

    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?

  • Oleksandr
    Oleksandr over 7 years
    Thank you for help. I think I have not clear question. I wanted to use custom names. Also, you can not use @Component annotations on methods.
  • Sundararaj Govindasamy
    Sundararaj Govindasamy over 4 years
    @Noel Yap, I retained that 'extra information' to remember how spring evolved on this. That's why I strike-out that text. Could you please re-add? Thanks.
  • Noel Yap
    Noel Yap over 4 years
    IMO such history doesn't belong in this answer. For example, I almost missed the actual answer since I almost stopped reading after the first few sentences. Foremost to consider is the purpose of SO and the primary problem those using it are trying to solve.
  • Noel Yap
    Noel Yap over 4 years
    Alternatively, the original, legacy answer could have been kept and a new, more up-to-date one created.