简体   繁体   English

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

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

Can @Component , @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device? @Component@Repository@Service注释可以在 Spring 中互换使用吗?或者它们是否提供除了充当符号设备之外的任何特定功能?

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 类并将注解从@Service更改为@Component ,它的行为方式是否仍然相同?

Or does the annotation also influence the behavior and functionality of the class?或者注释是否也会影响类的行为和功能?

From Spring Documentation :来自Spring 文档

The @Repository annotation is a marker for any class that fulfils the role or stereotype of a repository (also known as Data Access Object or DAO). @Repository注释是任何满足存储库角色或构造型(也称为数据访问对象或 DAO)的类的标记。 Among the uses of this marker is the automatic translation of exceptions, as described in Exception Translation .此标记的用途之一是异常的自动转换,如异常转换中所述

Spring provides further stereotype annotations: @Component , @Service , and @Controller . Spring 提供了更多的@Component型注解: @Component@Service @Controller@Controller @Component is a generic stereotype for any Spring-managed component. @Component是任何 Spring 管理的组件的通用@Component型。 @Repository , @Service , and @Controller are specializations of @Component for more specific use cases (in the persistence, service, and presentation layers, respectively). @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.因此,您可以使用@Component注释您的组件类,但是,通过使用@Repository@Service@Controller注释它们,您的类更适合由工具处理或与方面相关联。

For example, these stereotype annotations make ideal targets for pointcuts.例如,这些构造型注释是切入点的理想目标。 @Repository , @Service , and @Controller can also carry additional semantics in future releases of the Spring Framework. @Repository@Service@Controller还可以在 Spring Framework 的未来版本中携带额外的语义。 Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice.因此,如果您在服务层使用@Component@Service之间做出选择, @Service Service 显然是更好的选择。 Similarly, as stated earlier, @Repository is already supported as a marker for automatic exception translation in your persistence layer.同样,如前所述, @Repository已经被支持作为持久层中自动异常转换的标记。

Annotation注解 Meaning意义
@Component generic stereotype for any Spring-managed component任何 Spring 管理的组件的通用构造型
@Repository stereotype for persistence layer持久层的构造型
@Service stereotype for service layer服务层的构造型
@Controller stereotype for presentation layer (spring-mvc)表示层的构造型(spring-mvc)

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.值得再次强调的第一点是,关于 BeanDefinition 的扫描自动检测和依赖注入,所有这些注释(即@Component、@Service、@Repository、@Controller)都是相同的。 We can use one in place of another and can still get our way around.我们可以用一个代替另一个,并且仍然可以解决问题。


Differences between @Component, @Repository, @Controller and @Service @Component、@Repository、@Controller 和@Service 之间的区别

@Component @成分

This is a general-purpose stereotype annotation indicating that the class is a spring component.这是一个通用构造型注释,表明该类是一个弹簧组件。

What's special about @Component @Component 有什么特别之处
<context:component-scan> only scans @Component and does not look for @Controller , @Service and @Repository in general. <context:component-scan>只扫描@Component ,一般不查找@Controller@Service@Repository They are scanned because they themselves are annotated with @Component .它们被扫描是因为它们本身是用@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.因此,说@Controller@Service @Controller@Repository@Component注解的特殊类型并没有错。 <context:component-scan> picks them up and registers their following classes as beans, just as if they were annotated with @Component . <context:component-scan>拾取它们并将它们的后续类注册为 bean,就好像它们用@Component注释一样。

Special type annotations are also scanned, because they themselves are annotated with @Component annotation, which means they are also @Component s.特殊类型的注解也会被扫描,因为它们本身是用@Component注解进行注解的,这意味着它们也是@Component If we define our own custom annotation and annotate it with @Component , it will also get scanned with <context:component-scan>如果我们定义我们自己的自定义注解并使用@Component注解,它也会使用<context:component-scan>


@Repository @Repository

This is to indicate that the class defines a data repository.这是为了表明该类定义了一个数据存储库。

What's special about @Repository? @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.除了指出,这是一个基于注解的配置@Repository的工作是捕捉平台特定的异常并将它们作为 Spring 的统一未检查异常之一重新抛出。 For this, we're provided with PersistenceExceptionTranslationPostProcessor , that we are required to add in our Spring's application context like this:为此,我们提供了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 re-thrown as one of Spring's unchecked data access exceptions.这个 bean 后处理器向任何用@Repository注释的 bean 添加一个顾问,以便捕获任何特定于平台的异常,然后作为 Spring 的未经检查的数据访问异常之一重新抛出。


@Controller @控制器

The @Controller annotation indicates that a particular class serves the role of a controller. @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.我们不能将此注释与任何其他注释(如@Service@Repository切换,即使它们看起来相同。 The dispatcher scans the classes annotated with @Controller and detects methods annotated with @RequestMapping annotations within them.调度程序扫描用@Controller注释的类并检测其中用@RequestMapping注释注释的方法。 We can use @RequestMapping on/in only those methods whose classes are annotated with @Controller and it will NOT work with @Component , @Service , @Repository etc...我们可以使用@RequestMapping上/只,其类注释与方法@Controller ,它不会与工作@Component@Service@Repository等..

Note: If a class is already registered as a bean through any alternate method, like through @Bean or through @Component , @Service etc... annotations, then @RequestMapping can be picked if the class is also annotated with @RequestMapping annotation.注:如果一个类是通过任何替代方法通过已注册为一个bean,像@Bean或通过@Component@Service等...注释,然后@RequestMapping如果类也与注释可挑@RequestMapping注解。 But that's a different scenario.但这是一个不同的场景。


@Service @服务

@Service beans hold the business logic and call methods in the repository layer. @Service bean 在存储库层中保存业务逻辑和调用方法。

What's special about @Service? @Service 有什么特别之处?

Apart from the fact that it's used to indicate, that it's holding the business logic, there's nothing else noticeable in this annotation;除了用于表明它持有业务逻辑这一事实之外,此注释中没有其他值得注意的地方; but who knows, Spring may add some additional exceptional in future.但谁知道呢,Spring 可能会在未来增加一些额外的例外。


What else?还有什么?

Similar to above, in the future Spring may add special functionalities for @Service , @Controller and @Repository based on their layering conventions.与上面类似,未来 Spring 可能会根据它们的分层约定为@Service@Controller@Repository添加特殊功能。 Hence, it's always a good idea to respect the convention and use it in line with layers.因此,尊重约定并将其与层一起使用总是一个好主意。

They are almost the same - all of them mean that the class is a Spring bean.它们几乎相同——所有这些都意味着该类是一个 Spring bean。 @Service , @Repository and @Controller are specialized @Component s. @Service@Repository@Controller是专门的@Component You can choose to perform specific actions with them.您可以选择对它们执行特定操作。 For example:例如:

  • @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.所以所有用@ScheduledJob注释的类都是 spring bean,除此之外,还注册为石英作业。 You just have to provide code that handles the specific annotation.您只需要提供处理特定注释的代码。

@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.存储库是 DAO(数据访问对象),它们直接访问数据库。

Now you may ask why separate them: (I assume you know AOP-Aspect Oriented Programming)现在你可能会问为什么要把它们分开:(我假设你知道 AOP-Aspect Oriented Programming)

Let's say you want to Monitors the Activity of the DAO Layer only.假设您只想监控 DAO 层的活动。 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.您将编写一个 Aspect(一个类)类,该类在调用 DAO 的每个方法之前和之后执行一些日志记录,您可以使用 AOP 来执行此操作,因为您具有三个不同的层并且没有混合。

So you can do logging of DAO "around", "before" or "after" the DAO methods.因此,您可以在 DAO 方法的“周围”、“之前”或“之后”记录 DAO。 You could do that because you had a DAO in the first place.你可以这样做,因为你首先有一个 DAO。 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!试想如果只有一个注解@Controller,那么这个组件的调度、业务逻辑和访问数据库都是混杂的,好脏的代码!

Above mentioned is one very common scenario, there are many more use cases of why to use three annotations.上面提到的是一种很常见的场景,关于为什么要使用三个注解的用例还有很多。

In Spring @Component , @Service , @Controller , and @Repository are Stereotype annotations which are used for:在 Spring 中@Component@Service@Controller@Repository是 Stereotype 注释,用于:

@Controller: where your request mapping from presentation page done ie 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 ie 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. @Service :所有的业务逻辑都在这里,即数据相关的计算和所有。业务层的这个注解,我们的用户不直接调用持久化方法,所以它会使用这个注解调用这个方法。 It will request @Repository as per user request它将根据用户请求请求@Repository

@Repository : This is Persistence layer(Data Access Layer) of application which used to get data from the database. @Repository :这是应用程序的持久层(数据访问层),用于从数据库中获取数据。 ie all the Database related operations are done by the repository.所有与数据库相关的操作都由存储库完成。

@Component - Annotate your other components (for example REST resource classes) with a component stereotype. @Component - 使用组件@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: eg the @Repository annotation or AspectJ's @Aspect annotation.其他类级别的注释也可以被视为标识组件,通常是一种特殊类型的组件:例如@Repository 注释或AspectJ 的@Aspect 注释。

在此处输入图片说明

Spring 2.5 introduces further stereotype annotations: @Component, @Service and @Controller. Spring 2.5 引入了更多的构造型注解:@Component、@Service 和 @Controller。 @Component serves as a generic stereotype for any Spring-managed component; @Component 作为任何 Spring 管理的组件的通用构造型; whereas, @Repository, @Service, and @Controller serve as specializations of @Component for more specific use cases (eg, in the persistence, service, and presentation layers, respectively).而@Repository、@Service 和@Controller 作为@Component 的特化用于更具体的用例(例如,分别在持久层、服务层和表示层中)。 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.这意味着您可以使用@Component 注释您的组件类,但是通过使用@Repository、@Service 或@Controller 来注释它们,您的类更适合由工具处理或与方面相关联。 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.当然,@Repository、@Service 和@Controller 也有可能在 Spring Framework 的未来版本中携带额外的语义。 Thus, if you are making a decision between using @Component or @Service for your service layer, @Service is clearly the better choice.因此,如果您在为服务层使用 @Component 或 @Service 之间做出决定,@Service 显然是更好的选择。 Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.同样,如上所述,@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 进行类路径扫描、托管组件和编写配置

Technically @Controller , @Service , @Repository are all same.从技术上讲@Controller@Service@Repository都是一样的。 All of them extends @Component .所有这些都扩展了@Component

From the Spring source code:从 Spring 源代码:

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. @Controller -> 用此注释的类,旨在接收来自客户端的请求。 The first request comes to the Dispatcher Servlet, from where it passes the request to the particular controller using the value of @RequestMapping annotation.第一个请求到达 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. @Service -> 用此注释的类,旨在操作我们从客户端接收或从数据库获取的数据。 All the manipulation with data should be done in this layer.所有对数据的操作都应该在这一层完成。
  3. @Repository -> Classes annotated with this, are intended to connect with database. @Repository -> 用此注释的类,旨在与数据库连接。 It can also be considered as DAO(Data Access Object) layer.它也可以被认为是 DAO(数据访问对象)层。 This layer should be restricted to CRUD (create, retrieve, update, delete) operations only.该层应仅限于 CRUD(创建、检索、更新、删除)操作。 If any manipulation is required, data should be sent be send back to @Service layer.如果需要任何操作,应将数据发送回@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.使用三种不同的@annotations的主要目的是为企业应用程序提供更好的模块化。

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@Service用于所有 Web 服务类型的数据库连接
  2. Use @Repository for all your stored proc DB connections对所有存储的 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 事务相关的异常。

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

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注释就会存在于类之上

Spring provides four different types of auto component scan annotations, they are @Component , @Service , @Repository and @Controller . Spring 提供了四种不同类型的自动组件扫描注解,它们是@Component@Service@Repository@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. @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 :表示注解类是业务层的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形式,因为此注释可能包含未来的特定行为。

There is no difference between @Component , @Service , @Controller , @Repository . @Component@Service@Controller@Repository之间没有区别。 @Component is the Generic annotation to represent the component of our MVC. @Component是表示我们 MVC 组件的通用注解。 But there will be several components as part of our MVC application like service layer components, persistence layer components and presentation layer components.但是将有几个组件作为我们 MVC 应用程序的一部分,如服务层组件、持久层组件和表示层组件。 So to differentiate them Spring people have given the other three annotations also.所以为了区分它们,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

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 ).参考 Spring 现在支持的JSR-330 ,您只能使用@Named来定义一个 bean(不知何故@Named=@Component )。 So according to this standard, there seems that there is no use to define stereotypes (like @Repository , @Service , @Controller ) to categories beans.所以根据这个标准,似乎没有用定义@Repository型(如@Repository@Service@Controller )来分类 bean。

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 ) (例如,当您使用aspect-oriented ,这些可能是pointcuts的良好候选者)
  2. @Repository annotation will add some functionality to your bean (some automatic exception translation to your bean persistence layer). @Repository注释将为您的 bean 添加一些功能(一些自动异常转换到您的 bean 持久层)。
  3. If you are using spring MVC, the @RequestMapping can only be added to classes which are annotated by @Controller .如果您使用的是 spring MVC,则只能将@RequestMapping添加到由@Controller注释的类中。

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春天的@Component

“组件专业化”

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它的行为是相同的,但一方面是如果我们使用组件或@service,它们将无法捕获与 DAO 而不是 Repository 相关的某些特定异常。

@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. @Repository :您注释一个类@Repository ,它告诉 hibernate 它是一个 DAO 类并将其视为 DAO 类。 Means it makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException .意味着它使未经检查的异常(从 DAO 方法抛出)有资格转换为 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. @Service :这告诉 hibernate 它是一个 Service 类,您将在其中拥有@Transactional等服务层注释,因此 hibernate 将其视为服务组件。

Plus @Service is advance of @Component .加上@Service@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.假设 bean 类名为CustomerService ,因为您没有选择 XML bean 配置方式,所以您使用@Component对 bean 进行注释以指示它是一个 Bean。 So while getting the bean object CustomerService cust = (CustomerService)context.getBean("customerService");所以在获取 bean 对象CustomerService cust = (CustomerService)context.getBean("customerService"); By default, Spring will lower case the first character of the component – from 'CustomerService' to 'customerService'.默认情况下,Spring 将小写组件的第一个字符——从“CustomerService”到“customerService”。 And you can retrieve this component with name 'customerService'.您可以检索名称为“customerService”的组件。 But if you use @Service annotation for the bean class you can provide a specific bean name by但是,如果您对 bean 类使用@Service批注,则可以通过以下方式提供特定的 bean 名称

@Service("AAA")
public class CustomerService{

and you can get the bean object by你可以通过

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

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). @Repository 注释是任何满足存储库角色或构造型(也称为数据访问对象或 DAO)的类的标记。 Among the uses of this marker is the automatic translation of exceptions as described in Section 20.2.2, “Exception translation”.此标记的用途之一是自动转换异常,如第 20.2.2 节“异常转换”中所述。

Spring provides further stereotype annotations: @Component, @Service, and @Controller. Spring 提供了更多的构造型注解:@Component、@Service 和 @Controller。 @Component is a generic stereotype for any Spring-managed component. @Component 是任何 Spring 管理的组件的通用构造型。 @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively. @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.因此,您可以使用@Component 注释您的组件类,但是通过使用@Repository、@Service 或@Controller 来注释它们,您的类更适合由工具处理或与方面相关联。 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.在 Spring Framework 的未来版本中,@Repository、@Service 和 @Controller 也可能带有额外的语义。 Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice.因此,如果您在服务层使用 @Component 或 @Service 之间做出选择,@Service 显然是更好的选择。 Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.同样,如上所述,@Repository 已经被支持作为持久层中自动异常转换的标记。

@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 @Repository是专门的注解,它带来了转换来自 DAO 类的所有未检查异常的功能

@Service is specialized annotation. @Service是专门的注解。 it do not bring any new feature as of now but it clarifies the intent of the bean它目前没有带来任何新功能,但它阐明了 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这里有更多细节

Good enough answers are here to explain the whats-the-difference-between-component-repository-service-annotations.这里有足够好的答案来解释组件存储库服务注释之间的差异。 I would like to share the difference between @Controller & @RestController我想分享@Controller & @RestController之间的区别

@Controller vs RestController @ControllerRestController

@RestController : @RestController

在此处输入图片说明

  • This annotation is a specialized version of @Controller which adds @Controller and @ResponseBody annotation automatically.这个注解是@Controller一个特殊版本,它自动添加了@Controller@ResponseBody注解。 so we do not have to add @ResponseBody to our mapping methods.所以我们不必将@ResponseBody添加到我们的映射方法中。 That means @ResponseBody is default active.这意味着@ResponseBody默认处于活动状态。
  • If you use @RestController you cannot return a view (By using Viewresolver in Spring/Spring-Boot)如果使用@RestController ,则无法返回视图(通过在 Spring/Spring-Boot 中使用Viewresolver
  • @RestController also converts the response to JSON/XML automatically as @ResponseBody makes the returned objects to something that could be in the body, eg JSON or XML @RestController还自动将响应转换为JSON/XML automatically因为@ResponseBody使返回的对象成为可能在正文中的对象, eg JSON or XML

@Controller

在此处输入图片说明

  • @Controller is used to mark classes as Spring MVC Controller. @Controller用于将类标记为 Spring MVC 控制器。 This annotation is just a specialized version of @Component and it allows the controller classes to be auto-detected based on classpath scanning.这个注解只是@Component一个特殊版本,它允许基于类路径扫描自动检测控制器类。
  • @Controller you can return a view in Spring web MVC. @Controller您可以在 Spring Web MVC 中返回一个视图。

More Detailed View 更详细的视图

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."表示带注释的类是“服务”,最初由领域驱动设计(Evans,2003)定义为“作为独立于模型中的接口提供的操作,没有封装状态”。 May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar.也可能表示一个类是“业务服务外观”(在核心 J2EE 模式意义上)或类似的东西。 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,如果你看看 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. SERVICE 是作为独立于模型中的接口提供的操作,没有像 ENTITIES 和 VALUE OBJECTS 那样封装状态。 SERVICES are a common pattern in technical frameworks, but they can also apply in the domain layer. SERVICES 是技术框架中的常见模式,但它们也可以应用于领域层。 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.与 ENTITIES 和 VALUE OBJECTS 不同,它纯粹是根据它可以为客户端做什么来定义的。 A SERVICE tends to be named for an activity, rather than an entity—a verb rather than a noun. SERVICE 往往以活动命名,而不是实体——动词而不是名词。 A SERVICE can still have an abstract, intentional definition; SERVICE 仍然可以有一个抽象的、有意的定义; 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.一个 SERVICE 仍然应该有一个已定义的职责,并且这个职责和实现它的接口应该被定义为域模型的一部分。 Operation names should come from the UBIQUITOUS LANGUAGE or be introduced into it.操作名称应来自 UBIQUITOUS LANGUAGE 或引入其中。 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.应该明智地使用 SERVICES,不允许剥夺其所有行为的实体和价值对象。 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.在模型中声明为 SERVICE,而不是作为实际不代表任何内容的虚假对象,独立操作不会误导任何人。

and a Repository as per Eric Evans,和 Eric Evans 的Repository

A REPOSITORY represents all objects of a certain type as a conceptual set (usually emulated).一个 REPOSITORY 将某种类型的所有对象表示为一个概念集(通常是模拟的)。 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.添加和删​​除适当类型的对象,并且 REPOSITORY 背后的机制将它们插入或从数据库中删除。 This definition gathers a cohesive set of responsibilities for providing access to the roots of AGGREGATES from early life cycle through the end.这个定义收集了一组有凝聚力的责任,用于提供从早期生命周期到结束的对 AGGREGATES 根的访问。

The answers presented here are partially technically correct, but even though the response list is long and this will be at the bottom I thought it was worth putting an actually correct response in here too, just in case somebody stumbles upon it and learns something valuable from it.这里提供的答案在技术上是部分正确的,但即使回复列表很长而且这将在底部,我认为也值得在此处放置一个实际正确的回复,以防万一有人偶然发现并从中学到一些有价值的东西它。 It's not that the rest of the answers are completely wrong, it's just that they aren't right.并不是其余的答案完全错误,只是它们不正确。 And, to stop the hordes of trolls, yes, I know that technically these annotations are effectively the same thing right now and mostly interchangeable even unto spring 5. Now, for the right answer:而且,为了阻止成群结队的巨魔,是的,我知道从技术上讲,这些注释现在实际上是同一件事,并且即使到 spring 5 也几乎可以互换。现在,对于正确的答案:

These three annotations are completely different things and are not interchangeable.这三个注解是完全不同的东西,不可互换。 You can tell that because there are three of them rather than just one.你可以这么说,因为它们是三个而不是一个。 They are not intended to be interchangeable, they're just implemented that way out of elegance and convenience.它们不打算互换,它们只是为了优雅和方便而实现的。

Modern programming is invention, art, technique, and communication, in varying proportions.现代编程是不同比例的发明、艺术、技术和交流。 The communication bit is usually very important because code is usually read much more often than its written.通信位通常非常重要,因为代码的读取次数通常比编写的次数要多得多。 As a programmer you're not only trying to solve the technical problem, you're also trying to communicate your intent to future programmers who read your code.作为程序员,您不仅要尝试解决技术问题,还要尝试将您的意图传达给阅读您代码的未来程序员。 These programmers may not share your native language, nor your social environment, and it is possible that they may be reading your code 50-years in the future (it's not as unlikely as you may think).这些程序员可能不会分享你的母语,也不会分享你的社交环境,他们有可能在未来 50 年阅读你的代码(这并不像你想象的那么不可能)。 It's difficult to communicate effectively that far into the future.很难在那么远的将来进行有效的沟通。 Therefore, it is vital that we use the clearest, most efficient, correct, and communicative language available to us.因此,使用我们可用的最清晰、最有效、最正确和可交流的语言至关重要。 That we chose our words carefully to have maximum impact and to be as clear as possible as to our intent.我们仔细选择我们的话,以产生最大的影响,并尽可能清楚地表达我们的意图。

For example, it is vital that @Repository is used when we're writing a repository, rather than @Component .例如,在我们编写存储库时使用@Repository而不是@Component是至关重要的。 The latter is a very poor choice of annotation for a repository because it does not indicate that we're looking at a repository.后者对于存储库来说是一个非常糟糕的注释选择,因为它并不表明我们正在查看存储库。 We can assume that a repository is also a spring-bean, but not that a component is a repository.我们可以假设存储库也是 spring-bean,但不能假设组件是存储库。 With @Repository we are being clear and specific in our language.使用@Repository ,我们的语言变得清晰而具体。 We are stating clearly that this is a repository.我们清楚地说明这是一个存储库。 With @Component we are leaving it to the reader to decide what type of component they are reading, and they will have to read the whole class (and possibly a tree of subclasses and interfaces) to infer meaning.使用@Component我们让读者决定他们正在阅读什么类型的组件,他们将不得不阅读整个类(可能还有子类和接口的树)来推断含义。 The class could then possibly be misinterpreted by a reader in the distant future as not being a repository, and we would have been partially responsible for this mistake because we, who knew full well that this is a repository, failed to be specific in our language and communicate effectively our intent.在遥远的未来,这个类可能会被读者误解为不是一个存储库,我们应该对这个错误负部分责任,因为我们完全知道这是一个存储库,但未能在我们的语言中具体化并有效地传达我们的意图。

I won't go into the other examples, but will state as clearly as I can: these annotations are completely different things and should be used appropriately, as per their intent.我不会进入其他示例,但会尽可能清楚地说明:这些注释是完全不同的东西,应该根据它们的意图适当地使用。 @Repository is for storage repositories and no other annotation is correct. @Repository用于存储库,没有其他注释是正确的。 @Service is for services and no other annotation is correct. @Service用于服务,没有其他注释是正确的。 @Component is for components that are neither repositories nor services, and to use either of these in its place would also be incorrect. @Component用于既不是存储库也不是服务的组件,在它的位置使用它们中的任何一个也是不正确的。 It might compile, it might even run and pass your tests, but it would be wrong and I would think less of you (professionally) if you were to do this.它可能会编译,它甚至可能运行并通过您的测试,但这是错误的,如果您这样做,我会(专业地)认为您较少。

There are examples of this throughout spring (and programming in general).整个春天都有这样的例子(以及一般的编程)。 You must not use @Controller when writing a REST API, because @RestController is available.编写 REST API 时不得使用@Controller ,因为@RestController可用。 You must not use @RequestMapping when @GetMapping is a valid alternative.@GetMapping是有效的替代方案时,您不得使用@RequestMapping Etc. Etc. Etc. You must chose the most specific exact and correct language you can to communicate your intent to your readers, otherwise, you are introducing risks into your system, and risk has a cost.等等等等 你必须选择最具体、准确和正确的语言来向你的读者传达你的意图,否则,你将风险引入你的系统,风险是有代价的。

Finally, I'd like to bring up a point of order concerning Object-Oriented systems.最后,我想提出一个关于面向对象系统的程序问题。 One of the fundamental rules is that implementations can vary but interfaces shouldn't.基本规则之一是实现可以变化,但接口不应该。 Assuming that these annotations are the same thing is a very slippery slope and completely against OO.假设这些注释是同一个东西是一个非常滑坡并且完全反对 OO。 Although they may be implemented in an interchangeable way now, there is no guarantee that they will be in the future.尽管它们现在可能以可互换的方式实施,但不能保证它们将来会如此。 Further, even within the same team, an engineer may decide to hang some behaviour off one or more of these annotations using aspects, or a platform engineer may choose to replace the implementation of one of these for operational reasons.此外,即使在同一个团队中,工程师也可能决定使用方面将一些行为挂在这些注释中的一个或多个上,或者平台工程师可能出于操作原因选择替换其中一个的实现。 You just don't know, nor should you -- in OO you rely on the interface, not the implementation.你只是不知道,也不应该——在面向对象中,你依赖于接口,而不是实现。

Repository and Service are children of Component annotation. RepositoryServiceComponent annotation 的子代。 So, all of them are Component .所以,它们都是Component Repository and Service just expand it.存储库服务只是扩展它。 How exactly?具体如何? Service has only ideological difference: we use it for services.服务只有意识形态上的差异:我们将其用于服务。 Repository has particular exception handler.存储库具有特定的异常处理程序。

Explanation of stereotypes :刻板印象的解释:

  • @Service - Annotate all your service classes with @Service. @Service - 使用 @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.您可以从服务方法进行多次 DAO 调用,如果一个事务失败,则所有事务都应回滚。
  • @Repository - Annotate all your DAO classes with @Repository. @Repository - 使用 @Repository 注释所有 DAO 类。 All your database access logic should be in DAO classes.您所有的数据库访问逻辑都应该在 DAO 类中。
  • @Component - Annotate your other components (for example REST resource classes) with component stereotype. @Component - 使用组件@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. @Component是任何 Spring 管理的组件的通用@Component型。 @Repository , @Service , and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively. @Repository@Service@Controller@Component用于更具体的用例,例如,分别在持久层、服务层和表示层中。

Originally answered here .原来在这里回答。

Difference between @Component, @Repository, @Controller & @Service annotations @Component, @Repository, @Controller & @Service 注解的区别

@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 – 在持久层注释类,它将充当数据库存储库。

@Controller = @Component ( Internal Annotation ) + Presentation layer Features @Controller = @Component(内部注解)+ 表现层功能
@Service = @Component ( Internal Annotation ) + Service layer Features @Service = @Component(内部注解)+ 服务层功能
@Component = Actual Components ( Beans ) @Component = 实际组件(Beans)
@Repository = @Component ( Internal Annotation ) + Data Layer Features ( use for handling the Domain Beans ) @Repository = @Component(内部注释)+ 数据层功能(用于处理域 Bean)

In spring framework provides some special type of annotations,called stereotype annotations.在 spring 框架中提供了一些特殊类型的注解,称为构造型注解。 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.上面声明的注解是特殊的,因为当我们将<context:component-scan>到 xxx-servlet.xml 文件中时,spring 会在上下文创建/加载阶段自动创建那些用上面注解注解的类的对象。

@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管理的组件的通用@Repository@Service @Controller@Controller是用于更具体用途的@Component特化:

  • @Repository for persistence @Repository持久化
  • @Service for services and transactions @Service用于服务和交易
  • @Controller for MVC controllers @Controller用于 MVC 控制器

Why use @Repository , @Service , @Controller over @Component ?为什么在@Component使用@Repository@Service@Controller We can mark our component classes with @Component, but if instead we use the alternative that adapts to the expected functionality.我们可以用@Component 标记我们的组件类,但如果我们使用适应预期功能的替代方案。 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.使用@Repository注释的类具有更好的翻译和可读性错误处理与 org.springframework.dao.DataAccessException。 Ideal for implementing components that access data (DataAccessObject or DAO).非常适合实现访问数据的组件(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 管理器(门面)和事务处理的示例门面模式中发挥作用

In order to simplify this illustration, let us consider technicality by use case, These annotations are used to be injected and as I said literally " Used to be injected " , that mean, if you know how to use Dependency Injection "DI" and you should, then you will always look for these annotations, and by annotating the classes with these Stereo Types , you are informing the DI container to scan them to be ready for Injection on other places, this is the practical target.为了简化这个说明,让我们通过用例来考虑技术性,这些注解是用来注入的,正如我字面上所说的“用来注入”,这意味着,如果你知道如何使用依赖注入“DI”并且你应该,那么你会一直寻找这些注解,通过用这些Stereo Types来注解类,你是在通知DI容器扫描它们以准备在其他地方注入,这是实际的目标。

Now lets move to each one;现在让我们移到每一个; first @Service , If you are building some logic for specific business case you need to separate that in a place which will contain your business logic, this service is normal Class or you can use it as interface if you want , and it is written like this首先@Service ,如果您正在为特定业务案例构建一些逻辑,则需要将其分离在包含您的业务逻辑的地方,该服务是普通类,或者您可以根据需要将其用作接口,它的写法如下这

@Service
public class Doer {
   // Your logic 
}

// To use it in another class, suppose in Controller 
@Controller
public class XController {
 // You have to inject it like this 
 @Autowired 
 private Doer doer;
}

All are the same way when you inject them, @Repository it's an interface which apply the implementation for the Repository Pattern Repository design pattern , generally it's used when you are dealing with some data store or database, and you will find that, it contains multiple ready implementation for you to handle database operations;注入的时候都是一样的, @Repository是一个接口,应用了Repository Pattern Repository设计模式的实现,一般在你处理一些数据存储或数据库时使用,你会发现,它包含多个为您准备好处理数据库操作的实现; it can be CrudRepository , JpaRepository etc.它可以是CrudRepositoryJpaRepository等。

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

Finally the @Component , this is the generic form for registered beans in Spring, that's spring is always looking for bean marked with @Component to be registered, then both @Service and @Repository are special cases of @Component, however the common use case for component is when you're making something purely technical not for covering direct business case!最后是@Component ,这是 Spring 中注册 bean 的通用形式,即 spring 一直在寻找标有 @Component 的 bean 进行注册,那么 @Service 和 @Repository 都是 @Component 的特例,但是常见的用例组件是指您制作的东西纯粹是技术性的,而不是为了涵盖直接的业务案例! like formatting dates or handing special request serialization mechanism and so on.如格式化日期或处理特殊请求序列化机制等。

@Component acts as @Bean annotation in configuration class , register bean in spring context. @Component在配置类中充当@Bean 注解,在 spring 上下文中注册 bean。 Also it is parent for @Service, @Repository and @Controller annotation.它也是@Service、@Repository 和@Controller 注释的父级。

@Service , extends @Component annotation and has only naming difference. @Service ,扩展 @Component 注释并且只有命名差异。

@Repository - extends @Component annotation and translate all database exceptions into DataAccessException . @Repository - 扩展 @Component 注释并将所有数据库异常转换为DataAccessException

@Controller - acts as controller in MVC pattern. @Controller - 在 MVC 模式中充当控制器。 The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping annotations.调度程序将扫描这些带注释的类以查找映射方法,检测 @RequestMapping 注释。

Spring supports multiple types annotations such as @Component, @service, @Repository. Spring 支持@Component、@service、@Repository 等多种类型的注解。 All theses can be found under the org.springframework.stereotype package.所有论文都可以在 org.springframework.stereotype 包下找到。

When classes in our application are annotated with any of the above mentioned annotation then during project startup spring scan(using @ComponentScan) each class and inject the instance of the classes to the IOC container.当我们的应用程序中的类使用上述任何注释进行注释时,在项目启动期间 spring 扫描(使用 @ComponentScan)每个类并将类的实例注入 IOC 容器。 Another thing the @ComponentScan would do is running the methods with @Bean on it and restore the return object to the Ioc Container as a bean. @ComponentScan 要做的另一件事是运行带有 @Bean 的方法,并将返回对象作为 bean 恢复到 Ioc 容器。

Before we deep dive into ( @Component vs @service vs @Repository ) first we have to understand the differences between @Bean and @Component在我们深入研究(@Component vs @service vs @Repository)之前,首先我们必须了解@Bean 和@Component 之间的区别

在此处输入图片说明


@Component vs @Repository vs @Service @Component vs @Repository vs @Service


In most typical applications, we have distinct layers like data access, presentation, service, business, etc. Additionally, in each layer we have various beans.在大多数典型的应用程序中,我们有不同的层,如数据访问、表示、服务、业务等。此外,在每一层中,我们都有不同的 bean。 To detect these beans automatically, Spring uses classpath scanning annotations.Then it registers each bean in the ApplicationContext.为了自动检测这些 bean,Spring 使用类路径扫描注解。然后它在 ApplicationContext 中注册每个 bean。

Here's a short overview of a few of these annotations:以下是其中一些注释的简短概述:

  • @Component is a generic stereotype for any Spring-managed component. @Component 是任何 Spring 管理的组件的通用构造型。
  • @Service annotates classes at the service layer. @Service 在服务层注释类。
  • @Repository annotates classes at the persistence layer, which will act as a database repository. @Repository 在持久层注释类,它将充当数据库存储库。

@Component Annotation @Component 注解

@Component is a class level annotation.We can use @Component across the application to mark the beans as Spring's managed components. @Component 是一个类级别的注解。我们可以在整个应用程序中使用@Component 将bean 标记为Spring 的托管组件。 Spring will only pick up and register beans with @Component, and doesn't look for @Service and @Repository in general. Spring 只会使用@Component 获取和注册 bean,一般不会查找 @Service 和 @Repository。

They are registered in ApplicationContext because they are annotated with @Component它们是在 ApplicationContext 中注册的,因为它们是用 @Component 注释的

As stated, @Component is the parent of all stereotype annotations.如前所述,@Component 是所有构造型注释的父级。 When Spring performs a component scan, it only looks for classes marked with @Component annotations.当 Spring 执行组件扫描时,它只查找标有 @Component 注解的类。

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

We can use this annotation on all the classes and it won't cause any difference.我们可以在所有类上使用这个注解,它不会造成任何差异。

@Service Annotation @服务注解

We mark beans with @Service to indicate that they're holding the business logic.我们用@Service 标记bean 以表明它们持有业务逻辑。 Besides being used in the service layer, there isn't any other special use for this annotation.除了在服务层使用之外,这个注解没有任何其他特殊用途。

The @Service is child of component and used to denote classes from the service layer of the application. @Service 是组件的子级,用于表示来自应用程序服务层的类。

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

@Repository Annotation @Repository 注解

@Repository's job is to catch persistence-specific exceptions and re-throw them as one of Spring's unified unchecked exceptions. @Repository 的工作是捕获特定于持久性的异常并将它们作为 Spring 的统一未检查异常之一重新抛出。

For this, Spring provides PersistenceExceptionTranslationPostProcessor, which we are required to add in our application context (already included if we're using Spring Boot):为此,Spring 提供了 PersistenceExceptionTranslationPostProcessor,我们需要将其添加到我们的应用程序上下文中(如果我们使用 Spring Boot,则已包含):

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

This bean post processor adds an advisor to any bean that's annotated with @Repository.这个 bean 后处理器向任何用 @Repository 注释的 bean 添加了一个顾问。

Similarly, @Repository is also a child of component annotation and used on the classes that belong to persistence data access layer and serves as a data repository.同样,@Repository 也是组件注解的子类,用于属于持久化数据访问层的类,作为数据存储库。

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

Summary概括

@Service and @Repository are special cases of @Component. @Service 和@Repository 是@Component 的特例。 They are technically the same, but we use them for the different purposes.It's always a good idea to choose the annotation based on their layer conventions.它们在技术上是相同的,但我们将它们用于不同的目的。根据它们的图层约定选择注释总是一个好主意。

Even if it behaves same but this leverage the application many of software development principals, few examples are:即使它的行为相同,但它利用了许多软件开发原则的应用程序,几个例子是:

- Single Responsibility
- Open Closed Principal 
@Component
@Controller
@Repository
@Service
@RestController

These are all StereoType annotations.this are usefull for the making our classes as spring beans in ioc container,这些都是 StereoType 注释。这对于将我们的类作为 ioc 容器中的 spring bean 很有用,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何处理@Component和@Repository / @Service注释之间的区别是什么? - What's the difference between how @Component and @Repository / @Service annotations are processed? "Spring 中的@Repository 和@RepositoryDe​​finition 有什么区别?" - What's the difference between @Repository and @RepositoryDefinition in Spring? @Entity 和 @Repository 注释有什么区别? - What is the difference between @Entity and @Repository annotations? @RepositoryRestController和@Repository注释之间有什么区别? - What is the difference between @RepositoryRestController and the @Repository annotations? 与使用存储库相比,使用服务有什么区别? Spring 开机 - What's the difference between using a Service compared to using a repository? Spring Boot Spring注释之间的区别 - Difference between Spring annotations Seedstack 中的 Repository 和 Finder 有什么区别? - What's the difference between a Repository and a Finder in Seedstack? 在Spring框架中使用@Import和@ImportResource注释有什么区别? - What is the difference between the use of @Import and @ImportResource annotations in Spring framework? @CascadeOnDelete和CascadeType.REMOVE批注有什么区别? - What's the difference between @CascadeOnDelete and CascadeType.REMOVE annotations? Play控制器的@After和@Finally注释之间有什么区别? - What's the difference between @After and @Finally annotations for Play controllers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM