Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring annotations @Repository and @Service

Tags:

spring

What are the advantages of using @Repository and @Service?

Don't tell me about component scanning etc., I am looking forward to something extra benefits or features that are there if at all.

what happens if I don't use it? what is that I would be missing?

like image 259
BlueSky Avatar asked Jun 06 '11 18:06

BlueSky


People also ask

What is @service and @repository in Spring?

@Component is a generic stereotype for any Spring-managed component. @Service annotates classes at the service layer. @Repository annotates classes at the persistence layer, which will act as a database repository.

What is the difference between @component @repository @service and @controller?

@Component is a generic stereotype for any Spring-managed component or bean. @Repository is a stereotype for the persistence layer. @Service is a stereotype for the service layer. @Controller is a stereotype for the presentation layer (spring-MVC).

What is @repository annotation in Spring?

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

Can we interchange @service and @repository annotation?

There are no problem occur when I interchange the @service and @repository annotation in the spring MVC.


2 Answers

There are a few reasons:

  1. It's easier to target pointcuts with more specific annotations. Do not underestimate the usefulness of this!
  2. The @Repository annotation carries with it some additional functionality: it causes exceptions to be wrapped up as DataAccessExceptions.
  3. The @Service annotation may gain additional semantics in the future but it's not happened yet…
like image 157
Donal Fellows Avatar answered Sep 21 '22 13:09

Donal Fellows


The @Repository annotation (introduced in Spring 2.0) and @Service annotation (introduced in Spring 2.5) are specialization of the @Component annotation.

The main advantage of using @Repository or @Service over @Component is that it's easy to write an AOP pointcut that targets, for instance, all classes annotated with @Repository.

Also, the specialized annotations help to clearly demarcate application layers (in a standard 3 tiers application).

like image 25
Luciano Fiandesio Avatar answered Sep 21 '22 13:09

Luciano Fiandesio