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格式字符串

 

posted @   BigBender  阅读(153)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2020-01-17 行列式展开定理
点击右上角即可分享
微信分享提示
主题色彩