常规做法
@ConditionalOnProperty(name = "service.choice", havingValue = "service1")
我们都知道注解@ConditionalOnProperty可以进行配置选择注入,那如果多个实现想要并存如何实现呢,往下看:
多实现并存
接口
public interface MyService {
String get();
}
实现一
@Service
public class MyServiceImpl1 implements MyService {
@Override
public String get() {
return "Impl_1";
}
}
实现二
@Service
public class MyServiceImpl2 implements MyService {
@Override
public String get() {
return "Impl_2";
}
}
Service选择
这个类主要是为了对多个实现类进行合理的选择(注意:这里存在bean依赖问题。通常来说解决bean依赖问题有两种方式:1.构造器依赖,2.DependsOn注解)
@Service
//@DependsOn({"myServiceImpl1", "myServiceImpl1"})
public class ServiceSwitch {
private final Map<String, MyService> services = new HashMap<>();
public ServiceSwitch(Map<String, MyService> map) {
map.forEach((k, v) -> services.put(k, v));
}
/**
* 根据名字返回相应的实现类
*
* @param type 类名
* @return 实现类
*/
public MyService get(String type) {
return services.get(type);
}
}
Api测试
public class ConfigApi {
@Autowired
private ServiceSwitch switch;
@GetMapping("/service/{s}")
public String getService(@PathVariable("s") String s) {
final MyService myService = switch.get(s);
return myService.get();
}
}
测试
访问:http://localhost:8080/config/service/myServiceImpl1,返回:Impl_1
访问:http://localhost:8080/config/service/myServiceImpl2,返回:Impl_2