【问题标题】:Why can't I use a JPA repository in more than one controller?为什么我不能在多个控制器中使用 JPA 存储库?
【发布时间】: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


    【解决方案1】:

    当您使用字段自动装配时,字段不能是最终的。首先创建实例(使用null 值),然后更新自动装配字段。如果它们是最终的,那将无法完成。

    由于您使用的是@RequiredArgsConstructor,因此您只需删除@Autowired。这将使 Spring 使用构造函数自动装配;它会在调用构造函数时找到依赖关系。

    【讨论】:

    • 但为什么它在OneController 中有效?
    • 好问题,它也不应该工作。
    • 感谢您的回答,也很抱歉造成混乱。我已经编辑了这个问题,因为我省略了其他看起来不相关的部分,但实际上,它与问题有关。我不知道为什么会这样。我刚刚随机删除了一些行,它神奇地起作用了。 :-(
    • 额外的构造函数让一切变得不同。这个构造函数不是由 Lombok 管理的,它只会创建一个额外的构造函数。这意味着此构造函数必须遵循所有常规规则 - 每个 final 字段必须在构造函数完成后恰好初始化一次。你只设置了dateUtil,没有设置myRepository。
    • RequiredArgsConstructor 创建了一个构造函数,该构造函数接受所有必需(最终)字段的参数。 myRepository 字段不是最终的,因此不会由构造函数设置。这意味着它必须单独自动接线。把它改成final,你就不再需要用@Autowired注解了,因为创建的构造函数会设置它,这个构造函数会被Spring自动装配。
    猜你喜欢
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    相关资源
    最近更新 更多