将java对象转为json格式的数据,将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。代表每个返回的数据直接返给浏览器,而不是跳转到某个页面
注意:在使用此注解之后不会再走视图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
例如:
@ResponseBody @Controller public class HelloController { @RequestMapping("/hello") public String handle01(){ return "hello, springboot!"; } }
可以使用@RestController代替@ResponseBody与@Controller
@RestController:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @documented @Controller @ResponseBody public @interface RestController { @AliasFor( annotation = Controller.class ) String value() default ""; }@RequestBody
@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。
作用:
- 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定
到要返回的对象上;再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
@Target:描述注解能够作用的位置
ElementType取值
TYPE:可以作用于类上METHOD:可以作用于方法上FIELD:可以作用于成员变量上 @Retention:描述注解被保留的阶段
@Retention(RetentionPolicy.RUNTIME):当前被描述的注解,会保留到class字节码文件中,并被JVM读取@Retention(RetentionPolicy.CLASS):当前被描述的注解,会保留到class字节码文件中@Retention(RetentionPolicy.SOURCE):字节码文件中都不会存在注解 @documented:描述注解是否被抽取到api对象@Inherited:描述注解是否被子类继承 @Configuration
springboot 2.1版本
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @documented @Component public @interface Configuration { @AliasFor( annotation = Component.class ) String value() default ""; }
2.3版本
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @documented @Component public @interface Configuration { @AliasFor( annotation = Component.class ) String value() default ""; boolean proxyBeanMethods() default true; }
注意的是在2.1版本中并没有代理模式的配置
@Configuration(proxyBeanMethods = false/true)
如果为true,得到的配置对象时代理对象,调用多次仍旧为同一对象
如果为false,每次调用会调用其代码
代理模式为false,每次运行启动速度读都较快,跳过检查实例在容器中是否存在,使用true每一次调用都要检查容器中是否存在,会慢一些。
@AliasFor注解的别名
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)