Spring Boot 常用注解汇总

Spring Boot是越来越火了也主要是因为其注解给我们带来了莫大的帮助,使我们开发更加的快速便捷,所以,我们有必要简单的整理一下工作中常用的注解命令。

@SpringBootApplication:作用在主类上,标识该应用为Spring Boot 应用,为应用赋能。

1
2
3
4
5
6
7
8
@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

}

spring-boot-autoconfigure中,我们可以看到@SpringBootApplication包含了@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan三个注解:

1
2
3
4
5
6
7
8
9
10
11
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

}

@Configuration:该注解用于标识该类为一个配置类,作用于类,相当于配置文件如:

1
2
3
4
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" default-autowire="byName">
<bean id="dmsDataSecurityRuleService" class="xxxx.xx.datasecurity.service.DmsDataSecurityRuleService"/>
<bean id="dmsDataSecurityRuleAction" class="xxxx.xx.datasecurity.web.DmsDataSecurityRuleAction"/>
</beans>

@Bean:该注解主要作用于方法,作用是将该方法放回的类实例注入到IOC容器中.默认取方法名为对象bean id,可以使用@Bean注解设置属性值来指定bean id。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Configuration  //标识为配置类
@EnableSwagger2
@EnableSwaggerBootstrapUi
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfiguration {
@Bean("createRestApi") //指定bean id
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo( new ApiInfoBuilder()
//页面标题
.title("Demo Web Api文档")
//创建人
.contact(new Contact("eyiadmin", "https://springfox.github.io/springfox/", "eyiadmin@163.com"))
.version("1.0")
.description("Demo Web Api文档")
.build())
.select()
//API接口所在的包位置
.apis(RequestHandlerSelectors.basePackage("com.eyiadmin.demo.controller"))
.paths(PathSelectors.any())
.build();

}

}

@Scope:该注解作用于类方法,用于指定bean的作用域,默认为单例:

  • prototype:每次从IOC容器中取出对象都是重新创建Bean实例
  • singleton:整个应用IOC容器中只有一个Bean实例
  • request:同一个http请求创建一个Bean实例
  • session:同一个Session会话创建一个Bean实例

@EnableAutoConfiguration:允许 Spring Boot 自动配置注解,开启这个注解之后,Spring Boot 就能根据当前类路径>下的包或者类来配置 Spring Bean。
如:当前类路径下有 Mybatis 这个 JAR 包,MybatisAutoConfiguration 注解就能根据相>关参数来配置 Mybatis 的各个 Spring Bean。

@SpringBootConfiguration:这个注解就是 @Configuration 注解的变体,只是用来修饰是 Spring Boot 配置而已,或>者可利于 Spring Boot 后续的扩展。

@ComponentScan:该注解用来代替配置文件中的 component-scan 配置,开启>组件扫描,相当于context:component-scan,如果扫描到有@Component @Controller @Service等这些注解的类,则把这些类注册为Bean

@Component:该注解是将普通pojo实例化到spring容器中,相当于XML中的,一般加在主类上。

@AutoWired:该注解是将注入到的bean实例取出来,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
当加上(required=false)时,就算找不到bean也不报错。

@RestController:该注解相当于@Controller@ResponseBody两个注解的结合,我们可以再github查看源码https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/web/bind/annotation/RestController.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
* @since 4.0.1
*/
@AliasFor(annotation = Controller.class)
String value() default "";

}

controller相关注解在https://github.com/spring-projects/spring-framework/tree/master/spring-web/src/main/java/org/springframework/web/bind/annotation能找到。

@Controller:该注解主要作用于类上,标识该类为一个控制器,在对应的类上加上该注解,视图解析器可以解析return 的jsp,html页面,并且跳转到相应页面。

@ResponseBody:表示该方法的返回结果直接写入HTTP response body中一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@responsebody后,会直接返回json数据。

@RequestMapping:该注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上,看源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {

String name() default "";

@AliasFor("path")
String[] value() default {};

@AliasFor("value")
String[] path() default {};

RequestMethod[] method() default {};

String[] params() default {};

String[] headers() default {};

String[] consumes() default {};

String[] produces() default {};

}

RequestMethod是一个枚举类型:
public enum RequestMethod {

GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE

}

使用时需要执行valuemethod参数,如:@RequestMapping(value = "hello/{name}", method= RequestMethod.GET).

@GetMapping:该注解将HTTP GET请求映射到指定处理程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {

/**
* Alias for {@link RequestMapping#name}.
*/
@AliasFor(annotation = RequestMapping.class)
String name() default "";

/**
* Alias for {@link RequestMapping#value}.
*/
@AliasFor(annotation = RequestMapping.class)
String[] value() default {};

/**
* Alias for {@link RequestMapping#path}.
*/
@AliasFor(annotation = RequestMapping.class)
String[] path() default {};

/**
* Alias for {@link RequestMapping#params}.
*/
@AliasFor(annotation = RequestMapping.class)
String[] params() default {};

/**
* Alias for {@link RequestMapping#headers}.
*/
@AliasFor(annotation = RequestMapping.class)
String[] headers() default {};

/**
* Alias for {@link RequestMapping#consumes}.
* @since 4.3.5
*/
@AliasFor(annotation = RequestMapping.class)
String[] consumes() default {};

/**
* Alias for {@link RequestMapping#produces}.
*/
@AliasFor(annotation = RequestMapping.class)
String[] produces() default {};

}

我在源码中可以看到@RequestMapping(method = RequestMethod.GET)这句代码,组合了@RequestMapping注解并指定了GET请求方式,一般使用@GetMapping注解时,指定其value属性即可,如:@GetMapping(value = "/name"),等价于上面的@RequestMapping(value = "hello/{name}", method= RequestMethod.GET)。除了@GetMapping,还有@PostMapping@PutMapping@DeleteMapping等,也是才用类似的方式,就不一一说明了。

@PathVariable:该注解用于获取url中占位符的数据,如:

1
2
3
4
5
6
7
@RequestMapping(value = "hello/{name}", method= RequestMethod.GET)
public ResponseEntity<String> Hello( @PathVariable String name)
{
return new ResponseEntity<>(String.format("Hello %s!",name), HttpStatus.OK);
}
请求格式:
http://localhost:8080/demo/hello/jane

@RequestParam:该注解主要用于获取url中的请求参数,如:

1
2
3
4
5
6
7
@RequestMapping(value = "baby", method= RequestMethod.GET)
public ResponseEntity<String> Baby( @RequestParam String name)
{
return new ResponseEntity<>(String.format("Hello, %s Baby!",name), HttpStatus.OK);
}
请求格式:
http://localhost:8080/demo/baby?name=Jane

@RequestBody:该注解用于接收HTTP的Body的内容并序列化为接受类型的对象,可接受复杂嵌套的内容,默认是使用JSON的格式。

还有@RequestHeader@CookieValue等,大家自己去查阅相关文档吧

@Value:该注解主要作用于字段属性,用于属性取值:

  • @value(“值”),如:@value("农民工");
  • @Value(“#{}”) 表示SpEl表达式通常用来获取bean的属性,或者调用bean的某个方法,如:@Value("#{12*2}");
  • @Value(“${xxxx}”)注解从配置文件读取值,如:@Value("${datasource.url}");

    一般我们要取配置文件内容,还会配合@ConfigurationProperties一起使用,主要是用于指定配置文件中的指定 属性与该Bean绑定,如:@ConfigurationProperties("datasource")

@Repository:该注解用于标注数据访问组件(DAO),作用于类,https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/stereotype/Repository.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {

/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
@AliasFor(annotation = Component.class)
String value() default "";

}

@Service:该注解用于标识用业务层组件,作用于类,源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
@AliasFor(annotation = Component.class)
String value() default "";

}

value值作为Bean id,我们可以为Service指定Bean id,如:@Service("serviceBeanId")

@PropertySource:该注解用于导入properties配置文件,如:@PropertySource(value = {"classpath : path/application.properties"}),多配置文件在{}中意逗号(,)隔开。

@ImportResource:该注解用于导入xml配置文件,支持相对路径和绝对路径,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface ImportResource {

@AliasFor("locations")
String[] value() default {};

@AliasFor("value")
String[] locations() default {};

Class<? extends BeanDefinitionReader> reader() default BeanDefinitionReader.class;

}

@ControllerAdvice:该注解主要用于统一处理异常,作用于类,组合了@Component注解,源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {

@AliasFor("basePackages")
String[] value() default {};

@AliasFor("value")
String[] basePackages() default {};

Class<?>[] basePackageClasses() default {};

Class<?>[] assignableTypes() default {};

Class<? extends Annotation>[] annotations() default {};

}

用法如下:

1
2
3
4
5
@ControllerAdvice
public class GlobalExceptionHandler {


}

@ExceptionHandler:该注解声明异常处理方法,作用于方法上,例如:

1
2
3
4
@ExceptionHandler(Exception.class)
String catchException(){
return "";
}

当触发Exception会执行catchException方法。

目前能想到的大概就这些,后面有新发现再补充吧。

[参考]
终于有人总结Spring Boot最常用的25个注解,干货了解一下!

You forgot to set the qrcode for Alipay. Please set it in _config.yml.
You forgot to set the qrcode for Wechat. Please set it in _config.yml.
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×