我对使用 Spring 相当陌生,并且遇到了一个似乎无法解决的问题。我正在尝试使用一个名为优化规划器 https://docs.optaplanner.org/7.6.0.Final/optaplanner-docs/html_single/index.html#plannerIntroduction。在这种情况下,我或多或少地遵循一个简单的课程安排程序,视频是我正在做的部分发生在 51:00。
我的问题是,该过程的一个步骤需要依赖注入,当我构建/运行 Spring 应用程序时,我收到以下错误:
Description:
Field solverManager in com.java.optaplex.resource.MainResource required a bean of type 'org.optaplanner.core.api.solver.SolverManager' that could not be found.
The injection point has the following annotations:
- @javax.inject.Inject()
Action:
Consider defining a bean of type 'org.optaplanner.core.api.solver.SolverManager' in your configuration.
Process finished with exit code 1
我已经使用 Gradle 来管理我的 optaplanner 包,我可以看到依赖项存在(它是一个名为 SolverManager 的接口)。我不明白为什么它无法找到/生成 bean。我假设 Spring 会动态生成 bean,就像使用 @Autowired 装饰器时创建 JPA 存储库的 bean 一样。我尝试将 SolverManager 代码复制并粘贴到项目根目录下的自己的文件中,并在其上尝试了一些装饰器(例如 @Component),希望 Spring 能够检测到它,但它仍然抛出相同的错误,我不确定什么去做。
我在 GitHub 上创建了一个非常简单的演示应用程序here https://github.com/kriegsmaschine/optaplanner.simple.demo有错误。错误在文件中src/main/java/com/java/optaplex/resource/MainResource.java
另外,在 IntelliJ 中 SolverManager 实例求解器管理器(参见下面的代码)突出显示并表示:
Could not autowire. No beans of 'SolverManager<Test, Long>' type found.
MainResource.java:
package com.java.optaplex.resource;
import com.java.optaplex.pojo.Test;
import org.optaplanner.core.api.solver.SolverManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.inject.Inject;
@RestController
@RequestMapping("/api")
public class MainResource {
// THE OFFENDING LINE IS HERE
@Inject
SolverManager<Test, Long> solverManager;
@GetMapping("/test")
public Test test () {
return new Test("Result message here");
}
}
为了清楚起见,我在求解器管理器声明中的测试类是:
测试.java
package com.java.optaplex.pojo;
public class Test {
private String message;
public Test(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
我意识到我的示例代码实际上并没有使用 SolverManager,我只是希望构建时的错误停止,以便我可以继续开发它。我只是想提供一个导致错误的非常简单的案例。
最后,我的 Gradle 依赖项如下所示:
构建.gradle:
plugins {
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
id 'war'
}
group = 'com.java'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
// https://mvnrepository.com/artifact/org.optaplanner/optaplanner-core
compile group: 'org.optaplanner', name: 'optaplanner-core', version: '7.36.1.Final'
compile group: 'javax.inject', name: 'javax.inject', version: '1'
}
test {
useJUnitPlatform()
}