同接口多个实现,根据业务指定实现类

149 阅读1分钟
//接口
public interface TestService {
    /**
     * 业务
     */
    void doTest();

    /**
     * 实现类标识区分
     * @return
     */
    String getTestServiceType();
}

//实现类1
@Service
public class Test1ServiceImpl implements TestService{
    @Override
    public void doTest() {
        System.out.println("111111111111");
    }
    @Override
    public String getTestServiceType() {
        return "01";
    }
}
//实现类2
@Service
public class Test2ServiceImpl implements TestService{
    @Override
    public void doTest() {
        System.out.println("222222");
    }
    @Override
    public String getTestServiceType() {
        return "02";
    }
}
//处理实现类集合
@Component
public class TestServceLocator implements ApplicationContextAware {
    /**
     * 用于保存接口实现类名及对应的类
     */
    public Map<String, TestService> map = new HashMap<String, TestService>();

    /**
     * 获取应用上下文并获取相应的接口实现类
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, TestService> mapHandle = new HashMap<String, TestService>();
        //根据接口类型返回相应的所有bean
        Map<String, TestService> retMap = applicationContext.getBeansOfType(TestService.class);
        for (Map.Entry<String, TestService> map : retMap.entrySet()) {
            mapHandle.put(map.getValue().getTestServiceType(), map.getValue());
        }
        map = mapHandle;
    }
    /**
     * 获取所有实现集合
     * @return
     */
    public Map<String, TestService> getMap() {
        return map;
    }
    /**
     * 获取对应实现类
     * @param key
     * @return
     */
    public TestService getService(String key) {
        return map.get(key);
    }
}
//使用
@RestController
@RequestMapping("/system")
@Api("测试API")
public class TestSystemApiController {
    //引用
    @Autowired
    private TestServceLocator testServceLocator;

    @RequestMapping(value = "/hello3" ,method = RequestMethod.POST)
    public APIResponse<String> hello3(String name) {
        Map<String, TestService> retMap = testServceLocator.getMap();
        retMap.get(name).doTest();
        return APIResponse.success("say hello to" + name);
    }
}