Issue
I'm using Spring Beans with annotations and I need to choose different implementation at runtime.
@Service
public class MyService {
public void test(){...}
}
For example for windows's platform I need MyServiceWin extending MyService
, for linux platform I need MyServiceLnx extending MyService
.
For now I know only one horrible solution:
@Service
public class MyService {
private MyService impl;
@PostInit
public void init(){
if(windows) impl=new MyServiceWin();
else impl=new MyServiceLnx();
}
public void test(){
impl.test();
}
}
Please consider that I'm using annotation only and not XML config.
Solution
You can move the bean injection into the configuration, as:
@Configuration
public class AppConfig {
@Bean
public MyService getMyService() {
if(windows) return new MyServiceWin();
else return new MyServiceLnx();
}
}
Alternatively, you may use profiles windows
and linux
, then annotate your service implementations with the @Profile
annotation, like @Profile("linux")
or @Profile("windows")
, and provide one of this profiles for your application.
Answered By - Stanislav