为什么我不能在多个控制器中使用 JPA 存储库?



我正在使用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,但服务需要它。如果没有注释,整个页面就无法工作。为什么会这样?

使用字段自动布线时,字段不能是最终字段。首先创建实例(使用null值(,然后更新自动连接的字段。如果他们是决赛,那就不可能做到。

由于您使用的是@RequiredArgsConstructor,因此您可以删除@Autowired。这将使Spring使用构造函数autowiring;它将在调用构造函数时找到依赖项。

最新更新