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

2020-08-14 16:32:08 浏览数 (1)

话不多说,直接上代码

编写策略接口类
代码语言:javascript复制
public interface DemoService {
    void doQuery();
}
编写策略实现类
代码语言:javascript复制
@Service("test1")
@Slf4j
public class Test1ServiceImpl implements DemoService {
    @Override
    public void doQuery() {
        // do something
    }
}
代码语言:javascript复制
@Service("test2")
@Slf4j
public class Test2ServiceImpl implements DemoService {
    @Override
    public void doQuery() {
        // do something
    }
}
构建策略工厂, Service自动注入
代码语言:javascript复制
@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中直接使用
代码语言:javascript复制
@Autowired
private DemoStrategyFactory demoStrategyFactory;

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

0 人点赞