直接看@RestController 的源码实现:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any
* @since 4.0.1
*/
String value() default "";
}
显然,@RestController = @Controller + @ResponseBody
@RestController 被@Controller 和@ResponseBody标注,即拥有二者的注解语义,因此在注解处理时@RestController 比@Controller多了@ResponseBody 语义,这就是@RestController 和@Controller 的区别,也是@RestController 的返回值为何都是经过转换的 json 都原因。
使用场景:
@Controller表明该类内的所有方法默认返回页面路径,加了@ResponseBody的方法返回数据。
@RestController则是相当于@Controller@ResponseBody两个注解,该类返回的都是数据,不返回页面。
@RestController默认都只提供Rest风格接口返回值,针对不需要返回页面的Controller都采用@RestController进行注解
优劣势:解耦
在@controller注解中,返回的是字符串,或者是字符串匹配的模板名称,即直接渲染视图,与html页面配合使用的,在这种情况下,前后端的配合要求比较高,后端的代码要结合html的情况进行渲染,使用model对象(或者modelandview)将user的属性渲染到页面;前后端耦合度比较高。
而在@restcontroller中,返回的应该是一个对象,这时,在没有页面的情况下,也能看到返回的是一个实体对象对应的json字符串,而前端的作用是利用返回的json进行解析渲染页面,即后端数据与前端进行了解耦。