15

I'm not sure if I understand it correctly so want to clarify. If I want to create a repository for my entity eg.:

public interface BookRepository extends JpaRepository<Book, Id> {}

Should I annotate it with @Repository? According to this question @Repository annotation translates exceptions from SQL to persistence ones but doesn't JpaRepostiory already do that? What's the best practice - to annotate or not?

Community
  • 1
  • 1
doublemc
  • 3,021
  • 5
  • 34
  • 61
  • 3
    No, you don't need to when using Spring Data JPA. The Spring Data infrastructure scans for all interfaces extending `Repository` and automatically generates proxied implementations for them. – manish Mar 10 '17 at 08:03
  • See also: https://stackoverflow.com/questions/51918181/why-isnt-necessary-repository-for-this-spring-boot-web-app – Jens Schauder Oct 13 '22 at 13:04

2 Answers2

27

While using JpaRepository you don't need to annotate the interface with @Repository

It is just an interface and the concrete implementation is created dynamically as a proxy object by Spring and the JDBC Exceptions are handled there.

You need to use @Repository when you create a Custom DAO, so that spring creates a bean and handles the exception properly.

Cummings
  • 128
  • 2
  • 13
Avinash
  • 4,115
  • 2
  • 22
  • 41
0

You need to annotate it with @Repository so spring knows it should instantiate that class as a bean. The @Component, @Service and @Repository annotations all serve the same purpose in that regard. @Repository narrows the scope to a service that specifically deals with obtaining and storing data.

httPants
  • 1,832
  • 1
  • 11
  • 13