2

I read online, @Service is for service layer (business logic), @Controller is for the API endpoint, and @Repository is used for persistence layer.

In my company, the code structure is:

Client -> Rest endpoint -> service -> DAO -> database

What confused me is, in the DAO layer, is annotated as @Service (actually both service and DAO layer also annotated as @Service)

Is there any reason that DAO annotated as @Service? i couldn't ask the programmer because he is on leave.

hades
  • 4,294
  • 9
  • 46
  • 71
  • http://stackoverflow.com/questions/35449808/what-will-happen-if-we-interchange-service-and-repository-annotation-in-the-sp – soorapadman Apr 12 '17 at 11:00

1 Answers1

6

With @Component, @Repository, @Service and @Controller annotations in place and after enabling automatic component scanning, spring will automatically import the beans into the container so you don’t have to define them explicitly to autowire them.

@Component

The @Component annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and pull it into the application context. To use this annotation, apply it over class as below:

@Repository

Although above use of @Component is good enough but you can use more suitable annotation that provides additional benefits specifically for DAOs i.e. @Repository annotation. The @Repository annotation is a specialization of the @Component annotation with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

@Service

The @Service annotation is also a specialization of the component annotation. It doesn’t currently provide any additional behavior over the @Component annotation, but it’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.

@Controller

@Controller annotation marks a class as a Spring Web MVC controller. It too is a @Component specialization, so beans marked with it are automatically imported into the DI container. When you add the @Controller annotation to a class, you can use another annotation i.e. @RequestMapping; to map URLs to instance methods of a class.

In your scenario, it has no impact on application flow whether you use @Service or @Repository, application will work as they are elligible for autowiring. But standard practice is to use @Repository for dao classes.

Monzurul Shimul
  • 8,132
  • 2
  • 28
  • 42