50

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
  • 3,574
  • 8
  • 41
  • 78

1 Answers1

61

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

}
Prabhat
  • 338
  • 4
  • 20
Sundararaj Govindasamy
  • 8,180
  • 5
  • 44
  • 77
  • 1
    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. – Oleksandr Oct 06 '16 at 14:14
  • @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. – Sundararaj Govindasamy Nov 08 '19 at 18:50
  • 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 Nov 08 '19 at 23:47
  • Alternatively, the original, legacy answer could have been kept and a new, more up-to-date one created. – Noel Yap Nov 08 '19 at 23:49