@RestController的使用

来源:互联网 发布:js转换日期格式 编辑:程序博客网 时间:2024/06/02 07:15
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Controller@ResponseBodypublic @interface RestController {    String value() default "";}

可以看到,该注解本身使用@Controller@ResponseBody注解。使用这个特性,我们可以开发REST服务的时候不需要使用@Controller@ResponseBody 而使用专门的@RestController

但是即使这样使用也是不行的:

@org.springframework.web.bind.annotation.RestControllerpublic class RestController {    @RequestMapping(value = "/rest", method = RequestMethod.GET)    public String test() {        return "hello";    }}

这里写图片描述

通过查看官方文档得知:

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. In particular @RestController is not supported with the DefaultAnnotationHandlerMapping-AnnotationMethodHandlerAdapter pair both of which are also deprecated.

也就是需要使用RequestMappingHandlerMapping以及 RequestMappingHandlerAdapter。默认的DefaultAnnotationHandlerMappingAnnotationMethodHandlerAdapter 则不可以。

不加<mvc:annotation-driven/> 注解的情况下:
这里写图片描述
<mvc:annotation-driven/> 注解的情况下:
这里写图片描述

curl http://localhost:8080/SpringMVCDemo/rest
hello