Spring Boot 使用策略模式指定Service实现类

时间:2022-07-23
本文章向大家介绍Spring Boot 使用策略模式指定Service实现类,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

话不多说,直接上代码

编写策略接口类

public interface DemoService {
    void doQuery();
}

编写策略实现类

@Service("test1")
@Slf4j
public class Test1ServiceImpl implements DemoService {
    @Override
    public void doQuery() {
        // do something
    }
}
@Service("test2")
@Slf4j
public class Test2ServiceImpl implements DemoService {
    @Override
    public void doQuery() {
        // do something
    }
}

构建策略工厂, Service自动注入

@Component
public class DemoStrategyFactory {

    @Autowired
    Map<String, DemoService> DemoServices = new ConcurrentHashMap<>();

    public DemoService getDemoService(String component){
        DemoService demoService = DemoServices.get(component);
        if(demoService== null) {
            throw new RuntimeException("策略模式没找到对应实现类");
        }
        return demoService;
    }
}

Controller中直接使用

@Autowired
private DemoStrategyFactory demoStrategyFactory;

    @PostMapping("/test")
    public void test(@Valid @RequestParam String functionId){
        // eg: functionId = "test2" 
        DemoService demoService = demoStrategyFactory.getDemoService(functionId);
        demoService.doQuery();
    }