Spring @Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.

Spring @Repository Annotation

Spring Repository annotation is a specialization of @Component annotation, so Spring Repository classes are autodetected by spring framework through classpath scanning.

Spring Repository is very close to DAO pattern where DAO classes are responsible for providing CRUD operations on database tables. However, if you are using Spring Data for managing database operations, then you should use Spring Data Repository interface.

Spring Repository Example

Let’s look at a simple example where we will create a Spring Repository class. We will not use database operations, rather we will provide a repository for an Object.

Create a maven project in Eclipse or any other IDE you use, then add spring core dependency.

Below image shows our final project structure in Eclipse.


Let’s create the model class for which we will implement a spring repository.

Before we implement Repository class, I have created a generic ObjectRepository interface to provide the contract for our repository class to implement.

I am using Generics here, it’s a powerful technology to provide loosely coupled contract for the applications to implement.

Now let’s look at our Repository class implementation.

Note that I am using an in-memory Map to store the object data, you can use any other mechanisms too.

Spring Repository Test

Our Spring Repository is ready, let’s create a main class and test it out.

Just run the class as Java Application and you should get following output.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: