我正在使用带注释的 Spring Beans,我需要在运行时选择不同的实现。
@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 配置。
原文由 Tobia 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以将 bean 注入移动到配置中,如下所示:
Alternatively, you may use profiles
windows
andlinux
, then annotate your service implementations with the@Profile
annotation, like@Profile("linux")
or@Profile("windows")
,并为您的应用程序提供其中一个配置文件。