我正在使用带有注释的Spring Bean,并且需要在运行时选择其他实现。
@Service
public class MyService {
public void test(){...}
}
例如,我需要Windows平台,我需要MyServiceWin extending MyService
Linux平台MyServiceLnx extending MyService
。
目前,我只知道一个可怕的解决方案:
@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();
}
}
请考虑我仅使用注释,而不使用XML配置。
您可以将bean注入移动到配置中,如下所示:
@Configuration
public class AppConfig {
@Bean
public MyService getMyService() {
if(windows) return new MyServiceWin();
else return new MyServiceLnx();
}
}
或者,您可以使用配置文件windows
和linux
,然后用@Profile
注释(如@Profile("linux")
或)注释您的服务实现@Profile("windows")
,并为您的应用程序提供此配置文件之一。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句