Spring中@Controller和@RestController注解的区别
Spring Annotations是一种元数据形式,提供有关程序的数据。注释用于提供有关程序的补充信息。它对他们注释的代码的操作没有直接影响。它不会改变编译程序的动作。
@Controller 注解: Spring @Controller 注解也是@Component 注解的特化。 @Controller 注释表明一个特定的类充当控制器的角色。 Spring Controller 注解通常与基于注解的处理程序方法结合使用 @RequestMapping 注解。它只能应用于类。它用于将类标记为 Web 请求处理程序。它主要用于 Spring MVC 应用程序。这个注解充当被注解类的原型,表明它的作用。调度程序扫描这些带注释的类以查找映射方法并检测@RequestMapping注释。
Tip: Do read more about Spring @Controller Annotation with Example to get a better understanding.
@RestController 注解: RestController 用于借助@RestController 注解制作restful web 服务。此注解用于类级别,并允许类处理客户端发出的请求。让我们通过一个例子来理解@RestController 注解。 RestController 允许处理所有 REST API,例如 GET、POST、Delete 和 PUT 请求。
Tip: Do read more about Spring – REST Controller to get a better understanding.
现在让我们提出两者之间的主要区别,如下所示。这里@Controller 用于将类标记为Spring MVC Controller,而@RestController 是一个方便的注解,它只是添加@Controller 和@ResponseBody 注解,参考以下代码片段:
@Controller
@ResponseBody
class Controller
{
------
------
------
}
它相当于
@RestController
class RestController
{
------
------
------
}
让我们最后通过表格格式总结它们之间的差异,下面以表格格式描述如下: @Controller @RestController@Controller is used to mark classes as Spring MVC Controller. @RestController annotation is a special controller used in RESTful Web services, and it’s the combination of @Controller and @ResponseBody annotation. It is a specialized version of @Component annotation. It is a specialized version of @Controller annotation. In @Controller, we can return a view in Spring Web MVC. In @RestController, we can not return a view. @Controller annotation indicates that the class is a “controller” like a web controller. @RestController annotation indicates that class is a controller where @RequestMapping methods assume @ResponseBody semantics by default. In @Controller, we need to use @ResponseBody on every handler method. In @RestController, we don’t need to use @ResponseBody on every handler method. It was added to Spring 2.5 version. It was added to Spring 4.0 version.