【发布时间】:2022-02-04 11:50:32
【问题描述】:
我正在使用 Java Spring Boot 构建一个 Web 应用程序。我正在尝试在两个不同的控制器中使用 JPA 存储库。但是,它只能在一个控制器内工作,而不能在另一个控制器内工作。
MyRepository.java
public interface MyRepository extends JpaRepository<Favorite, Long> { }
它在 OneController 中运行良好,没有任何问题。
OneController.java
@RestController
@RequiredArgsConstructor
public class OneController {
@Autowired
private final MyRepository myRepository;
}
但是,当我尝试在 AnotherController 中也使用它时,我收到以下消息:Variable 'myRepository' might not have been initialized.
AnotherController.java
@Controller
@RequiredArgsConstructor
public class AnotherController {
@Autowired
private MyService myService;
@Autowired
private final MyRepository myRepository;
private final DateUtil dateUtil;
public AnotherController(DateUtil dateUtil) {
this.dateUtil = dateUtil;
}
}
这里有什么问题?一个是 RestController,另一个是 Controller,但这似乎不是问题。
编辑: 对困惑感到抱歉。我在原始问题中省略了 AnotherController 中的构造函数,所以我添加了它。
由于某种原因,删除构造函数后,我不再看到消息Variable 'myRepository' might not have been initialized. 如果没有构造函数,一切正常。为什么会这样?
此外,存储库似乎不需要@Autowired,但服务需要它。没有注释,整个页面将无法工作。为什么会这样?
【问题讨论】:
标签: java spring spring-boot spring-data-jpa spring-repositories