在Spring中,@Component、@Repository和@Service注解的区别是什么?

时间:2023-01-24 00:11:23

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

在Spring中,@Component、@Repository和@Service注解可以互换使用吗?它们除了充当符号设备之外,还能提供任何特定的功能吗?

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?

换句话说,如果我有一个服务类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?

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

或者注释也会影响类的行为和功能吗?

28 个解决方案

#1


1061  

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.0和以后的版本中,@Repository注解是满足存储库角色或原型(也称为数据访问对象或DAO)的任何类的标记。该标记的使用之一是异常的自动翻译。

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.

Spring 2.5引入了进一步的原型注解:@Component, @Service和@Controller。@Component是任何spring管理组件的通用原型。@Repository、@Service和@Controller分别是针对更具体的用例(例如,在持久性、服务和表示层)的@Component的专门化。

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.

因此,您可以使用@Component对组件类进行注释,但是通过使用@Repository、@Service或@Controller对它们进行注释,您的类更适合通过工具进行处理或与方面关联。例如,这些模板注释是切入点的理想目标。

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.

因此,如果您正在为您的服务层选择使用@Component还是使用@Service,那么@Service显然是更好的选择。类似地,如上所述,@Repository已经被支持作为持久性层中自动异常转换的标记。

┌────────────┬─────────────────────────────────────────────────────┐
│ 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)      │
└────────────┴─────────────────────────────────────────────────────┘

#2


387  

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.

第一点值得再次强调的是,对于bean定义的扫描自动检测和依赖注入,所有这些注解(即,@Component, @Service, @Repository, @Controller)都是相同的。我们可以用一个代替另一个,还可以继续前进。


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

@Component

@ component

This is a general-purpose stereotype annotation indicating that the class is a spring component.

这是一个通用的原型注释,指示类是spring组件。

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.

@Component 只扫描@Component,不查找@Controller、@Service和@Repository。它们被扫描,因为它们本身被@Component注释。

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

看看@Controller、@Service和@Repository注释定义:

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

因此,说@Controller、@Service和@Repository是@Component注解的特殊类型并没有错。 获取它们并将它们的后续类注册为bean,就像使用@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>

它们被扫描,因为它们本身用@Component注释进行注释。如果我们定义自己的自定义注释并使用@Component对其进行注释,那么也会使用 对其进行扫描


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

除了指出这是基于注释的配置之外,@Repository的任务是捕获平台特定的异常并将其重新抛出为Spring的统一未检查异常之一。为此,我们提供了PersistenceExceptionTranslationPostProcessor,我们需要在Spring的应用程序上下文中添加如下内容:

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

这个bean post处理器向任何带有@Repository注解的bean添加一个advisor,以便捕获特定于平台的异常,然后作为Spring的未检查数据访问异常之一重新抛出。


@Controller

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

@Controller注释表明一个特定的类服务于一个控制器的角色。@Controller注释充当带注释的类的原型,表明它的角色。

What’s special about @Controller?

@ 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或@Repository)交换,即使它们看起来是相同的。dispatcher扫描带有@Controller的类并检测其中的@RequestMapping注释。我们只能在@Controller带注释的类上使用@RequestMapping。


@Service

@ service

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

@Services在repository层中保存业务逻辑和调用方法。

What’s special about @Service?

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

除了使用它来表示它持有业务逻辑之外,这个注释没有提供明显的特性,但是谁知道呢,spring将来可能会添加一些额外的异常。


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.

与上面类似,在未来的Spring可能会根据其分层约定为@Service、@Controller和@Repository添加特殊的功能。因此,尊重惯例并在层中使用它们总是一个好主意。

#3


383  

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:

它们几乎是一样的——所有这些都意味着类是一个Spring bean。@Service、@Repository和@Controller都是专门的@ component。您可以选择使用它们执行特定的操作。例如:

  • @Controller beans are used by spring-mvc
  • @Controller bean被spring-mvc使用。
  • @Repository beans are eligible for persistence exception translation
  • @Repository bean可以进行持久性异常转换

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.

@Component提供的一个特性是,您可以用它注释其他的注解,然后以与@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.

所以@ScheduledJob注释的所有类都是spring bean,除此之外,还注册为quartz job。您只需提供处理特定注释的代码。

#4


328  

@Component is equivalent to

@ component相当于

<bean>

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

@Service, @Controller, @Repository = {@Component +一些特殊功能}

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.

假设您只想监视DAO层的活动。您将编写一个方面(类)类,该类在每个DAO方法被调用之前和之后进行一些日志记录,您可以使用AOP来实现这一点,因为您有三个不同的层,并且没有混合。

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.

因此,可以对DAO方法“around”、“before”或“after”进行日志记录。你可以这么做,因为你首先有一个DAO。您刚刚实现的是关注点或任务的分离。

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

想象一下,如果只有一个注释@Controller,那么这个组件将会有调度、业务逻辑和访问数据库,这些都是混合的,那么脏的代码!

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

上面提到的是一个非常常见的场景,有更多的用例说明为什么要使用三个注释。

#5


184  

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

在Spring @Component中,@Service、@Controller和@Repository是用于:

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

@Controller:你从表示页面的请求映射完成的地方,也就是表示层不会转到任何其他文件,它会直接转到@Controller类,并在@RequestMapping注释中检查所请求的路径,如果需要的话,在方法调用之前写入。

@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

@Service:所有的业务逻辑都在这里,即数据相关的计算。业务层的这个注释,其中我们的用户不直接调用持久性方法,因此它将使用这个注释调用这个方法。它将根据用户请求请求请求@Repository

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

@Repository:这是应用程序的持久性层(数据访问层),用于从数据库中获取数据。即,所有与数据库相关的操作都由存储库完成。

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

@Component——用组件模板注释其他组件(例如REST资源类)。

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.

其他类级别的注释也可以被视为标识组件,通常是一种特殊的组件:例如@Repository注释或AspectJ的@Aspect注释。

在Spring中,@Component、@Repository和@Service注解的区别是什么?

#6


59  

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.

Spring 2.5引入了进一步的原型注解:@Component, @Service和@Controller。@Component是任何spring管理组件的通用原型;然而,@Repository、@Service和@Controller作为更具体用例(例如,在持久性、服务和表示层)的@Component的专门化。这意味着您可以使用@Component对组件类进行注释,但是通过使用@Repository、@Service或@Controller对它们进行注释,您的类更适合使用工具进行处理或与方面关联。例如,这些原型注释为切入点提供了理想的目标。当然,在Spring框架的未来版本中,@Repository、@Service和@Controller也可能带有附加的语义。因此,如果您正在为您的服务层使用@Component或@Service之间做出决定,那么@Service显然是更好的选择。类似地,如上所述,@Repository已经被支持作为持久性层中自动异常转换的标记。

@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

- Spring文档-类路径扫描,管理组件和使用Java编写配置。

#7


51  

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

您将注意到所有的@Repository、@Service或@Controller都带有@Component的注释。那么,我们是否可以仅使用@Component对所有组件进行自动扫描?是的,可以,Spring会自动扫描所有带有@Component注释的组件。

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.

它工作得很好,但不是一个好的实践,为了可读性,您应该始终为指定层声明@Repository、@Service或@Controller,以使您的代码更易于阅读。

#8


40  

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

从数据库连接的角度来看,使用@Service和@Repository注解很重要。

  1. Use @Service for all your web service type of DB connections
  2. 为所有web服务类型的DB连接使用@Service。
  3. Use @Repository for all your stored proc DB connections
  4. 为所有存储的proc DB连接使用@Repository。

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.

如果您不使用适当的注解,您可能会面临由回滚事务覆盖的提交异常。在压力负载测试期间,您将看到与回滚JDBC事务相关的异常。

#9


30  

Difference Between @Component, @Service and @Repository

@Component、@Service和@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.

在多层应用程序中,我们将有不同的层,如表示层、服务层、业务层、数据访问层等。当要对类进行注释,以便Spring自动检测时,我们应该使用相应的模板,如下所示。

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

@Component——通用的,可以跨应用程序使用。@Service -在服务层级别注释类。@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.

如果技术上它们是相同的,那么为什么我们需要在不同的层次上使用它们呢?为什么不在所有层都使用相同的。例如,如果我们在所有层中使用@Service,那么所有的bean都将被实例化,没有问题。有一个小的区别,例如考虑@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.

后处理器自动查找所有的异常转换器(PersistenceExceptionTranslator接口的实现),并通知所有标有@Repository注解的bean,以便被发现的翻译器能够拦截并对抛出的异常应用适当的翻译。

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.

与上述类似,在未来的Spring中,可能会根据其分层约定为@Service、@Controller和@Repository添加值。对于这个附加特性的优势,最好尊重约定,并与层一起使用它们。

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

除此之外,在扫描自动检测方面,BeanDefinition @Component的依赖注入,@Service, @Repository, @Controller的依赖注入是相同的。

#10


24  

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

@Repository @Service和@Controller作为@Component的专门化,在此基础上更具体地使用,您可以将@Service替换为@Component,但在本例中,您将忽略专门化。

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.

#11


23  

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
  • 如果我们添加@Component,那么它会告诉类的角色是一个组件类,它意味着它是一个包含一些逻辑的类,但是它不会告诉一个包含特定业务或持久性或控制器逻辑的类,所以我们不会直接使用这个@Component注释
  • If we add @Service annotation then it tells that a role of class consisting business logic
  • 如果我们添加@Service注释,那么它会告诉我们一个包含业务逻辑的类的角色
  • If we add @Repository on top of class then it tells that a class consisting persistence logic
  • 如果我们在类的顶部添加@Repository,那么它就告诉我们一个包含持久化逻辑的类
  • Here @Component is a base annotation for @Service,@Repository and @Controller annotations
  • 在这里,@Component是@Service、@Repository和@Controller注释的基本注释

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
  • 每当我们添加@Service或@Repositroy或@Controller注释时,默认的@Component注释就会出现在类的顶部

#12


18  

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.

在多层应用程序中,我们将有不同的层,如表示层、服务层、业务层、数据访问层等。当要对类进行注释,以便Spring自动检测时,我们应该使用相应的模板,如下所示。

  • @Component – generic and can be used across application.
  • @Component——通用的,可以跨应用程序使用。
  • @Service – annotate classes at service layer level.
  • @Service -在服务层级别注释类。
  • @Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
  • @Controller -在表示层级别上注释类,主要用于Spring MVC。
  • @Repository – annotate classes at persistence layer, which will act as database repository.
  • @Repository—持久层的类注释,它将充当数据库存储库。

#13


16  

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

使用@Component注释其他组件,例如REST资源类。

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

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

@Component是任何Spring托管组件的通用原型。

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

@Controller、@Service和@Repository是针对特定用例的@Component的专门化。

@Component in Spring

在Spring中,@Component、@Repository和@Service注解的区别是什么?

#14


15  

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

1。这些刻板印象的主要区别在于它们用于不同的分类。

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.

2。在多层应用程序中,我们将有不同的层,如表示层、服务层、业务层、数据访问层等。当要对类进行注释,以便Spring自动检测时,我们应该使用相应的模板,如下所示。

  • @Component – generic and can be used across application.
  • @Component——通用的,可以跨应用程序使用。
  • @Service – annotate classes at service layer level.
  • @Service -在服务层级别注释类。
  • @Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
  • @Controller -在表示层级别上注释类,主要用于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.
  • @Repository—持久层的类注释,它将充当数据库存储库。如果技术上它们是相同的,那么为什么我们需要在不同的层次上使用它们呢?为什么不在所有层都使用相同的。例如,如果我们在所有层中使用@Service,那么所有的bean都将被实例化,没有问题。有一个小的区别,例如考虑@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.

后处理器自动查找所有的异常转换器(PersistenceExceptionTranslator接口的实现),并通知所有标有@Repository注解的bean,以便被发现的翻译器能够拦截并对抛出的异常应用适当的翻译。

  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. 与上述类似,在未来的Spring中,可能会根据其分层约定为@Service、@Controller和@Repository添加值。为了获得额外的特性优势,最好尊重约定并与层一起使用它们。
  3. Other than the above, with respect to scan-auto-detection, dependency injection for BeanDefinition @Component, @Service, @Repository, @Controller are same.
  4. 除此之外,在扫描自动检测方面,BeanDefinition @Component的依赖注入,@Service, @Repository, @Controller的依赖注入是相同的。
  5. 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.
  6. 正如Spring文档所示:@Repository注解是满足存储库角色或原型的任何类的标记(也称为数据访问对象或DAO)。该标记的用途之一是将异常自动翻译为第20.2.2节“异常翻译”。Spring提供了进一步的模板注释:@Component, @Service和@Controller。@Component是任何spring管理组件的通用原型。@Repository、@Service和@Controller分别是针对更具体的用例(例如,在持久性、服务和表示层)的@Component的专门化。因此,您可以使用@Component对组件类进行注释,但是通过使用@Repository、@Service或@Controller对它们进行注释,您的类更适合通过工具进行处理或与方面关联。例如,这些原型注释为切入点提供了理想的目标。在Spring框架的未来版本中,@Repository、@Service和@Controller也可能带有附加的语义。因此,如果您正在为您的服务层选择使用@Component还是使用@Service,那么@Service显然是更好的选择。类似地,如上所述,@Repository已经被支持作为持久性层中自动异常转换的标记。

#15


14  

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

Spring @Component、@Service、@Repository和@Controller注释在Spring框架中使用类路径扫描进行自动bean检测。

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

@Component是一个通用注释。@Service、@Repository、@Controller与@Component的区别在于,它们是@Component的特殊情况,用于特定目的。区别仅仅是分类。

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.

对于所有这些注释(原型),技术上的核心目的是相同的。Spring自动扫描并标识所有这些用“@Component, @Service, @Repository, @Controller”注释的类,并向ApplicationContext注册Bean定义。

#16


14  

We can answer this according to java standard

我们可以根据java标准来回答这个问题

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.

引用现在由spring支持的JSR-330,您只能使用@Named来定义一个bean (@Named=@Component)。因此,根据这个标准,似乎没有用于对类别bean定义原型(如@Repository、@Service、@Controller)的方法。

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

但是spring用户这些不同的注释在特定的用途上是不同的,例如:

  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. 帮助开发人员为有能力的人定义一个更好的类别。这种分类在某些情况下可能会有帮助。(例如,当您使用面向方面的时候,这些是切入点的很好的候选者)
  3. @Repository annotation will add some functionality to your bean (some automatic exception translation to your bean persistence layer).
  4. @Repository注释将向bean添加一些功能(将一些自动异常转换为bean持久性层)。
  5. If you are using spring MVC, the @RequestMapping can only be added to classes which are annotated by @Controller.
  6. 如果您正在使用spring MVC, @RequestMapping只能添加到由@Controller注释的类中。

#17


14  

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.

Spring提供了四种不同类型的自动组件扫描注释,它们是@Component、@Service、@Repository和@Controller。从技术上讲,它们之间没有区别,但是每个自动组件扫描注释都应该用于特殊目的,并在定义的层中使用。

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

@Component:它是一个基本的自动组件扫描注解,它表明带注解的类是自动扫描的。

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

@Controller:带注释的类表示它是一个控制器组件,主要用于表示层。

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

@Service:它表示带注释的类是业务层中的服务组件。

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

@Repository:您需要在持久性层中使用此注释,这类似于数据库存储库。

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

当注释它们的类时,应该选择更专门化的@Component形式,因为这个注释可能包含特定的行为。

#18


13  

In Spring 4, latest version:

在Spring 4中,最新版本:

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

@Repository注释是满足存储库角色或原型的任何类的标记(也称为数据访问对象或DAO)。该标记的用途之一是将异常自动翻译为第20.2.2节“异常翻译”。

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.

Spring提供了进一步的模板注释:@Component, @Service和@Controller。@Component是任何spring管理组件的通用原型。@Repository、@Service和@Controller分别是针对更具体的用例(例如,在持久性、服务和表示层)的@Component的专门化。因此,您可以使用@Component对组件类进行注释,但是通过使用@Repository、@Service或@Controller对它们进行注释,您的类更适合通过工具进行处理或与方面关联。例如,这些原型注释为切入点提供了理想的目标。在Spring框架的未来版本中,@Repository、@Service和@Controller也可能带有附加的语义。因此,如果您正在为您的服务层选择使用@Component还是使用@Service,那么@Service显然是更好的选择。类似地,如上所述,@Repository已经被支持作为持久性层中自动异常转换的标记。

#19


12  

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

即使我们交换@Component或@Repository或@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

它的行为是相同的,但是一个方面是,如果我们使用组件或@服务,它们将无法捕获与DAO相关的特定异常,而不是存储库

#20


9  

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.

@Component、@Service、@Controller、@Repository之间没有区别。@Component是表示MVC组件的通用注释。但是作为MVC应用程序的一部分,会有几个组件,比如服务层组件、持久性层组件和表示层组件。为了区分它们,Spring的人也给出了另外三个注解。

To represent persistence layer components : @Repository

表示持久性层组件:@Repository

To represent service layer components : @Service

表示服务层组件:@Service

To represent presentation layer components : @Controller

表示表示层组件:@Controller

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

或者你也可以使用@Component。

#21


8  

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

技术上讲,@Controller, @Service, @Repository都是一样的。所有这些都扩展了@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.

我们可以直接为每个bean使用@Component,但是为了更好地理解和维护大型应用程序,我们使用@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.

1)@ controller类- >注释,旨在从客户端接收请求。第一个请求Dispatcher Servlet时,从它将请求传递给特定的控制器使用@RequestMapping注释的值。

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.

2) @Service -带有此注释的>类,用于操作我们从客户端接收或从数据库获取的数据。所有使用数据的操作都应该在这个层中完成。

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.

3) @Repository—带有此注释的>类,用于连接数据库。它也可以被看作是DAO(数据访问对象)层。这一层应该仅限于CRUD(创建、检索、更新、删除)操作。如果需要任何操作,应该将数据发送回@Service层。

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

如果我们交换它们的位置(使用@Repository代替@Controller),我们的应用程序就会运行良好。

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

使用三个不同的@annotation的主要目的是为企业应用程序提供更好的模块化。

#22


7  

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

@ component是*通用的注释使得带注释的bean被扫描和DI容器中可用

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

@专业注释和它带来的转换特性的所有未经检查的异常DAO类

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

@ service是专门的注释。到目前为止,它没有带来任何新特性,但是它澄清了bean的意图

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

@ controller是专业注释使得bean MVC意识到并允许使用进一步注释@RequestMapping和所有这些

Here are more details

这里有更多的细节

#23


6  

A @Service to quote spring documentation,

引用spring文档的@Service,

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.

表示一个带注释的类是一个“服务”,最初由域驱动设计(Evans, 2003)定义为“一个单独在模型中提供的接口,没有封装状态。”也可能表明类是“业务服务Facade”(在核心J2EE模式意义上),或者类似的东西。这个注释是一个通用的原型,每个团队可能会缩小他们的语义并适当地使用它们。

If you look at domain driven design by eric evans,

如果你看看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,

根据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.

代表了某种类型的所有对象存储库是一组概念(通常模拟)。它就像一个集合,除了有更详细的查询功能。对象适当类型的添加和删除,和背后的机械存储库从数据库中插入或删除它们。这个定义收集一组内聚的责任提供聚合的根源从早期生命周期结束。

#24


6  

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

@Component:您注释一个类@Component,它告诉hibernate它是一个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.

@:@您标注了一个类,它告诉hibernate DAO类和把它当作DAO类。意味着它使未经检查的异常(从DAO方法)资格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.

@Service:这告诉hibernate这是一个服务类,您将在其中使用@Transactional etc服务层注释,所以hibernate将它作为服务组件。

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是@Component的advance。假设bean类名是CustomerService,因为您没有选择XML bean配置方式,所以您使用@Component对bean进行了注释,以将其表示为bean。因此,在获取bean对象CustomerService cust = (CustomerService)context.getBean(“CustomerService”)时;默认情况下,Spring将把组件的第一个字符——从“CustomerService”降为“CustomerService”。您可以使用名称“customerService”检索此组件。但是,如果您对bean类使用@Service注释,您可以提供一个特定的bean名称by

@Service("AAA")
public class CustomerService{

and you can get the bean object by

你可以通过

CustomerService cust = (CustomerService)context.getBean("AAA");

#25


5  

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

此注释用于类以指示Spring组件。它将Java类标记为bean或组件,以便Spring的组件扫描机制可以将其添加到应用程序上下文中。

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

@该注释用于直接访问数据库的Java类。它是一个标记任何类,实现存储库的角色或数据访问对象。这个注释有自动翻译功能。例如,当一个例外发生在@ repository,有一个异常处理程序,不需要添加一个try - catch块。

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

@Service它标记一个执行某些服务的Java类,例如执行业务逻辑、执行计算和调用外部api。此注释是用于服务层的@Component注释的一种特殊形式。

@Controller This annotation is used to indicate the class is a Spring controller.

这个注释用于指示类是Spring控制器。

#26


2  

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.
  • @Service -用@Service注释所有的服务类。这一层知道功的单位。您的所有业务逻辑都将在服务类中。服务层的方法一般都包含在事务中。您可以从服务方法进行多个DAO调用,如果一个事务失败,那么所有事务都应该回滚。
  • @Repository - Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
  • @Repository—使用@Repository对所有DAO类进行注释。所有数据库访问逻辑都应该在DAO类中。
  • @Component - Annotate your other components (for example REST resource classes) with component stereotype.
  • @Component——用组件模板注释其他组件(例如REST资源类)。
  • @Autowired - Let Spring auto-wire other beans into your classes using @Autowired annotation.
  • @Autowired -让Spring使用@Autowired注释将其他bean自动连接到您的类中。

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

@Component是任何spring管理组件的通用原型。@Repository、@Service和@Controller分别是针对更具体的用例(例如,在持久性、服务和表示层)的@Component的专门化。

Originally answered here.

最初的答案。

#27


2  

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

@Component——通用的,可以跨应用程序使用。@Service -在服务层级别注释类。@Repository—持久层的类注释,它将充当数据库存储库。

#28


0  

@Component, @ Repository, @ Service, @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:

@Component是Spring @Repository、@Service和@Controller管理的组件的通用原型,@Component是用于更具体用途的@Component专门化:

  • @Repository for persistence
  • @的持久性
  • @Service for services and transactions
  • 服务和交易服务。
  • @Controller for MVC controllers
  • @ controller,MVC控制器

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.

为什么在@Component上使用@Repository, @Service, @Controller ?我们可以使用@Component来标记我们的组件类,但是如果我们使用另一种方法来适应预期的功能的话。我们的类更适合每个特定情况下所期望的功能。

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

使用“@Repository”注释的类具有更好的翻译和可读的错误处理能力,可以使用org.springframe . dao.dataaccessexception。理想的实现访问数据的组件(DataAccessObject或DAO)。

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

带有“@Controller”的带注释类在Spring Web MVC应用程序中扮演控制器角色

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

带有“@Service”的带注释的类在业务逻辑服务、DAO Manager (Facade)的示例Facade模式和事务处理中扮演角色

#1


1061  

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.0和以后的版本中,@Repository注解是满足存储库角色或原型(也称为数据访问对象或DAO)的任何类的标记。该标记的使用之一是异常的自动翻译。

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.

Spring 2.5引入了进一步的原型注解:@Component, @Service和@Controller。@Component是任何spring管理组件的通用原型。@Repository、@Service和@Controller分别是针对更具体的用例(例如,在持久性、服务和表示层)的@Component的专门化。

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.

因此,您可以使用@Component对组件类进行注释,但是通过使用@Repository、@Service或@Controller对它们进行注释,您的类更适合通过工具进行处理或与方面关联。例如,这些模板注释是切入点的理想目标。

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.

因此,如果您正在为您的服务层选择使用@Component还是使用@Service,那么@Service显然是更好的选择。类似地,如上所述,@Repository已经被支持作为持久性层中自动异常转换的标记。

┌────────────┬─────────────────────────────────────────────────────┐
│ 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)      │
└────────────┴─────────────────────────────────────────────────────┘

#2


387  

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.

第一点值得再次强调的是,对于bean定义的扫描自动检测和依赖注入,所有这些注解(即,@Component, @Service, @Repository, @Controller)都是相同的。我们可以用一个代替另一个,还可以继续前进。


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

@Component

@ component

This is a general-purpose stereotype annotation indicating that the class is a spring component.

这是一个通用的原型注释,指示类是spring组件。

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.

@Component 只扫描@Component,不查找@Controller、@Service和@Repository。它们被扫描,因为它们本身被@Component注释。

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

看看@Controller、@Service和@Repository注释定义:

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

因此,说@Controller、@Service和@Repository是@Component注解的特殊类型并没有错。 获取它们并将它们的后续类注册为bean,就像使用@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>

它们被扫描,因为它们本身用@Component注释进行注释。如果我们定义自己的自定义注释并使用@Component对其进行注释,那么也会使用 对其进行扫描


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

除了指出这是基于注释的配置之外,@Repository的任务是捕获平台特定的异常并将其重新抛出为Spring的统一未检查异常之一。为此,我们提供了PersistenceExceptionTranslationPostProcessor,我们需要在Spring的应用程序上下文中添加如下内容:

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

这个bean post处理器向任何带有@Repository注解的bean添加一个advisor,以便捕获特定于平台的异常,然后作为Spring的未检查数据访问异常之一重新抛出。


@Controller

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

@Controller注释表明一个特定的类服务于一个控制器的角色。@Controller注释充当带注释的类的原型,表明它的角色。

What’s special about @Controller?

@ 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或@Repository)交换,即使它们看起来是相同的。dispatcher扫描带有@Controller的类并检测其中的@RequestMapping注释。我们只能在@Controller带注释的类上使用@RequestMapping。


@Service

@ service

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

@Services在repository层中保存业务逻辑和调用方法。

What’s special about @Service?

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

除了使用它来表示它持有业务逻辑之外,这个注释没有提供明显的特性,但是谁知道呢,spring将来可能会添加一些额外的异常。


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.

与上面类似,在未来的Spring可能会根据其分层约定为@Service、@Controller和@Repository添加特殊的功能。因此,尊重惯例并在层中使用它们总是一个好主意。

#3


383  

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:

它们几乎是一样的——所有这些都意味着类是一个Spring bean。@Service、@Repository和@Controller都是专门的@ component。您可以选择使用它们执行特定的操作。例如:

  • @Controller beans are used by spring-mvc
  • @Controller bean被spring-mvc使用。
  • @Repository beans are eligible for persistence exception translation
  • @Repository bean可以进行持久性异常转换

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.

@Component提供的一个特性是,您可以用它注释其他的注解,然后以与@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.

所以@ScheduledJob注释的所有类都是spring bean,除此之外,还注册为quartz job。您只需提供处理特定注释的代码。

#4


328  

@Component is equivalent to

@ component相当于

<bean>

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

@Service, @Controller, @Repository = {@Component +一些特殊功能}

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.

假设您只想监视DAO层的活动。您将编写一个方面(类)类,该类在每个DAO方法被调用之前和之后进行一些日志记录,您可以使用AOP来实现这一点,因为您有三个不同的层,并且没有混合。

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.

因此,可以对DAO方法“around”、“before”或“after”进行日志记录。你可以这么做,因为你首先有一个DAO。您刚刚实现的是关注点或任务的分离。

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

想象一下,如果只有一个注释@Controller,那么这个组件将会有调度、业务逻辑和访问数据库,这些都是混合的,那么脏的代码!

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

上面提到的是一个非常常见的场景,有更多的用例说明为什么要使用三个注释。

#5


184  

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

在Spring @Component中,@Service、@Controller和@Repository是用于:

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

@Controller:你从表示页面的请求映射完成的地方,也就是表示层不会转到任何其他文件,它会直接转到@Controller类,并在@RequestMapping注释中检查所请求的路径,如果需要的话,在方法调用之前写入。

@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

@Service:所有的业务逻辑都在这里,即数据相关的计算。业务层的这个注释,其中我们的用户不直接调用持久性方法,因此它将使用这个注释调用这个方法。它将根据用户请求请求请求@Repository

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

@Repository:这是应用程序的持久性层(数据访问层),用于从数据库中获取数据。即,所有与数据库相关的操作都由存储库完成。

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

@Component——用组件模板注释其他组件(例如REST资源类)。

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.

其他类级别的注释也可以被视为标识组件,通常是一种特殊的组件:例如@Repository注释或AspectJ的@Aspect注释。

在Spring中,@Component、@Repository和@Service注解的区别是什么?

#6


59  

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.

Spring 2.5引入了进一步的原型注解:@Component, @Service和@Controller。@Component是任何spring管理组件的通用原型;然而,@Repository、@Service和@Controller作为更具体用例(例如,在持久性、服务和表示层)的@Component的专门化。这意味着您可以使用@Component对组件类进行注释,但是通过使用@Repository、@Service或@Controller对它们进行注释,您的类更适合使用工具进行处理或与方面关联。例如,这些原型注释为切入点提供了理想的目标。当然,在Spring框架的未来版本中,@Repository、@Service和@Controller也可能带有附加的语义。因此,如果您正在为您的服务层使用@Component或@Service之间做出决定,那么@Service显然是更好的选择。类似地,如上所述,@Repository已经被支持作为持久性层中自动异常转换的标记。

@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

- Spring文档-类路径扫描,管理组件和使用Java编写配置。

#7


51  

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

您将注意到所有的@Repository、@Service或@Controller都带有@Component的注释。那么,我们是否可以仅使用@Component对所有组件进行自动扫描?是的,可以,Spring会自动扫描所有带有@Component注释的组件。

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.

它工作得很好,但不是一个好的实践,为了可读性,您应该始终为指定层声明@Repository、@Service或@Controller,以使您的代码更易于阅读。

#8


40  

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

从数据库连接的角度来看,使用@Service和@Repository注解很重要。

  1. Use @Service for all your web service type of DB connections
  2. 为所有web服务类型的DB连接使用@Service。
  3. Use @Repository for all your stored proc DB connections
  4. 为所有存储的proc DB连接使用@Repository。

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.

如果您不使用适当的注解,您可能会面临由回滚事务覆盖的提交异常。在压力负载测试期间,您将看到与回滚JDBC事务相关的异常。

#9


30  

Difference Between @Component, @Service and @Repository

@Component、@Service和@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.

在多层应用程序中,我们将有不同的层,如表示层、服务层、业务层、数据访问层等。当要对类进行注释,以便Spring自动检测时,我们应该使用相应的模板,如下所示。

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

@Component——通用的,可以跨应用程序使用。@Service -在服务层级别注释类。@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.

如果技术上它们是相同的,那么为什么我们需要在不同的层次上使用它们呢?为什么不在所有层都使用相同的。例如,如果我们在所有层中使用@Service,那么所有的bean都将被实例化,没有问题。有一个小的区别,例如考虑@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.

后处理器自动查找所有的异常转换器(PersistenceExceptionTranslator接口的实现),并通知所有标有@Repository注解的bean,以便被发现的翻译器能够拦截并对抛出的异常应用适当的翻译。

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.

与上述类似,在未来的Spring中,可能会根据其分层约定为@Service、@Controller和@Repository添加值。对于这个附加特性的优势,最好尊重约定,并与层一起使用它们。

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

除此之外,在扫描自动检测方面,BeanDefinition @Component的依赖注入,@Service, @Repository, @Controller的依赖注入是相同的。

#10


24  

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

@Repository @Service和@Controller作为@Component的专门化,在此基础上更具体地使用,您可以将@Service替换为@Component,但在本例中,您将忽略专门化。

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.

#11


23  

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
  • 如果我们添加@Component,那么它会告诉类的角色是一个组件类,它意味着它是一个包含一些逻辑的类,但是它不会告诉一个包含特定业务或持久性或控制器逻辑的类,所以我们不会直接使用这个@Component注释
  • If we add @Service annotation then it tells that a role of class consisting business logic
  • 如果我们添加@Service注释,那么它会告诉我们一个包含业务逻辑的类的角色
  • If we add @Repository on top of class then it tells that a class consisting persistence logic
  • 如果我们在类的顶部添加@Repository,那么它就告诉我们一个包含持久化逻辑的类
  • Here @Component is a base annotation for @Service,@Repository and @Controller annotations
  • 在这里,@Component是@Service、@Repository和@Controller注释的基本注释

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
  • 每当我们添加@Service或@Repositroy或@Controller注释时,默认的@Component注释就会出现在类的顶部

#12


18  

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.

在多层应用程序中,我们将有不同的层,如表示层、服务层、业务层、数据访问层等。当要对类进行注释,以便Spring自动检测时,我们应该使用相应的模板,如下所示。

  • @Component – generic and can be used across application.
  • @Component——通用的,可以跨应用程序使用。
  • @Service – annotate classes at service layer level.
  • @Service -在服务层级别注释类。
  • @Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
  • @Controller -在表示层级别上注释类,主要用于Spring MVC。
  • @Repository – annotate classes at persistence layer, which will act as database repository.
  • @Repository—持久层的类注释,它将充当数据库存储库。

#13


16  

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

使用@Component注释其他组件,例如REST资源类。

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

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

@Component是任何Spring托管组件的通用原型。

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

@Controller、@Service和@Repository是针对特定用例的@Component的专门化。

@Component in Spring

在Spring中,@Component、@Repository和@Service注解的区别是什么?

#14


15  

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

1。这些刻板印象的主要区别在于它们用于不同的分类。

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.

2。在多层应用程序中,我们将有不同的层,如表示层、服务层、业务层、数据访问层等。当要对类进行注释,以便Spring自动检测时,我们应该使用相应的模板,如下所示。

  • @Component – generic and can be used across application.
  • @Component——通用的,可以跨应用程序使用。
  • @Service – annotate classes at service layer level.
  • @Service -在服务层级别注释类。
  • @Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
  • @Controller -在表示层级别上注释类,主要用于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.
  • @Repository—持久层的类注释,它将充当数据库存储库。如果技术上它们是相同的,那么为什么我们需要在不同的层次上使用它们呢?为什么不在所有层都使用相同的。例如,如果我们在所有层中使用@Service,那么所有的bean都将被实例化,没有问题。有一个小的区别,例如考虑@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.

后处理器自动查找所有的异常转换器(PersistenceExceptionTranslator接口的实现),并通知所有标有@Repository注解的bean,以便被发现的翻译器能够拦截并对抛出的异常应用适当的翻译。

  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. 与上述类似,在未来的Spring中,可能会根据其分层约定为@Service、@Controller和@Repository添加值。为了获得额外的特性优势,最好尊重约定并与层一起使用它们。
  3. Other than the above, with respect to scan-auto-detection, dependency injection for BeanDefinition @Component, @Service, @Repository, @Controller are same.
  4. 除此之外,在扫描自动检测方面,BeanDefinition @Component的依赖注入,@Service, @Repository, @Controller的依赖注入是相同的。
  5. 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.
  6. 正如Spring文档所示:@Repository注解是满足存储库角色或原型的任何类的标记(也称为数据访问对象或DAO)。该标记的用途之一是将异常自动翻译为第20.2.2节“异常翻译”。Spring提供了进一步的模板注释:@Component, @Service和@Controller。@Component是任何spring管理组件的通用原型。@Repository、@Service和@Controller分别是针对更具体的用例(例如,在持久性、服务和表示层)的@Component的专门化。因此,您可以使用@Component对组件类进行注释,但是通过使用@Repository、@Service或@Controller对它们进行注释,您的类更适合通过工具进行处理或与方面关联。例如,这些原型注释为切入点提供了理想的目标。在Spring框架的未来版本中,@Repository、@Service和@Controller也可能带有附加的语义。因此,如果您正在为您的服务层选择使用@Component还是使用@Service,那么@Service显然是更好的选择。类似地,如上所述,@Repository已经被支持作为持久性层中自动异常转换的标记。

#15


14  

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

Spring @Component、@Service、@Repository和@Controller注释在Spring框架中使用类路径扫描进行自动bean检测。

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

@Component是一个通用注释。@Service、@Repository、@Controller与@Component的区别在于,它们是@Component的特殊情况,用于特定目的。区别仅仅是分类。

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.

对于所有这些注释(原型),技术上的核心目的是相同的。Spring自动扫描并标识所有这些用“@Component, @Service, @Repository, @Controller”注释的类,并向ApplicationContext注册Bean定义。

#16


14  

We can answer this according to java standard

我们可以根据java标准来回答这个问题

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.

引用现在由spring支持的JSR-330,您只能使用@Named来定义一个bean (@Named=@Component)。因此,根据这个标准,似乎没有用于对类别bean定义原型(如@Repository、@Service、@Controller)的方法。

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

但是spring用户这些不同的注释在特定的用途上是不同的,例如:

  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. 帮助开发人员为有能力的人定义一个更好的类别。这种分类在某些情况下可能会有帮助。(例如,当您使用面向方面的时候,这些是切入点的很好的候选者)
  3. @Repository annotation will add some functionality to your bean (some automatic exception translation to your bean persistence layer).
  4. @Repository注释将向bean添加一些功能(将一些自动异常转换为bean持久性层)。
  5. If you are using spring MVC, the @RequestMapping can only be added to classes which are annotated by @Controller.
  6. 如果您正在使用spring MVC, @RequestMapping只能添加到由@Controller注释的类中。

#17


14  

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.

Spring提供了四种不同类型的自动组件扫描注释,它们是@Component、@Service、@Repository和@Controller。从技术上讲,它们之间没有区别,但是每个自动组件扫描注释都应该用于特殊目的,并在定义的层中使用。

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

@Component:它是一个基本的自动组件扫描注解,它表明带注解的类是自动扫描的。

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

@Controller:带注释的类表示它是一个控制器组件,主要用于表示层。

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

@Service:它表示带注释的类是业务层中的服务组件。

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

@Repository:您需要在持久性层中使用此注释,这类似于数据库存储库。

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

当注释它们的类时,应该选择更专门化的@Component形式,因为这个注释可能包含特定的行为。

#18


13  

In Spring 4, latest version:

在Spring 4中,最新版本:

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

@Repository注释是满足存储库角色或原型的任何类的标记(也称为数据访问对象或DAO)。该标记的用途之一是将异常自动翻译为第20.2.2节“异常翻译”。

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.

Spring提供了进一步的模板注释:@Component, @Service和@Controller。@Component是任何spring管理组件的通用原型。@Repository、@Service和@Controller分别是针对更具体的用例(例如,在持久性、服务和表示层)的@Component的专门化。因此,您可以使用@Component对组件类进行注释,但是通过使用@Repository、@Service或@Controller对它们进行注释,您的类更适合通过工具进行处理或与方面关联。例如,这些原型注释为切入点提供了理想的目标。在Spring框架的未来版本中,@Repository、@Service和@Controller也可能带有附加的语义。因此,如果您正在为您的服务层选择使用@Component还是使用@Service,那么@Service显然是更好的选择。类似地,如上所述,@Repository已经被支持作为持久性层中自动异常转换的标记。

#19


12  

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

即使我们交换@Component或@Repository或@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

它的行为是相同的,但是一个方面是,如果我们使用组件或@服务,它们将无法捕获与DAO相关的特定异常,而不是存储库

#20


9  

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.

@Component、@Service、@Controller、@Repository之间没有区别。@Component是表示MVC组件的通用注释。但是作为MVC应用程序的一部分,会有几个组件,比如服务层组件、持久性层组件和表示层组件。为了区分它们,Spring的人也给出了另外三个注解。

To represent persistence layer components : @Repository

表示持久性层组件:@Repository

To represent service layer components : @Service

表示服务层组件:@Service

To represent presentation layer components : @Controller

表示表示层组件:@Controller

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

或者你也可以使用@Component。

#21


8  

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

技术上讲,@Controller, @Service, @Repository都是一样的。所有这些都扩展了@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.

我们可以直接为每个bean使用@Component,但是为了更好地理解和维护大型应用程序,我们使用@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.

1)@ controller类- >注释,旨在从客户端接收请求。第一个请求Dispatcher Servlet时,从它将请求传递给特定的控制器使用@RequestMapping注释的值。

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.

2) @Service -带有此注释的>类,用于操作我们从客户端接收或从数据库获取的数据。所有使用数据的操作都应该在这个层中完成。

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.

3) @Repository—带有此注释的>类,用于连接数据库。它也可以被看作是DAO(数据访问对象)层。这一层应该仅限于CRUD(创建、检索、更新、删除)操作。如果需要任何操作,应该将数据发送回@Service层。

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

如果我们交换它们的位置(使用@Repository代替@Controller),我们的应用程序就会运行良好。

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

使用三个不同的@annotation的主要目的是为企业应用程序提供更好的模块化。

#22


7  

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

@ component是*通用的注释使得带注释的bean被扫描和DI容器中可用

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

@专业注释和它带来的转换特性的所有未经检查的异常DAO类

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

@ service是专门的注释。到目前为止,它没有带来任何新特性,但是它澄清了bean的意图

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

@ controller是专业注释使得bean MVC意识到并允许使用进一步注释@RequestMapping和所有这些

Here are more details

这里有更多的细节

#23


6  

A @Service to quote spring documentation,

引用spring文档的@Service,

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.

表示一个带注释的类是一个“服务”,最初由域驱动设计(Evans, 2003)定义为“一个单独在模型中提供的接口,没有封装状态。”也可能表明类是“业务服务Facade”(在核心J2EE模式意义上),或者类似的东西。这个注释是一个通用的原型,每个团队可能会缩小他们的语义并适当地使用它们。

If you look at domain driven design by eric evans,

如果你看看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,

根据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.

代表了某种类型的所有对象存储库是一组概念(通常模拟)。它就像一个集合,除了有更详细的查询功能。对象适当类型的添加和删除,和背后的机械存储库从数据库中插入或删除它们。这个定义收集一组内聚的责任提供聚合的根源从早期生命周期结束。

#24


6  

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

@Component:您注释一个类@Component,它告诉hibernate它是一个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.

@:@您标注了一个类,它告诉hibernate DAO类和把它当作DAO类。意味着它使未经检查的异常(从DAO方法)资格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.

@Service:这告诉hibernate这是一个服务类,您将在其中使用@Transactional etc服务层注释,所以hibernate将它作为服务组件。

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是@Component的advance。假设bean类名是CustomerService,因为您没有选择XML bean配置方式,所以您使用@Component对bean进行了注释,以将其表示为bean。因此,在获取bean对象CustomerService cust = (CustomerService)context.getBean(“CustomerService”)时;默认情况下,Spring将把组件的第一个字符——从“CustomerService”降为“CustomerService”。您可以使用名称“customerService”检索此组件。但是,如果您对bean类使用@Service注释,您可以提供一个特定的bean名称by

@Service("AAA")
public class CustomerService{

and you can get the bean object by

你可以通过

CustomerService cust = (CustomerService)context.getBean("AAA");

#25


5  

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

此注释用于类以指示Spring组件。它将Java类标记为bean或组件,以便Spring的组件扫描机制可以将其添加到应用程序上下文中。

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

@该注释用于直接访问数据库的Java类。它是一个标记任何类,实现存储库的角色或数据访问对象。这个注释有自动翻译功能。例如,当一个例外发生在@ repository,有一个异常处理程序,不需要添加一个try - catch块。

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

@Service它标记一个执行某些服务的Java类,例如执行业务逻辑、执行计算和调用外部api。此注释是用于服务层的@Component注释的一种特殊形式。

@Controller This annotation is used to indicate the class is a Spring controller.

这个注释用于指示类是Spring控制器。

#26


2  

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.
  • @Service -用@Service注释所有的服务类。这一层知道功的单位。您的所有业务逻辑都将在服务类中。服务层的方法一般都包含在事务中。您可以从服务方法进行多个DAO调用,如果一个事务失败,那么所有事务都应该回滚。
  • @Repository - Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
  • @Repository—使用@Repository对所有DAO类进行注释。所有数据库访问逻辑都应该在DAO类中。
  • @Component - Annotate your other components (for example REST resource classes) with component stereotype.
  • @Component——用组件模板注释其他组件(例如REST资源类)。
  • @Autowired - Let Spring auto-wire other beans into your classes using @Autowired annotation.
  • @Autowired -让Spring使用@Autowired注释将其他bean自动连接到您的类中。

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

@Component是任何spring管理组件的通用原型。@Repository、@Service和@Controller分别是针对更具体的用例(例如,在持久性、服务和表示层)的@Component的专门化。

Originally answered here.

最初的答案。

#27


2  

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

@Component——通用的,可以跨应用程序使用。@Service -在服务层级别注释类。@Repository—持久层的类注释,它将充当数据库存储库。

#28


0  

@Component, @ Repository, @ Service, @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:

@Component是Spring @Repository、@Service和@Controller管理的组件的通用原型,@Component是用于更具体用途的@Component专门化:

  • @Repository for persistence
  • @的持久性
  • @Service for services and transactions
  • 服务和交易服务。
  • @Controller for MVC controllers
  • @ controller,MVC控制器

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.

为什么在@Component上使用@Repository, @Service, @Controller ?我们可以使用@Component来标记我们的组件类,但是如果我们使用另一种方法来适应预期的功能的话。我们的类更适合每个特定情况下所期望的功能。

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

使用“@Repository”注释的类具有更好的翻译和可读的错误处理能力,可以使用org.springframe . dao.dataaccessexception。理想的实现访问数据的组件(DataAccessObject或DAO)。

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

带有“@Controller”的带注释类在Spring Web MVC应用程序中扮演控制器角色

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

带有“@Service”的带注释的类在业务逻辑服务、DAO Manager (Facade)的示例Facade模式和事务处理中扮演角色