Announcement Announcement Module
No announcement yet.
Spring Context's "@Repository" vs. Spring Data's "Repository<T, ID>" Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring Context's "@Repository" vs. Spring Data's "Repository<T, ID>"

    Spring Context provides an annotation org.springframework.stereotype.Repository .
    From the Javadoc:
    [org.springframework.stereotype.Repository] indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects".
    On the other hand, Spring Data provides an interface<T, ID extends Serializable> .

    To me, both things seem to have the same intention. Are there best practices when to favor one over the other? Is it beneficial to add the @Repository annotation to a subtype of Repository<T, ID>?

  • #2
    No. Both types server different purposes. @Repository is used to annotate arbitrary classes to activate exception translation (persistence technology specific exceptions -> Spring's DataAccessException hierarchy). The repository interface is used by the Spring Data infrastructure to pick up user repository interfaces.

    We essentially had to introduce the latter as we cannot simply re-purpose the semantics of the already available annotation. Plus, the interface carries additional typing information (domain type, id type). The semantics of @Repository gets automatically activated when using Spring Data repositories, so there's no need to annotate the interfaces in turn.


    • #3
      Oliver, thank you for your competent answer! I just realized that Spring Data's class SimpleJpaRepository<T, ID extends Serializable> is annotated with @org.springframework.stereotype.Repository, therefore making SimpleJpaRepository eligible to Spring Framework's exception translation.