Spring&SpringBoot常用注解总结

打印 上一主题 下一主题

主题 884|帖子 884|积分 2652

Spring&SpringBoot常用注解总结

1.@SpringBootApplication

这个注解是 Spring Boot 项目标基石,创建 SpringBoot 项目之后会默认在主类加上。
  1. @SpringBootApplication
  2. public class SpringSecurityJwtGuideApplication {
  3.       public static void main(java.lang.String[] args) {
  4.         SpringApplication.run(SpringSecurityJwtGuideApplication.class, args);
  5.     }
  6. }
复制代码
我们可以把 @SpringBootApplication看作是 @Configuration、@EnableAutoConfiguration、@ComponentScan 注解的集合。
  1. package org.springframework.boot.autoconfigure;
  2. @Target(ElementType.TYPE)
  3. @Retention(RetentionPolicy.RUNTIME)
  4. @Documented
  5. @Inherited
  6. @SpringBootConfiguration
  7. @EnableAutoConfiguration
  8. @ComponentScan(excludeFilters = {
  9.     @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  10.     @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
  11. public @interface SpringBootApplication {
  12.    ......
  13. }
  14. package org.springframework.boot;
  15. @Target(ElementType.TYPE)
  16. @Retention(RetentionPolicy.RUNTIME)
  17. @Documented
  18. @Configuration
  19. public @interface SpringBootConfiguration {
  20. }
复制代码
根据 SpringBoot 官网,这三个注解的作用分别是:


  • @EnableAutoConfiguration:启用 SpringBoot 的自动配置机制
  • @ComponentScan:扫描被@Component (@Repository,@Service,@Controller)注解的 bean,注解默认会扫描该类所在的包下所有的类。
  • @Configuration:答应在 Spring 上下文中注册额外的 bean 或导入其他配置类
2.Spring Bean 相干

2.1@Autowired

自动导入对象到类中,被注入进的类同样要被 Spring 容器管理好比:Service 类注入到 Controller 类中。
  1. @Service
  2. public class UserService {
  3.   ......
  4. }
  5. @RestController
  6. @RequestMapping("/users")
  7. public class UserController {
  8.    @Autowired
  9.    private UserService userService;
  10.    ......
  11. }
复制代码
2.2@Component,@Repository,@Service, @Controller

我们一样平常使用 @Autowired 注解让 Spring 容器帮我们自动装配 bean。要想把类标识成可用于 @Autowired 注解自动装配的 bean 的类,可以接纳以下注解实现:


  • @Component:通用的注解,可标注任意类为 Spring 组件。如果一个 Bean 不知道属于哪个层,可以使用@Component 注解标注。
  • @Repository : 对应持久层即 Dao 层,重要用于数据库相干操作。
  • @Service : 对应服务层,重要涉及一些复杂的逻辑,需要用到 Dao 层。
  • @Controller : 对应 Spring MVC 控制层,重要用于接受用户请求并调用 Service 层返回数据给前端页面。
2.3RestController

@RestController注解是@Controller和@ResponseBody的合集,表现这是个控制器 bean,并且是将函数的返回值直接填入 HTTP 响应体中,是 REST 风格的控制器。
单独使用 @Controller 不加 @ResponseBody的话一样平常是用在要返回一个视图的情况,这种情况属于比力传统的 Spring MVC 的应用,对应于前后端不分离的情况。@Controller +@ResponseBody 返回 JSON 或 XML 形式数据
2.4@Scope

声明 Spring Bean 的作用域,使用方法:
  1. @Bean
  2. @Scope("singleton")
  3. public Person personSingleton() {
  4.     return new Person();
  5. }
复制代码
四种常见的 Spring Bean 的作用域:


  • singleton : 唯一 bean 实例,Spring 中的 bean 默认都是单例的。
  • prototype : 每次请求都会创建一个新的 bean 实例。
  • request : 每一次 HTTP 请求都会产生一个新的 bean,该 bean 仅在当前 HTTP request 内有效。
  • session : 每一个 HTTP Session 会产生一个新的 bean,该 bean 仅在当前 HTTP session 内有效
2.5. @Configuration

一样平常用来声明配置类,可以使用 @Component注解替换,不外使用@Configuration注解声明配置类更加语义化。
  1. @Configuration
  2. public class AppConfig {
  3.     @Bean
  4.     public TransferService transferService() {
  5.         return new TransferServiceImpl();
  6.     }
  7. }
复制代码
3. 处理常见的 HTTP 请求类型

5 种常见的请求类型:


  • GET:请求从服务器获取特定资源。举个例子:GET /users(获取所有学生)
  • POST:在服务器上创建一个新的资源。举个例子:POST /users(创建学生)
  • PUT:更新服务器上的资源(客户端提供更新后的整个资源)。举个例子:PUT /users/12(更新编号为 12 的学生)
  • DELETE:从服务器删除特定的资源。举个例子:DELETE /users/12(删除编号为 12 的学生)
  • PATCH:更新服务器上的资源(客户端提供更改的属性,可以看做作是部分更新),使用的比力少,这里就不举例子了
3.1. GET 请求

@GetMapping(“users”) 等价于@RequestMapping(value=“/users”,method=RequestMethod.GET)
  1. @GetMapping("/users")
  2. public ResponseEntity<List<User>> getAllUsers() {
  3. return userRepository.findAll();
  4. }
复制代码
3.2. POST 请求

  1. @PostMapping("users")` 等价于`@RequestMapping(value="/users",method=RequestMethod.POST)
复制代码
关于@RequestBody注解的使用,在下面的“前后端传值”这块会讲到。
  1. @PostMapping("/users")
  2. public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) {
  3. return userRepository.save(userCreateRequest);
  4. }
复制代码
3.3. PUT 请求

  1. @PutMapping("/users/{userId}")` 等价于`@RequestMapping(value="/users/{userId}",method=RequestMethod.PUT)
复制代码
  1. @PutMapping("/users/{userId}")
  2. public ResponseEntity<User> updateUser(@PathVariable(value = "userId") Long userId,
  3.   @Valid @RequestBody UserUpdateRequest userUpdateRequest) {
  4.   ......
  5. }
复制代码
3.4. DELETE 请求

  1. @DeleteMapping("/users/{userId}")`等价于`@RequestMapping(value="/users/{userId}",method=RequestMethod.DELETE)
复制代码
  1. @DeleteMapping("/users/{userId}")
  2. public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){
  3.   ......
  4. }
复制代码
3.5. PATCH 请求

一样平常实际项目中,我们都是 PUT 不够用了之后才用 PATCH 请求去更新数据。
  1.   @PatchMapping("/profile")
  2.   public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) {
  3.         studentRepository.updateDetail(studentUpdateRequest);
  4.         return ResponseEntity.ok().build();
  5.     }
复制代码
4. 前后端传值

4.1. @PathVariable 和 @RequestParam

@PathVariable用于获取路径参数,@RequestParam用于获取查询参数。
举个简单的例子:
  1. @GetMapping("/klasses/{klassId}/teachers")
  2. public List<Teacher> getKlassRelatedTeachers(
  3.          @PathVariable("klassId") Long klassId,
  4.          @RequestParam(value = "type", required = false) String type ) {
  5. ...
  6. }
复制代码
如果我们请求的 url 是:/klasses/123456/teachers?type=web
那么我们服务获取到的数据就是:klassId=123456,type=web。
4.2. @RequestBody

用于读取 Request 请求(大概是 POST,PUT,DELETE,GET 请求)的 body 部分并且Content-Type 为 application/json 格式的数据,接收到数据之后会自动将数据绑定到 Java 对象上去。系统会使用HttpMessageConverter大概自定义的HttpMessageConverter将请求的 body 中的 json 字符串转换为 java 对象。
我用一个简单的例子来给演示一下基本使用!
我们有一个注册的接口:
  1. @PostMapping("/sign-up")
  2. public ResponseEntity signUp(@RequestBody @Valid UserRegisterRequest userRegisterRequest) {
  3.   userService.save(userRegisterRequest);
  4.   return ResponseEntity.ok().build();
  5. }
复制代码
UserRegisterRequest对象:
  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. public class UserRegisterRequest {
  5.     @NotBlank
  6.     private String userName;
  7.     @NotBlank
  8.     private String password;
  9.     @NotBlank
  10.     private String fullName;
  11. }
复制代码
我们发送 post 请求到这个接口,并且 body 携带 JSON 数据:
  1. { "userName": "coder", "fullName": "shuangkou", "password": "123456" }
复制代码
这样我们的后端就可以直接把 json 格式的数据映射到我们的 UserRegisterRequest 类上。
需要注意的是:一个请求方法只可以有一个@RequestBody,但是可以有多个@RequestParam和@PathVariable。 如果你的方法必须要用两个 @RequestBody来接受数据的话,大概率是你的数据库计划大概系统计划出题目了!
5. 读取配置信息

许多时候我们需要将一些常用的配置信息好比阿里云 oss、发送短信、微信认证的相干配置信息等等放到配置文件中。
5.1. @Value(常用)

5.2. @ConfigurationProperties(常用)

通过@ConfigurationProperties读取配置信息并与 bean 绑定。你可以像使用普通的 Spring bean 一样,将其注入到类中使用
5.3. @PropertySource(不常用)

@PropertySource读取指定 properties 文件
6.参数校验

校验的时候我们实际用的是 Hibernate Validator 框架。Hibernate Validator 是 Hibernate 团队最初的数据校验框架,Hibernate Validator 4.x 是 Bean Validation 1.0(JSR 303)的参考实现,Hibernate Validator 5.x 是 Bean Validation 1.1(JSR 349)的参考实现,现在最新版的 Hibernate Validator 6.x 是 Bean Validation 2.0(JSR 380)的参考实现。
SpringBoot 项目标 spring-boot-starter-web 依靠中已经有 hibernate-validator 包,不需要引用相干依靠。如下图所示(通过 idea 插件—Maven Helper 天生):
:更新版本的 spring-boot-starter-web 依靠中不再有 hibernate-validator 包(如 2.3.11.RELEASE),需要本身引入 spring-boot-starter-validation 依靠。
6.1. 一些常用的字段验证的注解



  • @NotEmpty 被解释的字符串的不能为 null 也不能为空
  • @NotBlank 被解释的字符串非 null,并且必须包罗一个非空白字符
  • @Null 被解释的元素必须为 null
  • @NotNull 被解释的元素必须不为 null
  • @AssertTrue 被解释的元素必须为 true
  • @AssertFalse 被解释的元素必须为 false
  • @Pattern(regex=,flag=)被解释的元素必须符合指定的正则表达式
  • @Email 被解释的元素必须是 Email 格式。
  • @Min(value)被解释的元素必须是一个数字,其值必须大于便是指定的最小值
  • @Max(value)被解释的元素必须是一个数字,其值必须小于便是指定的最大值
  • @DecimalMin(value)被解释的元素必须是一个数字,其值必须大于便是指定的最小值
  • @DecimalMax(value) 被解释的元素必须是一个数字,其值必须小于便是指定的最大值
  • @Size(max=, min=)被解释的元素的巨细必须在指定的范围内
  • @Digits(integer, fraction)被解释的元素必须是一个数字,其值必须在可接受的范围内
  • @Past被解释的元素必须是一个过去的日期
  • @Future 被解释的元素必须是一个将来的日期
6.2. 验证请求体(RequestBody)

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. public class Person {
  5.     @NotNull(message = "classId 不能为空")
  6.     private String classId;
  7.     @Size(max = 33)
  8.     @NotNull(message = "name 不能为空")
  9.     private String name;
  10.     @Pattern(regexp = "((^Man$|^Woman$|^UGM$))", message = "sex 值不在可选范围")
  11.     @NotNull(message = "sex 不能为空")
  12.     private String sex;
  13.     @Email(message = "email 格式不正确")
  14.     @NotNull(message = "email 不能为空")
  15.     private String email;
  16. }
复制代码
我们在需要验证的参数上加上了@Valid注解,如果验证失败,它将抛出MethodArgumentNotValidException
6.3. 验证请求参数(Path Variables 和 Request Parameters)

一定一定不要忘记在类上加上 @Validated 注解了,这个参数可以告诉 Spring 去校验方法参数。
7. 全局处理 Controller 层非常

相干注解:

  • @ControllerAdvice :注解定义全局非常处理类
  • @ExceptionHandler :注解声明非常处理方法
8.事件 @Transactional

在要开启事件的方法上使用@Transactional注解即可!
  1. @Transactional(rollbackFor = Exception.class)
  2. public void save() {
  3.   ......
  4. }
复制代码
我们知道 Exception 分为运行时非常 RuntimeException 和非运行时非常。在@Transactional注解中如果不配置rollbackFor属性,那么事件只会在遇到RuntimeException的时候才会回滚,加上rollbackFor=Exception.class,可以让事件在遇到非运行时非常时也回滚。
@Transactional 注解一样平常可以作用在类大概方法上。


  • 作用于类:当把@Transactional 注解放在类上时,表现所有该类的 public 方法都配置相同的事件属性信息。
  • 作用于方法:当类配置了@Transactional,方法也配置了@Transactional,方法的事件会覆盖类的事件配置信息。
9. json 数据处理

过滤 json 数据

@JsonIgnoreProperties 作用在类上用于过滤掉特定字段不返回大概不解析。
  1. //生成json时将userRoles属性过滤
  2. @JsonIgnoreProperties({"userRoles"})
  3. public class User {
  4.     private String userName;
  5.     private String fullName;
  6.     private String password;
  7.     private List<UserRole> userRoles = new ArrayList<>();
  8. }
复制代码
@JsonIgnore一样平常用于类的属性上,作用和上面的@JsonIgnoreProperties 一样。
  1. public class User {
  2.     private String userName;
  3.     private String fullName;
  4.     private String password;
  5.    //生成json时将userRoles属性过滤
  6.     @JsonIgnore
  7.     private List<UserRole> userRoles = new ArrayList<>();
  8. }
复制代码
格式化 json 数据

@JsonFormat一样平常用来格式化 json 数据。
  1. @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT")
  2. private Date date;
复制代码
扁平化对象

  1. @Getter
  2. @Setter
  3. @ToString
  4. public class Account {
  5.     private Location location;
  6.     private PersonInfo personInfo;
  7.   @Getter
  8.   @Setter
  9.   @ToString
  10.   public static class Location {
  11.      private String provinceName;
  12.      private String countyName;
  13.   }
  14.   @Getter
  15.   @Setter
  16.   @ToString
  17.   public static class PersonInfo {
  18.     private String userName;
  19.     private String fullName;
  20.   }
  21. }
复制代码
未扁平化之前:
  1. {
  2.   "location": {
  3.     "provinceName": "湖北",
  4.     "countyName": "武汉"
  5.   },
  6.   "personInfo": {
  7.     "userName": "coder1234",
  8.     "fullName": "shaungkou"
  9.   }
  10. }
复制代码
使用@JsonUnwrapped 扁平对象之后:
  1. @Getter
  2. @Setter
  3. @ToString
  4. public class Account {
  5.     @JsonUnwrapped
  6.     private Location location;
  7.     @JsonUnwrapped
  8.     private PersonInfo personInfo;
  9.     ......
  10. }
  11. {
  12.   "provinceName": "湖北",
  13.   "countyName": "武汉",
  14.   "userName": "coder1234",
  15.   "fullName": "shaungkou"
  16. }
复制代码
10.测试相干

@ActiveProfiles一样平常作用于测试类上, 用于声明见效的 Spring 配置文件。
  1. @SpringBootTest(webEnvironment = RANDOM_PORT)
  2. @ActiveProfiles("test")
  3. @Slf4j
  4. public abstract class TestBase {
  5.   ......
  6. }
复制代码
@Test声明一个方法为测试方法
@Transactional被声明的测试方法的数据会回滚,克制污染测试数据。
@WithMockUser Spring Security 提供的,用来模拟一个真实用户,并且可以赋予权限。
  1.     @Test
  2.     @Transactional
  3.     @WithMockUser(username = "user-id-18163138155", authorities = "ROLE_TEACHER")
  4.     void should_import_student_success() throws Exception {
  5.         ......
  6.     }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

光之使者

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表