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

30

2578

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 its 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?

Uncanny answered 26/7, 2011 at 9:10 Comment(6)
Being a developer with Microsoft background, I recall the semantic definition of services in the old MS SmartClientSoftwareFactory framework (now a long deprecated complex framework for distributed desktop apps). That definition (nicely documented by Rich Newman) defined the services as stateless reusable objects, preferably with singleton scope, that are used to perform business logic operations on other objects passed as arguments. I tend to view Spring services the same waySchiro
Doesn't matter!! Whatever works for you :) I've always hated this about Spring that they always tend to define "rules" for you, which only add trivial value to your application. Not to mention Spring comes with huge stack of its own.Alp
@Alp Sprting is a framework, define "rules" for you is its job :)Sellers
For an analogy, we can compare them to HTML semantic elements (main, article, aside etc.)Garcia
@TriCore, I agree mostly with you. Spring originally was a huge improvement, compared to J2EE, and nowdays Spring turned into a monster with such extra complexity. I used for ages CDI, it is way more clear with its DI rules and requirements. An injected POJO, becomes a CDI bean, just cause it is injected. What can be easier? And now compare it with Spring-way.Friedrick
Some static code analysis tools will apply additional rules to classes marked with these annotations.Genome
C
1811

From Spring Documentation:

The @Repository annotation is a marker for any class that fulfils 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 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 (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. @Repository, @Service, and @Controller can also 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 earlier, @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)
Calpac answered 1/8, 2011 at 10:20 Comment(2)
Do I understand correctly that as of today, there's no functional difference between @Component, @Service, and @Repository save for exception translation in the latter case?Vanillin
If uses to identify the class or file management structure, you could be component for generate a pdf, you could be use service for business logic and repository is useful to all transaction directly in the database.Tumescent
C
1077

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.

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. 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 re-thrown 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 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...

Note: If a class is already registered as a bean through any alternate method, like through @Bean or through @Component, @Service etc... annotations, then @RequestMapping can be picked if the class is also annotated with @RequestMapping annotation. But that's a different scenario.


@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; but who knows, Spring may add some additional exceptional in future.


What else?

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

Corking answered 24/7, 2016 at 6:43 Comment(1)
Fantastic Explanation. You've cleared up a lot of my misunderstandings. Coming from a university where we built all our projects from the bottom up, I had difficulty understanding why Spring Applications just worked even though you're not explicitly linking the program together yourself. The annotations make a lot of sense now, thank you!Clausewitz
C
468

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.

Cayenne answered 26/7, 2011 at 9:16 Comment(1)
@Component beans are auto detectable by spring container. You don't need to define bean in configuration file, it will be automatically detected at runtime by Spring.Cernuous
A
418

@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.

Anzio answered 23/5, 2014 at 5:15 Comment(3)
I got a fundamental question - are annotations used by spring mechanism or they are just for the programmer to remember what those pieces of code do?Boatwright
@Boatwright They are mainly for the Programmer to remember layers in the application. However @Respository also has automatic exception translation feature. Like when an exception occurs in a @Repository there is usually a handler for that exception and there is no need to add try catch blocks in the DAO class. It is used along with PersistenceExceptionTranslationPostProcessorAnzio
See https://mcmap.net/q/40486/-what-39-s-the-difference-between-component-repository-amp-service-annotations-in-spring for more details on the "+ some more specific functionality".Parliamentarian
F
251

In Spring @Component, @Service, @Controller, and @Repository are Stereotype annotations which are 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 checks 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 method 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 the database. i.e. all the Database related operations are done by the repository.

@Component - Annotate your other components (for example REST resource classes) with a 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

Fibrinolysis answered 25/3, 2014 at 8:0 Comment(1)
these answers are all nice and all but im pretty sure what most of us want is some code examples of the features that components like service offers that we can more concretely put in our head rather than just a general description like "business logic" belongs in this object. otherwise, we still assume "oh that's great and everything but i can still apply the same code to component"Diver
O
84

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 :- Spring Documentation - Classpath scanning, managed components and writing configurations using Java

Oid answered 15/5, 2013 at 12:48 Comment(0)
M
72

These are Stereotype annotations, candidate for autoscanning

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

From the 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 bean, but for better understanding and maintainability of a large application, we use @Controller, @Service, @Repository.

Purpose of each annotation:

  1. @Controller -> Classes annotated with this, are intended to receive a request from the client side. The first request comes to the Dispatcher Servlet, from where it passes the request to the particular controller using the value of @RequestMapping annotation.
  2. @Service -> Classes annotated with this, are intended to manipulate data, that we receive from the client or fetch from the 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 sent be send back to @Service layer.

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

Montreal answered 27/7, 2017 at 10:20 Comment(0)
M
51

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.

Morly answered 2/11, 2012 at 16:5 Comment(0)
C
31

@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.
Clevie answered 18/7, 2014 at 11:23 Comment(0)
K
31

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
Karonkaross answered 25/4, 2015 at 16:19 Comment(0)
C
30

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 within the defined layer.

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

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

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

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

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

Castor answered 3/1, 2016 at 5:10 Comment(0)
H
26

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.
Highwrought answered 26/11, 2015 at 5:10 Comment(0)
Y
25

@Component: you annotate a class @Component, it tells hibernate that it is a Bean.

@Repository: you annotate a class @Repository, it tells hibernate it is a DAO class and treat it as DAO class. Means it makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

@Service: This tells hibernate it is a Service class where you will have @Transactional etc Service layer annotations so hibernate treats it as a Service component.

Plus @Service is advance of @Component. Assume the bean class name is CustomerService, since you did not choose XML bean configuration way so you annotated the bean with @Component to indicate it as a Bean. So while getting the bean object CustomerService cust = (CustomerService)context.getBean("customerService"); By default, Spring will lower case the first character of the component – from ‘CustomerService’ to ‘customerService’. And you can retrieve this component with name ‘customerService’. But if you use @Service annotation for the bean class you can provide a specific bean name by

@Service("AAA")
public class CustomerService{

and you can get the bean object by

CustomerService cust = (CustomerService)context.getBean("AAA");
Ylangylang answered 9/11, 2017 at 13:32 Comment(0)
R
25

Annotate other components with @Component, for example, REST Resource classes.

    @Component
    public class AdressComp {
        .......
        ...// some code here    
    }

@Component is a generic stereotype for any Spring-managed component.

@Controller, @Service and @Repository are Specializations of @Component for specific use cases.

@Component in Spring

"Component Specialization"

Rotor answered 22/11, 2017 at 18:42 Comment(0)
M
25

The answers presented here are partially technically correct, but even though the response list is long and this will be at the bottom I thought it was worth putting an actually correct response in here too, just in case somebody stumbles upon it and learns something valuable from it. It's not that the rest of the answers are completely wrong, it's just that they aren't right. And, to stop the hordes of trolls, yes, I know that technically these annotations are effectively the same thing right now and mostly interchangeable even unto spring 5. Now, for the right answer:

These three annotations are completely different things and are not interchangeable. You can tell that because there are three of them rather than just one. They are not intended to be interchangeable, they're just implemented that way out of elegance and convenience.

Modern programming is invention, art, technique, and communication, in varying proportions. The communication bit is usually very important because code is usually read much more often than its written. As a programmer you're not only trying to solve the technical problem, you're also trying to communicate your intent to future programmers who read your code. These programmers may share neither your native language nor your social environment, and it is possible that they may be reading your code 50-years in the future (it's not as unlikely as you may think). It's difficult to communicate effectively that far into the future. Therefore, it is vital that we use the clearest, most efficient, correct, and communicative language available to us. We chose our words carefully to have maximum impact and be as clear as possible as to our intent.

For example, it is vital that @Repository is used when we're writing a repository, rather than @Component. The latter is a very poor choice of annotation for a repository because it does not indicate that we're looking at a repository. We can assume that a repository is also a spring-bean, but not that a component is a repository. With @Repository we are being clear and specific in our language. We are stating clearly that this is a repository. With @Component we are leaving it to the reader to decide what type of component they are reading, and they will have to read the whole class (and possibly a tree of subclasses and interfaces) to infer meaning. The class could then possibly be misinterpreted by a reader in the distant future as not being a repository, and we would have been partially responsible for this mistake because we, who knew full well that this is a repository, failed to be specific in our language and communicate our intent effectively.

I won't go into the other examples, but will state as clearly as I can: these annotations are completely different things and should be used appropriately, as per their intent. @Repository is for storage repositories and no other annotation is correct. @Service is for services and no other annotation is correct. @Controller is for components that are neither repositories nor services, and to use either of these in its place would also be incorrect. It might compile, it might even run and pass your tests, but it would be wrong and I would think less of you (professionally) if you were to do this.

There are examples of this throughout spring (and programming in general). You must not use @Controller when writing a REST API, because @RestController is available. You must not use @RequestMapping when @GetMapping is a valid alternative. Etc. Etc. Etc. You must choose the most specific exact and correct language you can to communicate your intent to your readers, otherwise, you are introducing risks into your system, and risk has a cost.

Finally, I'd like to bring up a point of order concerning Object-Oriented systems. One of the fundamental rules is that implementations can vary but interfaces shouldn't. Assuming that these annotations are the same thing is a very slippery slope and completely against OO. Although they may be implemented in an interchangeable way now, there is no guarantee that they will be in the future. Further, even within the same team, an engineer may decide to hang some behaviour off one or more of these annotations using aspects, or a platform engineer may choose to replace the implementation of one of these for operational reasons. You just don't know, nor should you -- in OO you rely on the interface, not the implementation.

Math answered 8/5, 2020 at 13:25 Comment(0)
C
22

Even if we interchange @Component or @Repository or @Service, it will behave the same, but one aspect is that they won't be able to catch some specific exception related to DAO instead of Repository if we use @Component or @Service.

Crabb answered 10/2, 2014 at 18:21 Comment(0)
F
21

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 (Somehow @Named=@Component). So according to this standard, there seems that there is no use to define stereotypes (like @Repository, @Service, @Controller) to categories beans.

But spring user these different annotations in different for the specific use, for example:

  1. Help developers define a better category for the competent. This categorizing may become helpful in some cases. (For example when you are using aspect-oriented, these can be a good candidate for pointcuts)
  2. @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.
Feingold answered 4/5, 2016 at 4:23 Comment(0)
A
17

@Component is the top-level generic annotation that makes the annotated bean be scanned and available in the DI container.

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

@Service is a specialized annotation. it does not bring any new features as of now but it clarifies the intent of the bean.

@Controller is a specialized annotation that makes the bean MVC aware and allows the use of further annotations like @RequestMapping and all such.

Here are more details.

Algor answered 21/12, 2016 at 9:12 Comment(1)
Quick question. What do you mean by converting all the unchecked exceptions from the DAO classes? Converting to what exactly?Microwatt
P
15

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.

Pig answered 20/6, 2016 at 9:30 Comment(0)
Y
15

Spring supports multiple types annotations such as @Component, @service, @Repository. All theses can be found under the org.springframework.stereotype package and @Bean can be found under org.springframework.context.annotation package.

When classes in our application are annotated with any of the above mentioned annotation then during project startup spring scan(using @ComponentScan) each class and inject the instance of the classes to the IOC container. Another thing the @ComponentScan would do is running the methods with @Bean on it and restore the return object to the Ioc Container as a bean.

Before we deep dive into ( @Component vs @service vs @Repository ) first it's better to understand the differences between @Bean and @Component

enter image description here


@Component vs @Repository vs @Service


In most typical applications, we have distinct layers like data access, presentation, service, business, etc. Additionally, in each layer we have various beans. To detect these beans automatically, Spring uses classpath scanning annotations.Then it registers each bean in the ApplicationContext.

Here's a short overview of a few of these annotations:

  • @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.

@Component Annotation

@Component is a class level annotation.We can use @Component across the application to mark the beans as Spring's managed components. Spring will only pick up and register beans with @Component, and doesn't look for @Service and @Repository in general.

They are registered in ApplicationContext because they are annotated with @Component

As stated, @Component is the parent of all stereotype annotations. When Spring performs a component scan, it only looks for classes marked with @Component annotations.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
    String value() default "";
}

We can use this annotation on all the classes and it won’t cause any difference.

@Service Annotation

We mark beans with @Service to indicate that they're holding the business logic. Besides being used in the service layer, there isn't any other special use for this annotation.

The @Service is child of component and used to denote classes from the service layer of the application.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
   @AliasFor(
       annotation = Component.class
   )
   String value() default "";
}

@Repository Annotation

@Repository’s job is to catch persistence-specific exceptions and re-throw them as one of Spring’s unified unchecked exceptions.

For this, Spring provides PersistenceExceptionTranslationPostProcessor, which we are required to add in our application context (already included if we're using Spring Boot):

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

This bean post processor adds an advisor to any bean that’s annotated with @Repository.

Similarly, @Repository is also a child of component annotation and used on the classes that belong to persistence data access layer and serves as a data repository.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

Summary

@Service and @Repository are special cases of @Component. They are technically the same, but we use them for the different purposes.It's always a good idea to choose the annotation based on their layer conventions.

Yonkers answered 5/11, 2021 at 6:33 Comment(0)
R
13

Good enough answers are here to explain the whats-the-difference-between-component-repository-service-annotations. I would like to share the difference between @Controller & @RestController

@Controller vs RestController

@RestController:

enter image description here

  • This annotation is a specialized version of @Controller which adds @Controller and @ResponseBody annotation automatically. so we do not have to add @ResponseBody to our mapping methods. That means @ResponseBody is default active.
  • If you use @RestController, you cannot return a view (By using ViewResolver in Spring/Spring-Boot)
  • @RestController also converts the response to JSON/XML automatically as @ResponseBody makes the returned objects to something that could be in the body, e.g. JSON or XML

@Controller

enter image description here

  • @Controller is used to mark classes as Spring MVC Controller. This annotation is just a specialized version of @Component and it allows the controller classes to be auto-detected based on classpath scanning.
  • @Controller you can return a view in Spring web MVC.

More Detailed View

Raby answered 4/7, 2019 at 7:22 Comment(0)
B
11

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.

Bethune answered 28/12, 2016 at 8:18 Comment(0)
B
10

Repository and Service are children of Component annotation. So, all of them are Component. Repository and Service just expand it. How exactly? Service has only ideological difference: we use it for services. Repository has particular exception handler.

Basidiomycete answered 3/10, 2018 at 2:32 Comment(0)
P
10

@Component acts as @Bean annotation in configuration class , register bean in spring context. Also it is parent for @Service, @Repository and @Controller annotation.

@Service, extends @Component annotation and has only naming difference.

@Repository - extends @Component annotation and translate all database exceptions into DataAccessException.

@Controller - acts as controller in MVC pattern. The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping annotations.

Papaw answered 19/4, 2020 at 0:50 Comment(0)
E
6

Explanation of stereotypes :

  • @Service - Annotate all your service classes with @Service. This layer knows the unit of work. All your business logic will be in Service classes. Generally methods of service layer are covered under transaction. You can make multiple DAO calls from service method, if one transaction fails all transactions should rollback.
  • @Repository - Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
  • @Component - Annotate your other components (for example REST resource classes) with component stereotype.
  • @Autowired - Let Spring auto-wire other beans into your classes using @Autowired annotation.

@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.

Originally answered here.

Exhaust answered 21/3, 2018 at 7:3 Comment(0)
S
5

Difference between @Component, @Repository, @Controller & @Service annotations

@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.

@Controller = @Component ( Internal Annotation ) + Presentation layer Features
@Service = @Component ( Internal Annotation ) + Service layer Features
@Component = Actual Components ( Beans )
@Repository = @Component ( Internal Annotation ) + Data Layer Features ( use for handling the Domain Beans )

Sufferance answered 6/8, 2019 at 7:25 Comment(0)
R
4

In spring framework provides some special type of annotations,called stereotype annotations. These are following:-

@RestController- Declare at controller level.
@Controller – Declare at controller level.
@Component – Declare at Bean/entity level.
@Repository – Declare at DAO level.
@Service – Declare at BO level.

above declared annotations are special because when we add <context:component-scan> into xxx-servlet.xml file ,spring will automatically create the object of those classes which are annotated with above annotation during context creation/loading phase.

Ruwenzori answered 5/7, 2018 at 19:11 Comment(0)
F
3

@Component, @ Repository, @ Service, @Controller:

@Component is a generic stereotype for the components managed by Spring @Repository, @Service, and @Controller are @Component specializations for more specific uses:

  • @Repository for persistence
  • @Service for services and transactions
  • @Controller for MVC controllers

Why use @Repository, @Service, @Controller over @Component? We can mark our component classes with @Component, but if instead we use the alternative that adapts to the expected functionality. Our classes are better suited to the functionality expected in each particular case.

A class annotated with @Repository has a better translation and readable error handling with org.springframework.dao.DataAccessException. Ideal for implementing components that access data (DataAccessObject or DAO).

An annotated class with @Controller plays a controller role in a Spring Web MVC application

An annotated class with @Service plays a role in business logic services, example Facade pattern for DAO Manager (Facade) and transaction handling

Feuillant answered 21/6, 2018 at 0:10 Comment(0)
S
1

In order to simplify this illustration, let us consider technicality by use case, These annotations are used to be injected and as I said literally "Used to be injected" , that mean, if you know how to use Dependency Injection "DI" and you should, then you will always look for these annotations, and by annotating the classes with these Stereo Types, you are informing the DI container to scan them to be ready for Injection on other places, this is the practical target.

Now lets move to each one; first @Service, If you are building some logic for specific business case you need to separate that in a place which will contain your business logic, this service is normal Class or you can use it as interface if you want , and it is written like this

@Service
public class Doer {
   // Your logic 
}

To use it in another class, suppose in Controller

@Controller
public class XController {
    // You have to inject it like this 
    @Autowired 
    private Doer doer;

    // Your logic
}

All are the same way when you inject them, @Repository it's an interface which apply the implementation for the Repository Pattern Repository design pattern, generally it's used when you are dealing with some data store or database, and you will find that, it contains multiple ready implementation for you to handle database operations; it can be CrudRepository, JpaRepository etc.

For example:

public interface DoerRepository implements JpaRepository<Long, XEntity> {
}

Finally the @Component, this is the generic form for registered beans in Spring, that's spring is always looking for bean marked with @Component to be registered, then both @Service and @Repository are special cases of @Component, however the common use case for component is when you're making something purely technical not for covering direct business case! like formatting dates or handing special request serialization mechanism and so on.

Spitz answered 30/4, 2019 at 20:21 Comment(0)
L
0

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

Yes, Each of annotation serves a special purpose, provides additional features and behavior.

@Repository: This provides additional features related to data access, persistence, class will be eligible for Spring data exceptions and other persistence related features.

@Controller: This indicates handling & mapping of http request (Even you can use specialized annotation for API calls as @RestController)

@Service: This acts as a business layer, having business logic, application specific logic, workflow.

We never know, in future spring releases, Each of the annotation could possibly enhance with purpose specific functionality add-on. So adhere to use annotation based on purpose will make future upgrade easier.

Lanfri answered 6/3 at 21:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.