zoukankan      html  css  js  c++  java
  • 理解Spring4.0新特性@RestController注解

    参考原文 

    @RestController注解是它继承自@Controller注解。4.0之前的版本,spring MVC的组件都使用@Controller来标识当前类是一个控制器servlet。 
    使用这个特性,我们可以开发REST服务的时候不需要使用@Controller而专门的@RestController。

    当你实现一个RESTful web services的时候,response将一直通过response body发送。为了简化开发,Spring 4.0提供了一个专门版本的controller。下面我们来看看@RestController实现的定义:

    Java代码代码:
    @Target(value=TYPE)    
     @Retention(value=RUNTIME)    
     @Documented    
     @Controller    
     @ResponseBody    
    public @interface RestController  

    Spring的官方文档解释如下:

    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. 注解本身使用@Controller和@ResponseBody注解。使用了这个注解的类会被看作一个controller-使用@RequestMapping的方法有一个默认的@ResponseBody注解。 @ResponseBody – As of version 4.0 this annotation can also be added on the type level in which case is inherited and does not need to be added on the method level. @ResponseBody也可以加到类一级,通过继承方法一级不需要添加。

    为了更加了解@RestController注解先了解一下@ResponseBody注解: 
    该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。 

    使用时机: 
    返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

    当我们在Controller上标注了@RestController,这样相当于Controller的所有方法都标注了@ResponseBody

  • 相关阅读:
    边缘检测算法——Canny和LoG边缘检测算法
    Java读书笔记03 输入输出
    CMake入门
    二叉树及二叉树的遍历
    Java读书笔记11 图形程序——颜色 字体 图像
    XNA实现骨骼动画 归纳总结
    Java读书笔记09 内部类
    Java读书笔记02 基础知识
    Java用户界面 模型视图控制器(MVC)模式
    简单理解传值和传引用
  • 原文地址:https://www.cnblogs.com/panchanggui/p/10383378.html
Copyright © 2011-2022 走看看