问题描述
我正在使用带有注释的Spring Beans,我需要在运行时选择不同的实现。
I'm using Spring Beans with annotations and I need to choose different implementation at runtime.
@Service
public class MyService {
public void test(){...}
}
例如对于windows的平台,我需要 MyServiceWin扩展MyService
,对于linux平台,我需要 MyServiceLnx扩展MyService
。
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();
}
}
请考虑我只使用注释而不是XML配置。
Please consider that I'm using annotation only and not XML config.
推荐答案
您可以将bean注入到配置中,如下所示:
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();
}
}
或者,您可以使用资料 windows
和 linux
,然后使用 @Profile
注释注释您的服务实现,如 @Profile(linux)
或 @Profile(windows)
,并为您提供此配置文件之一申请。
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.
这篇关于Spring在运行时选择bean实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!