代码可能这样
public class handler {
void handler(String param){
if('A'.equals(param)){
ATestService.do();
}else if('B'.equals(param){
BTestService.do();
}
}
}
@Autowired用法
@Autowired 官方文档
private Map<String, MovieCatalog> movieCatalogs;
@Autowired
public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}
// ...
利用这种方式的自动注入,可以将同一个接口的实现bean,注入Map,Map的key为Bean的名称name,value为该bean。
干掉 else if
// 接口
public interface TestService {
void do();
}
// 实现 bean A
@Service("A")
public class ATestServiceImpl Impl TestService{
void do(){
...
}
}
// 实现 bean B
@Service("B")
public class BTestServiceImpl Impl TestService{
void do(){
...
}
}
@Component
public class handler {
@Autowired(required = false)
private Map<String, TestService> services = Maps.newHashMap();
void handler(String beanName) {
TestService service = services.get(beanName);
service.do();
}
}
其他
当然也可以用其他的方法获取bean来进行解耦,例如继承ApplicationContextAware,通过ApplicationContext#getBeansOfType方法获取bean集合