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?
转载于:https://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-service-annotations-in
They are almost the same - all of them mean that the class is a Spring bean. @Service
, @Repository
and @Controller
are specialized @Component
s. 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 translationAnother 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.
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) │
└────────────┴─────────────────────────────────────────────────────┘
Use of @Service
and @Repository
annotations are important from database connection perspective.
@Service
for all your web service type of DB connections@Repository
for all your stored proc DB connectionsIf 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.
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
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
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.
@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,
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.
@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.
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
}
}
@Service
or @Repositroy
or @Controller
annotation by default @Component
annotation is going to existence on top of the classThere 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.
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.
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:
aspect-oriented
, these can be a good candidate for pointcuts
)@Repository
annotation will add some functionality to your bean (some automatic exception translation to your bean persistence layer).@RequestMapping
can only be added to classes which are annotated by @Controller
.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.
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.
@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.
@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
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.
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 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.
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.
@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");
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.
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.
@Component
This annotation is used on classes to indicate a Spring component.It marks the Java class as a bean or component so that the component-scanning mechanism of Spring can add it into the application context.
@Repository
This annotation is used on Java classes that directly access the database.It works as a marker for any class that fulfills the role of repository or Data Access Object.This annotation has an automatic translation feature. For example, when an exception occurs in the @Repository, there is a handler for that exception and there is no need to add a try-catch block.
@Service
It marks a Java class that performs some service, such as executing business logic, performing calculations, and calling external APIs. This annotation is a specialized form of the @Component
annotation intended to be used in the service layer.
@Controller
This annotation is used to indicate the class is a Spring controller.
@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:
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
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.
@component
@controller
@Repository
@service
@RestController
These are all StereoType annotations. If we placed @controller on top of class. It will not become controller class based on the different layers(components) we can annotate with this annotations but compiler will not do anything about this just for developer understanding purpose we can choose based on the components which annotations we have to write
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.
Before you learn the difference between @Component, @Service, @Controller, and @Repository
annotations in Spring framework, it's important to understand the role of @Component
annotation in Spring. During initial release of Spring, all beans are used to be declared in an XML file. For a large project, this quickly becomes a massive task and Spring guys recognize the problem rather quickly. In later versions, they provide annotation-based dependency injection and Java-based configuration. From Spring 2.5 annotation-based dependency injection was introduced, which automatically scans and register classes as Spring bean which is annotated using @Component
annotation. This means you don't to declare that bean using the tag and inject the dependency, it will be done automatically by Spring. This functionality was enabled and disabled using <context:component-scan>
tag.
Now that you know what does @Component
annotation does let's see what does @Service, @Controller, and @Repository
annotation do. They are nothing but the specialized form of @Component
annotation for certain situations. Instead of using @Component
on a controller class in Spring MVC, we use @Controller
, which is more readable and appropriate.
By using that annotation we do two things, first, we declare that this class is a Spring bean and should be created and maintained by Spring ApplicationContext, but also we indicate that its a controller in MVC setup. This latter property is used by web-specific tools and functionalities.
For example, DispatcherServlet
will look for @RequestMapping
on classes which are annotated using @Controller
but not with @Component
.
This means @Component
and @Controller
are same with respect to bean creation and dependency injection but later is a specialized form of former. Even if you replace @Controller
annotation with @Compoenent
, Spring can automatically detect and register the controller class but it may not work as you expect with respect to request mapping.
Same is true for @Service
and @Repository
annotation, they are a specialization of @Component
in service and persistence layer. A Spring bean in the service layer should be annotated using @Service
instead of @Component
annotation and a spring bean in persistence layer should be annotated with @Repository
annotation.
By using a specialized annotation we hit two birds with one stone. First, they are treated as Spring bean and second you can put special behavior required by that layer.
For example, @Repository's
not only helping in annotation based configure but also catch Platform specific exceptions and re-throw them as one of Spring’s unified unchecked exception.
Though for that you also need to declare org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
as Spring bean in your application context.
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.
I hope after reading this you will have clear Understanding regarding @Component, @Service, @Controller, and @Repository
.
Thanks for giving your time and reading my post.