Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) {
     ...
 }
like image 832
user3908406 Avatar asked Jul 09 '20 19:07

user3908406


People also ask

Can we use @qualifier and @bean together?

NOTE: if you are creating bean with @Bean, it will be injected byType if there is duplicates then it will injected byName. we no need to mention @Bean(name="bmwDriver") . so you can directly use qualifier("bmwDriver") wherever you need in classes.

What is the use of @bean name?

@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .

How do you name a bean in Spring?

Custom Naming of Beans Similar to @Component(“myBean”), we can specify the name using other annotations such as @Service(“myService”), @Controller(“myController”), and @Bean(“myCustomBean”), and then Spring will register that bean with the given name.

What is the difference between @primary and @qualifier in Spring?

Spring @Primary vs @Qualifier. 3.1. We use @Qualifier in Spring to autowire a specific bean among same type of beans, where as @Primary is used to give high preference to the specific bean among multiple beans of same type to inject to a bean.


1 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.

like image 168
夢のの夢 Avatar answered Sep 23 '22 09:09

夢のの夢