Skip to content

Instantly share code, notes, and snippets.

@marlonklc
Last active January 19, 2023 03:54
Show Gist options
  • Save marlonklc/68315df6ba19a884efbbaecf98a1136d to your computer and use it in GitHub Desktop.
Save marlonklc/68315df6ba19a884efbbaecf98a1136d to your computer and use it in GitHub Desktop.
How to instantiate dynamic implementations of a service using spring config
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