Spring注解之@RestController与@Controller的区别

 @RestController官方地址

 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html

 @Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Controller
 @ResponseBody
 public @interface RestController
 A convenience annotation that is itself annotated with @Controller and @ResponseBody.

 Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.

 NOTE: @RestController is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured

 such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace.

 翻译一下

 一个能代替它自己的比较方便的注解是 @Controller 和 @ResponseBody

 携带此注释的类型被视为默认@RequestMapping方法采用@ResponseBody语义的控制器

 如果配置了适当的 HandlerMapping-HandlerAdapter 映射与适配器对,类似于MVC中的Java配置和命名空间中的默认值

 就像RequestMappingHandlerMapping-RequestMappingHandlerAdapter对,则@RestController会被调用用处理

 注意咯,这里指的是,@RestController 等价于 @Controller 和 @ResponseBody

 @Controller官方地址

 https://docs.spring.io/spring-framework/docs/current/javadoc-api/

 @Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
 public @interface Controller
 Indicates that an annotated class is a "Controller" (e.g. a web controller).

 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.

 翻译一下

 指示带注解的类是“控制器”(例如web控制器)。

 此注释是 @Component 的特有一种特有形式,允许实现类通过路径扫描被自动检测到

 它通常用于结合加注解的基于RequestMapping注解的的处理方法

 Returns: the suggested component name, if any (or empty String otherwise),返回的是一个组件名

 二者区别

 @RestController无法返回指定页面,而@Controller可以。

 对于Controller, 如果只是使用@RestController注解,则其方法无法返回指定页面

 此时配置的视图解析器 InternalResourceViewResolver 不起作用,返回的内容就是 return 里的内容。

 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行

 @RestController 可以返回JSON格式字符串

 

上一篇:后端-前台shiro异常信息变更


下一篇:2021-04-05