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

引用文档:



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

最佳答案

注释用于避免为实际上与存储库接口(interface)的条件匹配但不打算成为接口(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实例。

10-02 05:05