In this article, I’d love to help you understand the meaning, purpose and usage of the @Repository annotation in Spring framework with some code examples.

You know, @Repository is a class-level annotation indicates that an annotated class is a “Repository”. A repository class should implement code relates to persistent layer or DAO (Data Access Objects) of a specific domain, e.g. UserRepository encapsulates storage, retrieval, and search behavior of a collection of User objects.

That’s the semantic purpose of using @Repository annotation: specify the role of a class as a repository, which encapsulates code of persistence/DAO layer for a specific business domain.

And the technical purpose is that the annotated class will be a candidate for auto-detection when using annotation-based configuration and classpath scanning. When Spring container scans and finds a class annotated with @Repository annotation, it will create a managed bean of the class in the application context. The managed bean will be eligible for used by other components through dependency injection, such as via @Autowired field or constructor injection.

Also, if Spring Data is used, the annotated class is eligible for Spring exception translation that automatically translates native resource exceptions (e.g. JDBC exceptions) to Spring’s DataAccessException hierarchy.

Now, let’s look at an example that uses @Repository annotation. Say, we have a domain model class as follows:

package net.codejava;

public class User {
	private int id;
	private String name;

	protected User(int id, String name) {
		this.id = id;
		this.name = name;
	}

	// getters and setters...
	
	// override toString()....
	
	// override equals() and hashCode()...
	
}
In the persistence layer, we define a generic DAO interface as follows:

package net.codejava;

import java.util.List;

public interface BaseDAO<T> {

	public T save(T entity);
	
	public T get(Integer id);
	
	public List<T> findAll();
}
And below is a concrete implementation example of UserRepository:

package net.codejava;

import java.util.*;
import java.util.stream.Collectors;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository implements BaseDAO<User> {

	private Map<Integer, User> repository = new TreeMap<>();
	
	@Override
	public User save(User user) {
		return repository.put(user.getId(), user);
	}

	@Override
	public User get(Integer id) {
		return repository.get(id);
	}

	@Override
	public List<User> findAll() {
		return repository.entrySet()
				.stream().map(entry -> entry.getValue())
				.collect(Collectors.toList());
	}

}
Note that the implementation code here is for demo purpose. You can see the @Repository annotation is used at the class level. Thus it’s possible to inject an instance of UserRepository in the service class, as shown below:

package net.codejava;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

	@Autowired private UserRepository repo;
	
	public List<User> list() {
		return repo.findAll();
	}
}


As you can see, because @Autowired is used, Spring will inject the managed bean of type UserRepository into an instance of this service class.

If you’re curious, write a small test program as shown in the below example:

package net.codejava;

import java.util.List;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringApplication {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.scan("net.codejava");
		context.refresh();
		
		UserRepository userRepo = (UserRepository) context.getBean("userRepository");
		
		userRepo.save(new User(1, "John Doe"));
		userRepo.save(new User(2, "Tim Cook"));
		
		List<User> users = userRepo.findAll();
		users.forEach(System.out::println);
		
	}

}
This program will scan classes under the package net.codejava, and then it will get the managed bean with the name userRepository from the application context. Then it uses the repository to save two User objects and list all users.

Those are some code examples about @Respository annotation in Spring framework. I hope you also find my explanation above helpful. You can watch the following video to see the coding in action:

 

Reference:

                Annotation Interface Repository (Spring Docs)

 

Other Spring Annotations:

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment