Spring Boot 第一个示例的 @RestController 和 @RequestMapping 注解

在示例源代码类中的第一个注解(annotation)是 @RestController。 这个注解被称为 stereotype 注解。在使用 Spring 的时候,需要对注解有所了解。Spring 有多个类型的注解,例如在包 org.springframework.context.annotation 和 org.springframework.stereotype 的注解。 不仅仅是 @Component,他的派生注解 @Service、@Controller、@RestController 和 @Repository都在这个包中,实际上它就是在告诉使用者这些注解提供 stereotype 的特性(或者称为功能、作用)。 Stereotype 特性最早出现在J2EE6 中,可以理解为围绕着 “元数据” 功能而发展出来的一种设计模式。 这个注解提示人们在阅读代码的时候了解 Spring 实现的功能和扮演的特定的角色。 在这个类中,我们告诉 Spring 是一个 Web 的 @Controller,因此 Spring 会通过这个注解来考虑这个类用于处理访问的 Web 请求。

con-01

@RequestMapping 注解,为我们的应用提供了 “routing” 信息。在这里的 routing 可以理解为路径,在我们访问 Web 资源的时候都会要求提供一个路径的信息。 具体有关这个注解的解释为任何 HTTP 的请求,如果使用了 / 路径的话,所有的请求将会映像到 home 方法,或者可以理解为 home 方法 将会被执行。 @RestController 注解将会告诉 Spring 将返回的结果使用 String 字符串来进行渲染,然后将渲染的结果返回给调用者。

@Controller 和 @RestController 之间有什么区别? 非常简单来说 @RestController 是一个特殊版本的 controller。是由 @Controller@ResponseBody 2 个注解合并而成的。 在没有 @RestController 注解之前,你可以使用 @Controller,同时你还需要使用 @ResponseBody 注解来确定返回的内容是什么。设计 @RestController 的目的主要也是为了针对目前越来越流行的微服务和 Rest API 的开发来设计的。

con-02

@RestController@RequestMapping 注解都是 Spring MVC 中的注解(这 2 个注解是没有在 Spring Boot 中指定的)。 请参考 Spring 参考文档中的 MVC 部分 来获得更多的有关信息。

https://www.ossez.com/t/spring-boot-restcontroller-requestmapping/1100

猜你喜欢

转载自blog.csdn.net/huyuchengus/article/details/112450144