Spring Boot Qualifiers
Qualifier Overview
Qualifiers are a Spring feature rather than a Spring Boot-specific feature. Spring provides qualifiers similar to CDI qualifiers.
Specifying a Qualifier Name
- Use
@Qualifierto specify a Bean name. - Combine
@Autowiredand@Qualifierto inject a specific Bean. - This is similar to using
@Namedin CDI.
Writing the Code
public interface MyInterface {
}
@Component
@Qualifier("hoge")
public class Hoge implements MyInterface {
}
@Component
@Qualifier("fuga")
public class Fuga implements MyInterface {
}
@SpringBootApplication
public class Main {
public static void main(String[] args) {
try (ConfigurableApplicationContext context = SpringApplication.run(Main.class, args)) {
Main m = context.getBean(Main.class);
System.out.println("hoge = " + m.hoge.getClass());
System.out.println("fuga = " + m.fuga.getClass());
}
}
@Autowired @Qualifier("hoge")
private MyInterface hoge;
@Autowired @Qualifier("fuga")
private MyInterface fuga;
}
Result
hoge = class sample.springboot.Hoge
fuga = class sample.springboot.Fuga
Creating a Qualifier
- Create a qualifier by annotating a custom annotation with
@Qualifier. - This works like a custom CDI qualifier.
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface MyQualifier {
MyType value();
}
public enum MyType {
HOGE,
FUGA,
}
@Component
@MyQualifier(MyType.HOGE)
public class Hoge implements MyInterface {
}
@Component
@MyQualifier(MyType.FUGA)
public class Fuga implements MyInterface {
}
@Autowired @MyQualifier(MyType.HOGE)
private MyInterface hoge;
@Autowired @MyQualifier(MyType.FUGA)
private MyInterface fuga;
The result is the same: each field receives the Bean with the matching custom qualifier.