Yes there is a difference: @Bean("foo")
(or @Component("foo")
) gives your bean the name “foo” in the Spring Context, whereas @Qualifier("foo")
only adds information without changing the name of the bean.
As the bean name is the bean’s unique identifier in the Context, you can only have 1 bean named “foo”, whereas you can have multiple beans with @Qualifier("foo")
.
Example:
interface TypeOne {}
The following will add a bean with name “beanOne”, automatically generated from the class name.
@Component // explicitly: @Component("beanOne")
class BeanOne implements TypeOne {
}
Same as the following declaration within a @Configuration
class:
@Bean // explicitly: @Bean(name = "beanOne")
BeanOne beanOne() { return new BeanOne(); }
The following will add a bean with name “beanTwo” and another with name “beanThree”, with the same qualifier “beanQualifier”:
@Component
@Qualifier("beanQualifier")
class BeanTwo implements TypeOne { }
@Component
@Qualifier("beanQualifier")
class BeanThree implements TypeOne { }
With the above, you can autowire using the qualifier:
@Autowired
@Qualifier("beanQualifier")
Map<String, TypeOne> typeOneMap;
The map will only contain the 2 beans with qualifier “beanQualifier”.
{beanThree=BeanThree@9f674ac, beanTwo=BeanTwo@1da4b3f9}
The other, “beanOne”, has not been wired into the map because it’s not qualified by “beanQualifier”.
Note that the map keys are the bean names that have been automatically generated.