目录
注解(annotations)列表及概述
1、@SpringBootApplication
通常配置在主类上。让Spring Boot自动给程序进行必要的配置,该配置等同于:@Configuration(@SpringBootConfiguration)、@ComponentScan、@EnableAutoConfiguration。
@SpringBootConfigurstion 继承@Configuration,此标注当前类是配置类,并会将当前类内声明的一个或者多个已@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名。
@EnableAutoConfiguration 该注解可以让SpringBoot能自动进行配置。主要是通过此注解,能将所有符合自动配置条件的bean的定义加载到spring容器中。
@ComponentScan 该注解会扫描配置的包的当前包及其子包下被@Component、@Controller、@Service、@Repository等注解标记的类并纳入到spring容器中进行管理。
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2、@Configuration
等同于spring中的XML的配置文件
3、@EnableAutoConfiguration
自动配置
4、@ComponentScan
组件扫描,可自动发现和装配一些bean
5、@Component
可配合CommandLineRunner使用,在程序启动后执行一些基础任务。
6、@RestController
该注解时@Controller和@ResponseBody的合集,表示函数的返回值直接写入到HTTP响应体中,时RESTful风格的控制器
7、@Autowired
自动导入Bean
8、@PathVariable
获取参数
9、@JsonBackReference
解决嵌套外链问题
10、RepositoryRestResourcepublic
配合spring-boot-starter-data-rest使用
11、@ResponseBody
该注解表示在一个方法中的返回结果直接写入到Http response body中,一般在异步获取数据时使用,用于构建RESTful的api。在使用@RequestMapping时,返回值通常解析为跳转路径,加上@ResponseBody后返回值结果是不会被解析为跳转路径,而是直接写入http响应体中。
// 1、将方法的返回结果直接写入http响应体中,在浏览器中访问该url会在浏览器中显示“Ok”
@RequestMapping("/test")
@ResponseBody
public String test(){
return "Ok";
}
// 2、将方法返回值作为跳转路径,在浏览器访问该url会跳转到test.html页面
@RequestMapping("/test")
public String test(){
return "/test.html";
}
12、@Controller
该注解用于定义控制器类,在Spring项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),这个注解使用在类上,通常方法需要注解@RequestMapping来配合使用
@Controller
@RequestMapping(“/demoInfo”)
public class DemoController {
@Autowired
private DemoInfoService demoInfoService;
@RequestMapping("/hello")
public String hello(Map<String,Object> map){
System.out.println("DemoController.hello()");
map.put("hello","from TemplateController.helloHtml");
//会使用hello.html或者hello.ftl模板进行渲染显示.
return "/hello";
}
}
13、@RestController
该注解用于标注控制层,是@ResponseBody和@Controller的合集
package com.kfit.demo.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(“/demoInfo2”)
public class DemoController2 {
@RequestMapping("/test")
public String test(){
return "ok";
}
}
14、@RequestMapping
该注解提供路由信息,负责URL到Controller中的具体方法或者类的映射。
package com.kfit.demo.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(“/demoInfo2”)
public class DemoController2 {
@RequestMapping("/test")
public String test(){
return "ok";
}
}