java - 了解 Spring Data JPA @NoRepositoryBean 接口(interface)

标签 java spring jpa spring-data spring-data-jpa

在阅读 Spring Data 文档时,我多次遇到 @NoRepositoryBean 接口(interface)。

引用文档:

If you're using automatic repository interface detection using the Spring namespace using the interface just as is will cause Spring trying to create an instance of MyRepository. This is of course not desired as it just acts as indermediate between Repository and the actual repository interfaces you want to define for each entity. To exclude an interface extending Repository from being instantiated as repository instance annotate it with @NoRepositoryBean.

但是,我仍然不确定何时何地使用它。有人可以建议并给我一个具体的用法示例吗?

最佳答案

注解用于避免为实际上符合 repo 接口(interface)标准但不打算成为一个标准的接口(interface)创建存储库代理。仅当您开始使用功能扩展所有存储库时才需要它。举个例子吧:

假设您想将方法 foo() 添加到所有存储库。您可以从添加这样的 repo 接口(interface)开始

public interface com.foobar.MyBaseInterface<…,…> extends CrudRepository<…,…> {

  void foo();
}

您还可以添加相应的实现类、工厂等。现在,您的具体存储库接口(interface)将扩展该中间接口(interface):

public interface com.foobar.CustomerRepository extends MyBaseInterface<Customer, Long> {

}

现在假设你引导 - 比如说 Spring Data JPA - 如下:

<jpa:repositories base-package="com.foobar" />

你使用 com.foobar 因为你在同一个包中有 CustomerRepository。 Spring Data 基础设施现在无法判断 MyBaseRepository 不是具体的存储库接口(interface),而是充当中间存储库以公开附加方法。所以它会尝试为它创建一个存储库代理实例并失败。您现在可以使用 @NoRepositoryBean 来注释这个中间接口(interface),本质上告诉 Spring Data:不要为这个接口(interface)创建存储库代理 bean。

这种情况也是CrudRepositoryPagingAndSortingRepository也带有这个注解的原因。如果包扫描偶然发现了这些(因为您不小心以这种方式配置了它),则 Bootstrap 将失败。

长话短说:使用注释来防止存储库接口(interface)被选为候选最终成为存储库 bean 实例。

关于java - 了解 Spring Data JPA @NoRepositoryBean 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11576831/

相关文章:

java - JTextField.getText() 返回 null 值,即使它里面有内容

java - 使用 Java 中的 Google Admin SDK Directory API 为域创建 Gmail 帐户

java - Spring boot通用字符串修剪序列化

java - JPA:2个应用程序需要更新一个对象

java - 在 JPA 中,如何知道持久性异常是否是由特定数据库触发器引起的?

java - 正则表达式在捕获之前仅与两个相似的 URL 进行非常具体的匹配

用于将 CSV 文件上传到数据库的 Java 桌面应用程序

java - Spring MVC Google Search Console 验证

java - 获取通用基础存储库的参数类型名称

java - JPA - EclipseLink - 如何更改默认模式