Understanding the Spring Data JPA @NoRepositoryBean interface

Viewed 52109

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?

2 Answers

We can declare a new interface as our custom method:

@NoRepositoryBean
public interface ExtendedRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
    List<T> findByAttributeContainsText(String attributeName, String text);
}

Our interface extends the JpaRepository interface so that we'll benefit from all the standard behavior.

You'll also notice we added the @NoRepositoryBean annotation. This is necessary because otherwise, the default Spring behavior is to create an implementation for all subinterfaces of Repository.

public interface ExtendedStudentRepository extends ExtendedRepository<Student, Long> {
}
Related