我使用带有注释的 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 配置。
1. 实施自定义Condition
public class LinuxCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Linux"); }
}
同样适用于Windows
.
2. Use @Conditional在你的Configuration
class
@Configuration
public class MyConfiguration {
@Bean
@Conditional(LinuxCondition.class)
public MyService getMyLinuxService() {
return new LinuxService();
}
@Bean
@Conditional(WindowsCondition.class)
public MyService getMyWindowsService() {
return new WindowsService();
}
}
3. Use @Autowired
照常
@Service
public class SomeOtherServiceUsingMyService {
@Autowired
private MyService impl;
// ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)