Last active
January 19, 2023 03:54
-
-
Save marlonklc/68315df6ba19a884efbbaecf98a1136d to your computer and use it in GitHub Desktop.
How to instantiate dynamic implementations of a service using spring config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface MyService { | |
String print(); | |
} | |
@Service("service1") | |
public class MyFirstService implements MyService { | |
@Override | |
public String print() {return "service ONE";} | |
} | |
@Service("service2") | |
public class MySecondService implements MyService { | |
@Override | |
public String print() { return "service TWO"; } | |
} | |
@Configuration | |
public class MyConfiguration { | |
@Autowired | |
private ApplicationContext applicationContext; | |
@Bean | |
public MyService customServiceAlias(@Value("${my.service}") final String myservice) { | |
return (MyService) applicationContext.getBean(myservice); | |
} | |
} | |
@RestController | |
@RequestMapping("/api") | |
public class MyApi { | |
private MyService service; | |
public MyApi(@Qualifier("customServiceAlias") MyService service) { | |
this.service = service; | |
} | |
@GetMapping | |
public ResponseEntity<String> test() { | |
return ResponseEntity.ok().body(service.print()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment