liveBook · Manning

Repository annotation

As explained in Spring Start Here, Second Edition

The Spring @Repository stereotype annotation marks a class as a data-access component eligible for bean registration.

In a Spring application, a repository is responsible for working with persisted data. The @Repository stereotype annotation marks a class with that responsibility and instructs Spring to add an instance as a bean in its context. section 4.3 section 12.2

Choose a stereotype that makes the class’s role clear:

  • Use @Repository for a class that works with data. section 4.5
  • Use @Service for a class that implements service logic. section 4.3
  • Use the more general @Component when there is no specific stereotype for the class’s responsibility. section 4.3

Annotate the implementation class, not its interface. For example, DBCommentRepository can implement the CommentRepository interface while carrying @Repository itself. section 4.3 section 4.5

Listing 12.5 Injecting a JdbcTemplate bean to work with persisted data
@Repository
public class PurchaseRepository {
 
  private final JdbcTemplate jdbc;
 
  public PurchaseRepository(   #A
    JdbcTemplate jdbc) {
 
    this.jdbc = jdbc;
  }
 
}

PurchaseRepository is a Spring bean that receives a JdbcTemplate through its constructor. It can use that dependency to work with the database. section 12.2

In the purchase example, Spring Boot configures the data source and JdbcTemplate when the H2 dependency is added. Without Spring Boot, those beans need to be defined in the Spring context. section 12.2

How Spring Start Here, Second Edition covers it

How deep it goes
Explains stereotype selection and bean registration, then demonstrates constructor injection into a repository.
Examples
Uses a comment repository implementation and a purchase repository that injects JdbcTemplate.
What you can do after
Apply it via Spring to register a repository class and make its data-access role clear.
How it connects
Connects stereotype annotations with dependency injection, interfaces, service logic, and data persistence.

Also explained in

Compare how 2 books explain repository annotation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.