Home > AI > Backend > SpringBoot >

@Qualifier

Specify which subclass to use

Example codes:

Formatter.java

1
2
3
4
5
public interface Formatter {
 
    String format();
 
}

BarFormatter.java

1
2
3
4
5
6
7
8
@Component
@Qualifier("barFormatter")
public class BarFormatter implements Formatter {
 
    public String format() {
        return "bar";
    }
}

FooFormatter.java

1
2
3
4
5
6
7
8
@Component
@Qualifier("fooFormatter")
public class FooFormatter implements Formatter {
 
    public String format() {
        return "foo";
    }
}

FooService.java

1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class FooService {
 
    @Autowired
    @Qualifier("barFormatter")
    private Formatter formatter;
 
    public String doStuff() {
        return formatter.format();
    }
 
}

DemoApplication.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RestController
@SpringBootApplication
public class DemoApplication {
 
    private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
 
    public static void main(String[] args) throws IOException {
 
        SpringApplication.run(DemoApplication.class, args);
    }
 
    @Autowired
    FooService f;
    @GetMapping("/hello")
    public String hello() {
        return f.doStuff();
    }
}

Leave a Reply