美文网首页JAVA框架
Spring Boot 使用策略模式指定Service实现类

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

作者: 夹胡碰 | 来源:发表于2020-06-22 17:54 被阅读0次

话不多说,直接上代码

编写策略接口类

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();
    }

相关文章

网友评论

    本文标题:Spring Boot 使用策略模式指定Service实现类

    本文链接:https://www.haomeiwen.com/subject/idkffktx.html