preface

When more than one Bean of the same type is created, we can resolve the confusion by matching @Autowired with @Qualifier to determine which Bean to inject. In addition, @Qualifier can be annotated to implement logical grouping on beans.

The source code

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Qualifier {
    String value(a) default "";
}
Copy the code

use

Annotated on a single attribute, the Bean is retrieved by name:

@Autowired
@Qualifier("bean2")
private MyBean mybean;

@Bean
public MyBean bean1(a) {
    return new MyBean();
}

@Bean
public MyBean bean2(a) {
    return new MyBean();
}
Copy the code

Annotated on the collection, you can filter out beans annotated by @Qualifier

@Autowired
private List<User> users; // user1, user2, user3

@Autowired
@Qualifier
private List<User> usersQualifier; // user2, user3

@Bean
public User user1(a) {
    return new User();
}

@Bean 
@Qualifier
public User user2(a) {
    return new User();
}

@Bean
@Qualifier
public User user3(a) {
    return new User();
}
Copy the code