配置指定的Solution类无@PlanningSolution注解,多方案类场景报错求助
解决OptaPlanner多解决方案类配置报错问题
核心前提
OptaPlanner的硬性规则:所有作为规划解决方案的类,无论用XML还是注解配置,都必须添加@PlanningSolution注解。你遇到的报错,就是因为指定的Solution类缺少这个注解,框架无法识别它是合法的解决方案载体。
多解决方案类的实现方案
要在单个应用中使用多个解决方案类,不需要放弃注解,按以下方式操作即可:
- 给每个解决方案类都加上
@PlanningSolution注解,各自定义对应的实体集合、分数计算器(或约束提供器)、问题事实等核心元素。 - 为每个解决方案类单独编写Solver XML配置,比如创建多个独立的配置文件,或者在同一文件中定义多个
solver节点,分别指定对应的solutionClass、entityClass、约束提供器等。 - 在代码中根据业务需求,加载对应配置文件来实例化针对不同解决方案类的Solver。
配置示例
针对两个不同解决方案类的XML配置片段:
<!-- SolutionA对应的Solver配置 --> <solver> <solutionClass>com.example.SolutionA</solutionClass> <entityClass>com.example.EntityA</entityClass> <scoreDirectorFactory> <constraintProviderClass>com.example.ConstraintProviderA</constraintProviderClass> </scoreDirectorFactory> <!-- 其他Solver配置(如终止条件、启发式算法等) --> </solver>
<!-- SolutionB对应的Solver配置 --> <solver> <solutionClass>com.example.SolutionB</solutionClass> <entityClass>com.example.EntityB</entityClass> <scoreDirectorFactory> <constraintProviderClass>com.example.ConstraintProviderB</constraintProviderClass> </scoreDirectorFactory> <!-- 其他Solver配置 --> </solver>
代码示例
根据需求加载对应配置创建Solver:
// 初始化针对SolutionA的Solver SolverFactory<SolutionA> solverFactoryA = SolverFactory.create(new FileInputStream("solver-config-a.xml")); Solver<SolutionA> solverA = solverFactoryA.buildSolver(); // 初始化针对SolutionB的Solver SolverFactory<SolutionB> solverFactoryB = SolverFactory.create(new FileInputStream("solver-config-b.xml")); Solver<SolutionB> solverB = solverFactoryB.buildSolver();
优化提示
如果多个配置有重复内容,可以通过XML的<import>标签引入公共配置片段,减少代码冗余,但每个解决方案类的核心标识(solutionClass、约束提供器等)必须单独定义。
内容的提问来源于stack exchange,提问作者chalapathinagavarma bhupathira
相关产品推荐
相关产品推荐

