前言
使用注解的优势:
1.采用纯java代码,不在需要配置繁杂的xml文件
2.在配置中也可享受面向对象带来的好处
3.类型安全对重构可以提供良好的支持
4.减少复杂配置文件的同时亦能享受到springIoC容器提供的功能
Spring Boot的核心就是注解。Spring Boot通过各种组合注解,极大地简化了Spring项目的搭建和开发。在Spring Boot中有一些注解是其中的关键,必须掌握。接下来就给大家做详细的介绍。
一、注解(annotations)列表
@SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。其中@ComponentScan让spring Boot扫描到Configuration类并把它加入到程序上下文。
@Configuration 等同于spring的XML配置文件;使用Java代码可以检查类型安全。
@EnableAutoConfiguration 自动配置。
@ComponentScan 组件扫描,可自动发现和装配一些Bean。
@Component可配合CommandLineRunner使用,在程序启动后执行一些基础任务。
@RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器bean,并且是将函数的返回值直 接填入HTTP响应体中,是REST风格的控制器。
@Autowired自动导入。
@PathVariable获取参数。
@JsonBackReference解决嵌套外链问题。
@RepositoryRestResourcepublic配合spring-boot-starter-data-rest使用。
二、注解(annotations)详解
@SpringBootApplication:申明让spring boot自动给程序进行必要的配置,这个配置等同于:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三个配置。
package com.example.myproject;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScanpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
@ResponseBody:表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用,用于构建RESTful的api。在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@responsebody后,会直接返回json数据。该注解一般会配合@RequestMapping一起使用。示例代码:
@RequestMapping(“/test”)@ResponseBody public String test(){return”ok”;}
@Controller:用于定义控制器类,在spring 项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),一般这个注解在类中,通常方法需要配合注解@RequestMapping。示例代码:
@Controller @RequestMapping(“/demoInfo”)publicclass DemoController {@Autowired private DemoInfoService demoInfoService;@RequestMapping("/hello")public String hello(Map map){System.out.println("DemoController.hello()");map.put("hello