今天是12月31日,马上元旦告别2020年,走入2021.2020可以说是特别的一年,可以说是比较动荡的一年,之前聊天总喜欢说今年是最差的一年,但是往后十年来看是最好的一年,但是经历了2020,我们经过了这么多磨难,很多都是历史性时刻,新冠,贸易战,美股四次熔断,长租暴雷,最富有看点的美国大选,马拉多纳逝世等等,恨不得一年顶十年,多次见证历史,可以说我们都挺过来,相信这个世界会变好的。
好了,进入正题,新的一年要把这个注解系列丰富起来:
基本上Controller和RestController应该是我们spring mvc 或者 spring boot项目工程上用的最多一个了,页面跳转,对外接口,对内提供服务等都少不了
(实际上spring boot你可以看作一个spring mvc不在web容器屋檐下唯唯诺诺,而是自带web服务器独立重拳出击的升级版)
但是这两个注解@Conroller和@RestController注解有啥关系,我其实更愿意用集合和他的子集来解释。
Controller实际上是@component的一个魔改或者说是一个扩展,算是component的一个子集,@Component和@Bean看代码很像,@Component比@Bean多了一个index注解,功能和作用上也有类似的地方,这也是为什么我上次听到面试,对比@Bean和@Autowire有点疑惑(但实际上看代码,@Bean和@Autowired代码也很像,但是Bean做的事更多一些)。
而RestController是Controller的一个扩展,有人的归纳就是RestController = Controller + ResponseBody,从代码上和作用上看我只能说,老铁没毛病。
请对比一下@Controller和@RestController的代码对比(注意restcontroller代码,理解为什么说RestController是controller的一个扩展)
package org.springframework.stereotype;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
@AliasFor(
annotation = Component.class
)
String value() default "";
}
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Controller;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
@AliasFor(
annotation = Controller.class
)
String value() default "";
}
要知道我们跳转和返回用Controller就可以了,但是加了RequestBody,我们可以不用再去管理入参是否加@RequestBody(实际上我项目中还是加了,毕竟有时候还要用RequestParam),返回JSON数据。
但是用@RestController坏处就是不能跳转页面了,所以你看一些spring boot需要跳转页面都会提醒你要用@Controller注解而不是@RestController注解