I encountered the @NoRepositoryBean
interface several times whilst reading the Spring Data documentation.
To quote from the documentation:
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
.
However, I am still not sure when and where to use it. Can someone please advise and give me a concrete usage example?
Best Answer
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:
Assume you'd like to add a method foo() to all of your repositories. You would start by adding a repo interface like this
You would also add the according implementation class, factory and so on. You concrete repository interfaces would now extend that intermediate interface:
Now assume you bootstrap - let's say Spring Data JPA - as follows:
You use
com.foobar
because you haveCustomerRepository
in the same package. The Spring Data infrastructure now has no way to tell that theMyBaseRepository
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.That scenario is also the reason why
CrudRepository
andPagingAndSortingRepository
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.Long story short: use the annotation to prevent repository interfaces from being picked up as candidates to end up as repository bean instances eventually.