Spring 注解@Controller 和@Service 一样吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15922991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:51:32  来源:igfitidea点击:

Is Spring annotation @Controller same as @Service?

springservicecontroller

提问by Ketan

Is Spring annotation @Controllersame as @Service?

Spring 注释@Controller@Service?

I have idea about @Controllerwhich can be used for URLmapping and invoking business logic.

我知道@Controller哪些可用于URL映射和调用业务逻辑。

while @Serviceused to annotate service class which contains business logic.

while@Service用于注释包含业务逻辑的服务类。

Can I use @Controllerinstead of @Serviceto annotate Service class?

我可以使用@Controller而不是@Service注释服务类吗?

回答by AndreaNobili

No, they are pretty different from each other.

不,它们彼此非常不同。

Both are different specializations of @Componentannotation (in practice, they're two different implementations of the same interface) so both can be discovered by the classpath scanning (if you declare it in your XML configuration)

两者都是@Component注释的不同特化(实际上,它们是同一接口的两种不同实现),因此可以通过类路径扫描发现它们(如果您在 XML 配置中声明它)

@Serviceannotation is used in your service layer and annotates classes that perform service tasks, often you don't use it but in many case you use this annotation to represent a best practice. For example, you could directly call a DAO class to persist an object to your database but this is horrible. It is pretty good to call a service class that calls a DAO. This is a good thing to perform the separation of concerns pattern.

@Service注解用在你的服务层,对执行服务任务的类进行注解,通常你不使用它,但在很多情况下,你使用这个注解来表示最佳实践。例如,你可以直接调用一个 DAO 类来将一个对象持久化到你的数据库中,但这太可怕了。调用一个调用 DAO 的服务类是很不错的。这是执行关注点分离模式的一件好事。

@Controllerannotation is an annotation used in Spring MVC framework (the component of Spring Framework used to implement Web Application). 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. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations.

@Controller注解是 Spring MVC 框架(Spring Framework 中用于实现 Web Application 的组件)中使用的注解。@Controller 注释指示特定类充当控制器的角色。@Controller 注解作为注解类的构造型,表明它的作用。调度程序扫描此类带注释的类以查找映射方法并检测 @RequestMapping 注释。

So looking at the Spring MVC architecture you have a DispatcherServlet class (that you declare in your XML configuration) that represent a front controller that dispatch all the HTTP Request towards the appropriate controller classes (annotated by @Controller). This class perform the business logic (and can call the services) by its method. These classes (or its methods) are typically annotated also with @RequestMappingannotation that specify what HTTP Request is handled by the controller and by its method.

因此,查看 Spring MVC 架构,您有一个 DispatcherServlet 类(您在 XML 配置中声明),它代表一个前端控制器,它将所有 HTTP 请求分派到适当的控制器类(由 @Controller 注释)。此类通过其方法执行业务逻辑(并可调用服务)。这些类(或其方法)通常也使用@RequestMapping批注进行批注,以指定控制器及其方法处理的 HTTP 请求。

For example:

例如:

@Controller
@RequestMapping("/appointments")
public class AppointmentsController {

    private final AppointmentBook appointmentBook;

    @Autowired
    public AppointmentsController(AppointmentBook appointmentBook) {
        this.appointmentBook = appointmentBook;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Appointment> get() {
        return appointmentBook.getAppointmentsForToday();
    }

This class is a controller.

这个类是一个控制器。

This class handles all the HTTP Request toward "/appointments" "folder" and in particular the get method is the method called to handle all the GET HTTP Request toward the folder "/appointments".

此类处理所有指向“/appointments”“文件夹”的 HTTP 请求,特别是 get 方法是处理所有指向“/appointments”文件夹的 GET HTTP 请求的方法。

I hope that now it is more clear for you.

我希望现在你更清楚了。

回答by Raman Sahasi

If you look at the definitions of @Controller, @Serviceannotations, then you'll find that these are special type of @Componentannotation.

如果您查看@Controller,@Service注释的定义,那么您会发现这些是特殊类型的@Component注释。

@Component
public @interface Service {
    ….
}

?

?

@Component
public @interface Controller {
    …
}


So what's the difference?

那么有什么区别呢?

@Controller

@控制器

The @Controllerannotation indicates that a particular class serves the role of a controller. The @Controllerannotation acts as a stereotype for the annotated class, indicating its role.

@Controller注解表明特定类供应控制器的作用。该@Controller注释充当注解类刻板印象,这表明它的作用。

What's special about @Controller?

@Controller 有什么特别之处?

You cannot switch this annotation with any other like @Serviceor @Repository, even though they look same. The dispatcher scans the classes annotated with @Controllerand detects @RequestMappingannotations within them. You can only use @RequestMappingon @Controllerannotated classes.

您不能将此注释与任何其他类似@Service或切换@Repository,即使它们看起来相同。调度程序扫描带有注释的类@Controller并检测其中的@RequestMapping注释。您只能@RequestMapping在带@Controller注释的类上使用。



@Service

@服务

@Serviceshold business logic and call method in repository layer.

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

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 specialty that this annotation provides, but who knows, spring may add some additional exceptional in future.

除了用来表示它持有业务逻辑这一事实之外,这个注解没有提供明显的特殊性,但谁知道,spring 将来可能会添加一些额外的例外。

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

链接答案:Spring 中的 @Component、@Repository 和 @Service 注释之间有什么区别?

回答by NilsH

No, @Controlleris not the same as @Service, although they both are specializations of @Component, making them both candidates for discovery by classpath scanning. The @Serviceannotation is used in your service layer, and @Controlleris for Spring MVC controllers in your presentation layer. A @Controllertypically would have a URL mapping and be triggered by a web request.

不,@Controller与 不同@Service,尽管它们都是 的特化@Component,使它们都是通过类路径扫描发现的候选对象。该@Service注释用于您的服务层,@Controller用于表示层中的 Spring MVC 控制器。A@Controller通常具有 URL 映射并由 Web 请求触发。

回答by Kanthishere

@Service vs @Controller

@Service 与 @Controller

@Service : class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar.

@Service : class 是“业务服务外观”(在核心 J2EE 模式意义上),或类似的东西。

@Controller : Indicates that an annotated class is a "Controller" (e.g. a web controller).

@Controller :表示带注释的类是“控制器”(例如 Web 控制器)。

----------Find Usefull notes on Major Stereotypes http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html

----------查找有关主要构造型的有用说明 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html

@interface Component

@interface 组件

  @Target(value=TYPE)
     @Retention(value=RUNTIME)
     @Documented
    public @interface Component

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 注释。

@interface Controller

@接口控制器

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
public @interface Controller

Indicates that an annotated class is a "Controller" (e.g. a web controller).

表示一个带注释的类是一个“控制器”(例如一个 web 控制器)。

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the RequestMapping annotation.

该注解作为@Component 的特化,允许通过类路径扫描自动检测实现类。它通常与基于 RequestMapping 注释的注释处理程序方法结合使用。

@interface Service

@接口服务

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
public @interface 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)定义为“作为独立于模型中的接口提供的操作,没有封装状态”。也可能表示一个类是“业务服务外观”(在核心 J2EE 模式意义上)或类似的东西。此注释是通用的刻板印象,个别团队可能会缩小其语义范围并酌情使用。

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

该注解作为@Component 的特化,允许通过类路径扫描自动检测实现类。

@interface Repository

@interface 存储库

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
public @interface Repository

Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects". Teams implementing traditional J2EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

表示带注释的类是一个“存储库”,最初由领域驱动设计(Evans,2003)定义为“一种用于封装存储、检索和搜索行为的机制,它模拟对象集合”。实现传统 J2EE 模式(例如“数据访问对象”)的团队也可以将此构造型应用于 DAO 类,但在这样做之前应注意理解数据访问对象和 DDD 样式存储库之间的区别。此注释是通用的刻板印象,个别团队可能会缩小其语义范围并酌情使用。

A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.

当与 PersistenceExceptionTranslationPostProcessor 结合使用时,这样注释的类有资格进行 Spring DataAccessException 转换。出于工具、方面等的目的,还阐明了带注释的类在整个应用程序架构中的作用。

As of Spring 2.5, this annotation also serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

从 Spring 2.5 开始,这个注解也作为 @Component 的特化,允许通过类路径扫描自动检测实现类。

回答by Yasir Shabbir Choudhary

I already answered similar question on here Here is the Link

我已经在这里回答了类似的问题这是链接

No both are different.

不,两者是不同的。

@Service annotation have use for other purpose and @Controller use for other. Actually Spring @Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework, but it doesn't ,mean that all functionalities are same. @Service: It indicates annotated class is a Service component in the business layer.

@Service 注释有其他用途,@Controller 用于其他用途。实际上 Spring @Component、@Service、@Repository 和 @Controller 注释用于在 Spring 框架中使用类路径扫描进行自动 bean 检测,但这并不意味着所有功能都相同。@Service:表示注解类是业务层的Service组件。

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

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

回答by NimChimpsky

No you can't they are different. When the app was deployed your controller mappings would be borked for example.

不,你不能他们是不同的。例如,在部署应用程序时,您的控制器映射将被取消。

Why do you want to anyway, a controller is nota service, and vice versa.

反正你为什么要,控制器不是服务,反之亦然。

回答by cos

From Spring In Action

从春天在行动

As you can see, this class is annotated with @Controller. On its own, @Controller doesn't do much. Its primary purpose is to identify this class as a component for component scanning. Because HomeController is annotated with @Controller, Spring's component scanning automatically discovers it and creates an instance of HomeController as a bean in the Spring application context.

In fact, a handful of other annotations (including @Component, @Service, and @Repository) serve a purpose similar to @Controller. You could have just as effectively annotated HomeController with any of those other annotations, and it would have still worked the same. The choice of @Controller is, however, more descriptive of this component's role in the application.

如您所见,此类使用@Controller 进行了注释。就其本身而言,@Controller 并没有做太多事情。其主要目的是将此类标识为组件扫描的组件。因为 HomeController 是用@Controller 注释的,Spring 的组件扫描会自动发现它,并在 Spring 应用程序上下文中创建一个 HomeController 实例作为 bean。

事实上,其他一些注解(包括@Component、@Service 和@Repository)的作用类似于@Controller。您可以使用任何其他注释对 HomeController 进行同样有效的注释,它仍然可以正常工作。然而,@Controller 的选择更能说明该组件在应用程序中的作用。

回答by Aditya Rewari

You can declare a @serviceas @Controller.

您可以将@service声明为@Controller

You can NOTdeclare an @Controlleras @Service

不能@Controller声明为@Service

@Service

@服务

It is regular. You are just declaring class as a Component.

这是定期的。您只是将类声明为组件。

@Controller

@控制器

It is a little more special than Component. The dispatcherwill search for @RequestMappinghere. So a class annotated with @Controller, will be additionally empowered with declaring URLs through which APIs are called

它比 Component 稍微特殊一点。该调度程序将搜索@RequestMapping这里。所以一个用@Controller 注释的类,将被额外授权声明调用 API 的 URL