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) {
...
}
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.
@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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With