Specify which subclass to use
Example codes:
Formatter.java
public interface Formatter {
String format();
}
BarFormatter.java
@Component
@Qualifier("barFormatter")
public class BarFormatter implements Formatter {
public String format() {
return "bar";
}
}
FooFormatter.java
@Component
@Qualifier("fooFormatter")
public class FooFormatter implements Formatter {
public String format() {
return "foo";
}
}
FooService.java
@Component
public class FooService {
@Autowired
@Qualifier("barFormatter")
private Formatter formatter;
public String doStuff() {
return formatter.format();
}
}
DemoApplication.java
@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();
}
}