了解Spring Data JPA @NoRepositoryBean接口 [英] Understanding the Spring Data JPA @NoRepositoryBean interface
问题描述
我在阅读Spring Data文档时多次遇到 @NoRepositoryBean
界面。
I encountered the @NoRepositoryBean
interface several times whilst reading the Spring Data documentation.
引用来自文档:
如果您正在使用
Spring命名空间使用接口进行自动存储库接口检测,那将导致Spring
尝试创建MyRepository实例。这当然不是
,因为它只是在Repository和你想为每个实体定义的
实际存储库接口之间起中间作用。
排除扩展存储库的接口被实例化为
存储库实例使用@NoRepositoryBean
注释它。
但是,我仍然不确定何时何地使用它。有人可以建议并给我一个具体的用法示例吗?
However, I am still not sure when and where to use it. Can someone please advise and give me a concrete usage example?
推荐答案
注释用于避免为实际的接口创建存储库代理匹配repo接口的标准,但不是一个。只有在您开始使用功能扩展所有存储库时才需要它。让我举个例子:
The annotation is used to avoid creating repository proxies for interfaces that actually match the criteria of a repo interface but are not intended to be one. It's only required once you start going into extending all repositories with functionality. Let me give you an example:
假设您想要为所有存储库添加方法foo()。你可以先添加一个这样的repo界面
Assume you'd like to add a method foo() to all of your repositories. You would start by adding a repo interface like this
public interface com.foobar.MyBaseInterface<…,…> extends CrudRepository<…,…> {
void foo();
}
您还可以添加相应的实现类,工厂等。您具体的存储库接口现在将扩展该中间接口:
You would also add the according implementation class, factory and so on. You concrete repository interfaces would now extend that intermediate interface:
public interface com.foobar.CustomerRepository extends MyBaseInterface<Customer, Long> {
}
现在假设你引导 - 让我们说Spring Data JPA - 如下:
Now assume you bootstrap - let's say Spring Data JPA - as follows:
<jpa:repositories base-package="com.foobar" />
你使用 com.foobar
因为你有同一个包中的 CustomerRepository
。 Spring Data基础结构现在无法告诉 MyBaseRepository
不是具体的存储库接口,而是充当中间存储库来公开其他方法。因此它会尝试为它创建一个存储库代理实例并失败。您现在可以使用 @NoRepositoryBean
来注释此中间接口,从根本上告诉Spring Data:不要为此接口创建存储库代理bean。
You use com.foobar
because you have CustomerRepository
in the same package. The Spring Data infrastructure now has no way to tell that the MyBaseRepository
is not a concrete repository interface but rather acts as intermediate repo to expose the additional method. So it would try to create a repository proxy instance for it and fail. You can now use @NoRepositoryBean
to annotate this intermediate interface to essentially tell Spring Data: don't create a repository proxy bean for this interface.
这种情况也是 CrudRepository
和 PagingAndSortingRepository
带来这个注释的原因。如果软件包扫描意外地选择了这些(因为你不小心这样配置),引导程序就会失败。
That scenario is also the reason why CrudRepository
and PagingAndSortingRepository
carry this annotation as well. If the package scanning picked those up by accident (because you've accidentally configured it this way) the bootstrap would fail.
长话短说:使用注释来防止存储库接口作为候选者最终成为存储库bean实例。
Long story short: use the annotation to prevent repository interfaces from being picked up as candidates to end up as repository bean instances eventually.
这篇关于了解Spring Data JPA @NoRepositoryBean接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!