Spring @Bean(name ="name") vs @Bean @Qualifier("name")

Viewed 12333

Is there any differences between the following 2 bean declaration?

 @Bean(name = "bean1")
 public A getA() {
     return new A();
 }


 @Bean
 @Qualifier("bean1")
 public A getA() {
     return new A();
 }

Both can be autowired using @Qualifier

 @Autowire
 public void test(@Qualifier("bean1") A a) {
     ...
 }
3 Answers

With value() you don't have to specify attribute name, like @Qualifier("bean1"). Attribute name() reference the same value as value() because of custom annotation @AliasFor(..) from Spring, therefore they are just different names with the same behavior.

The first part is fundamentally the same, the second part is what you basically need when two or more beans of same type exist. The first part is just the preference one might have.

You can use

 @Autowire
 public void test(A bean1) {
     ...
 }

if you use

 @Bean(name = "bean1")

not with

@Bean
@Qualifier("bean1")
Related