Home » Java » What's the difference between @Component, @Repository & @Service annotations in Spring?

What's the difference between @Component, @Repository & @Service annotations in Spring?

Posted by: admin November 2, 2017 Leave a comment

Questions:

Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?

In other words, if I have a Service class and I change the annotation from @Service to @Component, will it still behave the same way?

Or does the annotation also influence the behavior and functionality of the class?

Answers:

From Spring Documentation:

In Spring 2.0 and later, the @Repository annotation is a marker for
any class that fulfills the role or stereotype (also known as Data
Access Object or DAO) of a repository. Among the uses of this marker
is the automatic translation of exceptions.

Spring 2.5 introduces further stereotype annotations: @Component,
@Service, and @Controller. @Component is a generic stereotype for any
Spring-managed component. @Repository, @Service, and @Controller are
specializations of @Component for more specific use cases, for
example, in the persistence, service, and presentation layers,
respectively.

Therefore, you can annotate your component classes with @Component,
but by annotating them with @Repository, @Service, or @Controller
instead, your classes are more properly suited for processing by tools
or associating with aspects. For example, these stereotype annotations
make ideal targets for pointcuts.

Thus, if you are choosing between using @Component or @Service for
your service layer, @Service is clearly the better choice. Similarly,
as stated above, @Repository is already supported as a marker for
automatic exception translation in your persistence layer.

| Annotation | Meaning                                             |
+------------+-----------------------------------------------------+
| @Component | generic stereotype for any Spring-managed component |
| @Repository| stereotype for persistence layer                    |
| @Service   | stereotype for service layer                        |
| @Controller| stereotype for presentation layer (spring-mvc)      |

Questions:
Answers:

They are almost the same – all of them mean that the class is a Spring bean. @Service, @Repository and @Controller are specialized @Components. You can choose to perform specific actions with them. For example:

  • @Controller beans are used by spring-mvc
  • @Repository beans are eligible for persistence exception translation

Another thing is that you designate the components semantically to different layers.

One thing that @Component offers is that you can annotate other annotations with it, and then use them the same way as @Service.

For example recently I made:

@Component
@Scope("prototype")
public @interface ScheduledJob {..}

So all classes annotated with @ScheduledJob are spring beans and in addition to that are registered as quartz jobs. You just have to provide code that handles the specific annotation.

Questions:
Answers:

@Component is equivalent to

<bean>

@Service, @Controller, @Repository = {@Component + some more special functionality}

That mean Service, The Controller and Repository are functionally the same.

The three annotations are used to separate “Layers” in your application,

  • Controllers just do stuff like dispatching, forwarding, calling service methods etc.
  • Service Hold business Logic, Calculations etc.
  • Repository are the DAOs (Data Access Objects), they access the database directly.

Now you may ask why separate them: (I assume you know AOP-Aspect Oriented Programming)

Let’s say you want to Monitors the Activity of the DAO Layer only. You will write an Aspect (A class) class that does some logging before and after every method of your DAO is invoked, you are able to do that using AOP as you have three distinct Layers and are not mixed.

So you can do logging of DAO “around”, “before” or “after” the DAO methods. You could do that because you had a DAO in the first place. What you just achieved is Separation of concerns or tasks.

Imagine if there were only one annotation @Controller, then this component will have dispatching, business logic and accessing database all mixed, so dirty code!

Above mentioned is one very common scenario, there are many more use cases of why to use three annotations.

Questions:
Answers:

As many of the answers already state what these annotations are used for, we’ll here focus on some minor differences among them.

First the Similarity

First point worth highlighting again is that with respect to scan-auto-detection and dependency injection for BeanDefinition all these annotations (viz., @Component, @Service,
@Repository, @Controller) are the same. We can use one in place
of another and can still get our way around.


Differences between @Component, @Repository, @Controller and @Service

@Component

This is a general-purpose stereotype annotation indicating that the class is a spring 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.

Just take a look at @Controller, @Service and @Repository annotation definitions:

@Component
public @interface Service {
    ….
}

 

@Component
public @interface Repository {
    ….
}

 

@Component
public @interface Controller {
    …
}

Thus, it’s not wrong to say that @Controller, @Service and @Repository are special types of @Component annotation. <context:component-scan> picks them up and registers their following classes as beans, just as if they were annotated with @Component.

They are scanned because they themselves are annotated with @Component annotation. If we define our own custom annotation and annotate it with @Component, then 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. And for this, we’re provided with PersistenceExceptionTranslationPostProcessor, that we are required to add in our Spring’s application context like this:

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

This bean post processor adds an advisor to any bean that’s annotated with @Repository so that any platform-specific exceptions are caught and then rethrown as one of Spring’s unchecked data access exceptions.


@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 @RequestMapping annotations within them. We can only use @RequestMapping on @Controller annotated classes.


@Service

@Services hold business logic and call method in repository layer.

What’s special about @Service?

Apart from the fact that it is used to indicate that it’s holding the business logic, there’s no noticeable speciality that this annotation provides, but who knows, spring may add some additional exceptional in future.


What else?

Similar to above, in future Spring may choose to add special functionalities for @Service, @Controller and @Repository based on their layering conventions. Hence its always a good idea to respect the convention and use them in line with layers.

Questions:
Answers:

In Spring @Component, @Service, @Controller, and @Repository are Stereotype annotations which is used for:

@Controller: where your request mapping from presentation page done i.e. Presentation layer won’t go to any other file it goes directly to @Controller class and check for requested path in @RequestMapping annotation which written before method calls if necessary.

@Service: All business logic is here i.e. Data related calculations and all.This annotation of business layer in which our user not directly call persistence method so it will call this methods using this annotation. It will request @Repository as per user request

@Repository:This is Persistence layer(Data Access Layer) of application which used to get data from database. i.e. all the Database related operations are done by repository.

@Component – Annotate your other components (for example REST resource classes) with component stereotype.

Indicates that an annotated class is a “component“. Such classes are
considered as candidates for auto-detection when using
annotation-based configuration and classpath scanning.

Other class-level annotations may be considered as identifying a
component as well, typically a special kind of component: e.g. the
@Repository annotation or AspectJ’s @Aspect annotation.

enter image description here

Questions:
Answers:

Spring 2.5 introduces further stereotype annotations: @Component, @Service and @Controller. @Component serves as a generic stereotype for any Spring-managed component; whereas, @Repository, @Service, and @Controller serve as specializations of @Component for more specific use cases (e.g., in the persistence, service, and presentation layers, respectively). What this means is that you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. Of course, it is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are making a decision between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

@Component – Indicates a auto scan component.
@Repository – Indicates DAO component in the persistence layer.
@Service – Indicates a Service component in the business layer.
@Controller – Indicates a controller component in the presentation layer.

reference :- http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s12.html

Questions:
Answers:
@Component – Indicates a auto scan component.  
@Repository – Indicates DAO component in the persistence layer.  
@Service – Indicates a Service component in the business layer.   
@Controller – Indicates a controller component in the presentation layer.  

You will noticed that all @Repository,@Service or @Controller are annotated with @Component. So, can we use just @Component for all the components for auto scanning? Yes, you can, and Spring will auto scan all your components with @Component annotated.

It’s working fine, but not a good practice, for readability, you should always declare @Repository,@Service or @Controller for a specified layer to make your code more easier to read.

Questions:
Answers:

Use of @Service and @Repository annotations are important from database connection perspective.

  1. Use @Service for all your web service type of DB connections
  2. Use @Repository for all your stored proc DB connections

If you do not use the proper annotations, you may face commit exceptions overridden by rollback transactions. You will see exceptions during stress load test that is related to roll back JDBC transactions.

Questions:
Answers:

Difference Between @Component, @Service and @Repository

Major difference between these stereotypes is they are used for different classification.

In a multitier application, we will have different layers like presentation, service, business, data access etc. When a class is to be annotated for auto-detection by Spring, then we should use the respective stereotype as below.

@Component – generic and can be used across application.
@Service – annotate classes at service layer level.
@Repository – annotate classes at persistence layer, which will act as database repository.

If technically they are going to be same then why do we need to use these at different layers level. Why not use the same at all layers. For example, if we use @Service in all layers, all the beans will get instantiated and no issues. There is a minor difference, for example consider @Repository.

The postprocessor automatically looks for all exception translators (implementations of the PersistenceExceptionTranslator interface) and advises all beans marked with the @Repository annotation so that the discovered translators can intercept and apply the appropriate translation on the thrown exceptions.

Similar to the above, in future Spring may choose to add value for @Service, @Controller and @Repository based on their layering conventions. To that additional feature advantage its better to respect the convention and use them in line with layers.

Other than the above, with respect to scan-auto-detection, dependency injection for BeanDefinition @Component, @Service, @Repository, @Controller are same.

Questions:
Answers:

@Repository @Service and @Controller are serves as specialization of @Component for more specific use on that basis you can replace @Service to @Component but in this case you loose the specialization.

1. **@Repository**   - Automatic exception translation in your persistence layer.
2. **@Service**      - It indicates that the annotated class is providing a business service to other layers within the application.

Questions:
Answers:

all these annotations are type of stereo type type of annotation,the difference between these three annotations are

  • If we add the @Component then it tells the role of class is a component class it means it is a class consisting some logic,but it
    does not tell whether a class containing a specifically business or
    persistence or controller logic so we don’t use directly this
    @Component annotation
  • If we add @Service annotation then it tells that a role of class consisting business logic
  • If we add @Repository on top of class then it tells that a class consisting persistence logic
  • Here @Component is a base annotation for @Service,@Repository and @Controller annotations

for example

package com.spring.anno;
@Service
public class TestBean
{
    public void m1()
    {
       //business code
    }
}

package com.spring.anno;
@Repository
public class TestBean
{
    public void update()
    {
       //persistence code
    }
}
  • whenever we adds the @Service or @Repositroy or @Controller annotation by default @Component annotation is going to existence on top of the class
Questions:
Answers:

In a multitier application, we will have different layers like presentation, service, business, data access etc. When a class is to be annotated for auto-detection by Spring, then we should use the respective stereotype as below.

  • @Component – generic and can be used across application.
  • @Service – annotate classes at service layer level.
  • @Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
  • @Repository – annotate classes at persistence layer, which will act as database repository.
Questions:
Answers:

Spring @Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework.

@Component is a generic annotation. Difference of @Service, @Repository, @Controller with @Component is they are special cases of @Component and used for particular purposes. The difference is just classification only.

For all these annotations (stereotypes), technically the core purpose is same. Spring automatically scans and identifies all these classes that are annotated with “ @Component, @Service, @Repository, @Controller” and registers Bean Definition with ApplicationContext.

Questions:
Answers:

Spring provides four different types of auto component scan annotations, they are @Component, @Service, @Repository and @Controller. Technically, there is no difference between them, but every auto component scan annotation should be used for a special purpose and with in the defined layer.

@Component: It is a basic auto component scan annotation, it indicates annotated class is a auto scan component.

@Controller: Annotated class indicates that it is a controller components, and mainly used at presentation layer.

@Service: It indicates annotated class is a Service component in the business layer.

@Repository: You need to use this annotation with in the persistence layer, this acts like database repository.

One should choose more specialised form of @Component while annotating their class as this annotation may contain specific behavior going forward.

Questions:
Answers:

1.Major difference between these stereotypes is they are used for different classification.

2.In a multitier application, we will have different layers like presentation, service, business, data access etc. When a class is to be annotated for auto-detection by Spring, then we should use the respective stereotype as below.

  • @Component – generic and can be used across application.
  • @Service – annotate classes at service layer level.
  • @Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
  • @Repository – annotate classes at persistence layer, which will act as database repository. If technically they are going to be same then why do we need to use these at different layers level. Why not use the same at all layers. For example, if we use @Service in all layers, all the beans will get instantiated and no issues. There is a minor difference, for example consider @Repository.

The postprocessor automatically looks for all exception translators
(implementations of the PersistenceExceptionTranslator interface) and
advises all beans marked with the @Repository annotation so that the
discovered translators can intercept and apply the appropriate
translation on the thrown exceptions.

  1. Similar to the above, in future Spring may choose to add value for
    @Service, @Controller and @Repository based on their layering
    conventions. To that additional feature advantage it’s better to
    respect the convention and use them in line with layers.
  2. Other than the above, with respect to scan-auto-detection, dependency
    injection for BeanDefinition @Component, @Service, @Repository,
    @Controller are same.
  3. As per Spring documentation :
    The @Repository annotation is a marker for any class that fulfills the role or stereotype of a repository (also known as Data Access Object or DAO). Among the uses of this marker is the automatic translation of exceptions as described in Section 20.2.2, “Exception translation”.
    Spring provides further stereotype annotations: @Component, @Service, and @Controller. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively. Therefore, you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. It is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.
Questions:
Answers:

In Spring 4, latest version:

The @Repository annotation is a marker for any class that fulfills the
role or stereotype of a repository (also known as Data Access Object
or DAO). Among the uses of this marker is the automatic translation of
exceptions as described in Section 20.2.2, “Exception translation”.

Spring provides further stereotype annotations: @Component, @Service,
and @Controller. @Component is a generic stereotype for any
Spring-managed component. @Repository, @Service, and @Controller are
specializations of @Component for more specific use cases, for
example, in the persistence, service, and presentation layers,
respectively. Therefore, you can annotate your component classes with
@Component, but by annotating them with @Repository, @Service, or
@Controller instead, your classes are more properly suited for
processing by tools or associating with aspects. For example, these
stereotype annotations make ideal targets for pointcuts. It is also
possible that @Repository, @Service, and @Controller may carry
additional semantics in future releases of the Spring Framework. Thus,
if you are choosing between using @Component or @Service for your
service layer, @Service is clearly the better choice. Similarly, as
stated above, @Repository is already supported as a marker for
automatic exception translation in your persistence layer.

Questions:
Answers:

Even if we interchange @Component or @Repository or @service

It will behave the same , but one aspect is that they wont be able to catch some specific exception related to DAO instead of Repository if we use component or @ service

Questions:
Answers:

We can answer this according to java standard

Referring to JSR-330, which is now supported by spring, you can only use @Named to define a bean (Some how @[email protected]). So according to this standard there seems that there is no use to define stereo types (like @Repository, @Service, @Controller) to categories beans.

But spring define these stereotypes to

  1. Help developers define a better category for the competent. This categorizing may be come helpful in some cases. (For example when you are using aspect oriented, these can be good candidate for point cuts)
  2. Currently only @Repository annotation will add some functionality to your bean (some automatic exception translation to your bean persistence layer).
  3. If you are using spring mvc, the @RequestMapping can only be added to classes which are annotated by @Controller.
Questions:
Answers:

There is no difference between @Component,@Service,@Controller,@Repository.
@Component is the Generic annotation to represent the component of our MVC. But there will be several components as part of our MVC application like service layer components, persistence layer components and presentation layer components. So to differentiate them Spring people have given the other three annotations also.

To represent persistence layer components : @Repository

To represent service layer components : @Service

To represent presentation layer components : @Controller

or else you can use @Component for all of them.

Questions:
Answers:

Technically @Controller, @Service, @Repository are all same. All of them extends @Components.

From Spring source code:

Indicates that an annotated class is a “component”. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

We can directly use @Component for each and every beans, but for better understanding and maintainability of large application we use @Controller, @Service, @Repository.

Purpose of each annotations:

1) @Controller -> Classes annotated with this, are intended to receive request from the client side. First request comes to the Dispatcher Servlet, from where it passes the request to the particular controller using value of @RequestMapping annotation.

2) @Service -> Classes annotated with this, are intended to manipulate data, that we receive from client or fetch from database. All the manipulation with data should be done in this layer.

3) @Repository -> Classes annotated with this, are intended to connect with database. It can also be considered as DAO(Data access Object) layer. This layer should be restricted to CRUD (create,retrieve,update,delete) operations only.
If any manipulation is required, data should be send be send back to @Service layer.

If we interchange their place(use @Repository in place of @Controller), our application will work fine.

The main purpose of using three different @annotations is to provide better Modularity to the Enterprise application.

Questions:
Answers:

A @Service to quote spring documentation,

Indicates that an annotated class is a “Service”, originally defined
by Domain-Driven Design (Evans, 2003) as “an operation offered as an
interface that stands alone in the model, with no encapsulated state.”

May also indicate that a class is a “Business Service Facade” (in the
Core J2EE patterns sense), or something similar. This annotation is a
general-purpose stereotype and individual teams may narrow their
semantics and use as appropriate.

If you look at domain driven design by eric evans,

A SERVICE is an operation offered as an interface that stands alone in
the model, without encapsulating state, as ENTITIES and VALUE OBJECTS
do. SERVICES are a common pattern in technical frameworks, but they
can also apply in the domain layer. The name service emphasizes the
relationship with other objects. Unlike ENTITIES and VALUE OBJECTS, it
is defined purely in terms of what it can do for a client. A SERVICE
tends to be named for an activity, rather than an entity—a verb rather
than a noun. A SERVICE can still have an abstract, intentional
definition; it just has a different flavor than the definition of an
object. A SERVICE should still have a defined responsibility, and that
responsibility and the interface fulfilling it should be defined as
part of the domain model. Operation names should come from the
UBIQUITOUS LANGUAGE or be introduced into it. Parameters and results
should be domain objects. SERVICES should be used judiciously and not
allowed to strip the ENTITIES and VALUE OBJECTS of all their behavior.
But when an operation is actually an important domain concept, a
SERVICE forms a natural part of a MODEL-DRIVEN DESIGN. Declared in the
model as a SERVICE, rather than as a phony object that doesn’t
actually represent anything, the standalone operation will not mislead
anyone.

and a Repository as per Eric Evans,

A REPOSITORY represents all objects of a certain type as a conceptual
set (usually emulated). It acts like a collection, except with more
elaborate querying capability. Objects of the appropriate type are
added and removed, and the machinery behind the REPOSITORY inserts
them or deletes them from the database. This definition gathers a
cohesive set of responsibilities for providing access to the roots of
AGGREGATES from early life cycle through the end.

Questions:
Answers:

@Component is the top level generic annotation which makes the annotated bean to be scanned and available in the DI container

@Repository is specialized annotation and it brings the feature of converting all the unchecked exceptions from the DAO classes

@Service is specialized annotation. it do not bring any new feature as of now but it clarifies the intent of the bean

@Controller is specialized annotation which makes the bean MVC aware and allows the use of further annotation like @RequestMapping and all such

Here are more details