如何優雅的處理SpringBoot中的多個實現類

接口

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 aSwitch;

    @GetMapping("/service/{s}")
    public String getService(@PathVariable("s") String s) {
        final MyService myService = aSwitch.get(s);
        return myService.get();
    }
}

測試

訪問:http://localhost:8080/config/service/myServiceImpl1,返回:Impl_1

訪問:http://localhost:8080/config/service/myServiceImpl2,返回:Impl_2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章