Difference between @Component, @Repository & @Service annotations in Spring

Posted on Sept. 17, 2019
spring boot
annotations
1024

@Component:

What’s special about @Component ?
<context:component-scan> only scans @Component and does not look for @Controller@Service and @Repository in general. They are scanned because they themselves are annotated with @Component.<context:component-scan> picks them up and registers their following classes as beans, just as if they were annotated with @Component.

@Service :

@Component
public @interface Service {
   //some logic
}

@Repository :

@Component
public @interface Repository {
  //some logic
}

@Controller :

@Component
public @interface Controller {
   //some logic
}

Special type annotations are also scanned, because they themselves are annotated with @Component annotation, which means they are also @Components. If we define our own custom annotation and annotate it with @Component, it will also get scanned with <context:component-scan>

@Repository

This is to indicate that the class defines a data repository.

What’s special about @Repository?

In addition to pointing out, that this is an Annotation based Configuration@Repository’s job is to catch platform specific exceptions and re-throw them as one of Spring’s unified unchecked exception.

@Controller

The @Controller annotation indicates that a particular class serves the role of a controller. The @Controller annotation acts as a stereotype for the annotated class, indicating its role.

What’s special about @Controller?

We cannot switch this annotation with any other like @Service or @Repository, even though they look same. The dispatcher scans the classes annotated with @Controller and detects methods annotated with @RequestMapping annotations within them. We can use @RequestMapping on/in only those methods whose classes are annotated with @Controller and it will NOT work with @Component@Service@Repository etc...

@Service

@Service beans hold the business logic and call methods in the repository layer.

What’s special about @Service?

Apart from the fact that it's used to indicate, that it's holding the business logic, there’s nothing else noticeable in this annotation




0 comments

Please log in to leave a comment.