Spring-Boot常用注解总结

Spring-Boot常用注解总结

@SpringBootApplication 相当于 @Configuration @ComponentScan @EnableAutoConfiguration 三个注解

这个注解是 Spring Boot 项目的基石,创建 SpringBoot 项目之后会默认在主类加上。

@SpringBootApplication 
public class DemoApplication {

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

}

我们可以把 @SpringBootApplication看作是 @Configuration@EnableAutoConfiguration@ComponentScan 注解的集合。

package org.springframework.boot.autoconfigure;
@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 {
   ......
}

package org.springframework.boot;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {

}

根据 SpringBoot 官网,这三个注解的作用分别是:

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

2. Spring Bean 相关

2.1. @Autowired

自动导入对象到类中,被注入进的类同样要被 Spring 容器管理比如:Service 类注入到 Controller 类中。

@Service
public class DemoService {
  ......
}

@RestController
@RequestMapping("/demo")
public class DemoController {
   @Autowired
   private DemoService demoService;
   ......
}

2.2. Component,@Repository,@Service@Controller

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

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

2.3. @RestController

@RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器 bean,并且是将函数的返回值直 接填入 HTTP 响应体中,是 REST 风格的控制器。

单独使用 @Controller 不加 @ResponseBody的话一般使用在要返回一个视图的情况,这种情况属于比较传统的 Spring MVC 的应用,对应于前后端不分离的情况。@Controller +@ResponseBody 返回 JSON 或 XML 形式数据。

2.4. @Scope

声明 Spring Bean 的作用域,使用方法:

@Bean
@Scope("singleton")
public Demo demoSingleton() {
    return new Demo();
}

四种常见的 Spring Bean 的作用域:

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

2.5. Configuration

一般用来声明配置类,可以使用 @Component注解替代,不过使用Configuration注解声明配置类更加语义化。

@Configuration
public class DemoConfig {
    @Bean
    public DemoService demoService() {
        return new DemoServiceImpl();
    }

}

3. 处理常见的 HTTP 请求类型

5 种常见的请求类型:

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

3.1. GET 请求

@GetMapping("demos") 等价于@RequestMapping(value="/demos",method=RequestMethod.GET)

@GetMapping("/demos")
public ResponseEntity<List<Demo>> getAllDemos() {
 return demoRepository.findAll();
}

3.2. POST 请求

@PostMapping("demos") 等价于@RequestMapping(value="/demos",method=RequestMethod.POST)

关于@RequestBody注解的使用,在下面的“前后端传值”这块会讲到。

@PostMapping("/demos")
public ResponseEntity<Demo> createDemo(@Valid @RequestBody DemoCreateRequest demoCreateRequest) {
 return demoRespository.save(demo);
}

3.3. PUT 请求

@PutMapping("/demos/{demoId}") 等价于@RequestMapping(value="/demos/{demoId}",method=RequestMethod.PUT)

@PutMapping("/demos/{demoId}")
public ResponseEntity<Demo> updateDemo(@PathVariable(value = "demoId") Long demoId,
  @Valid @RequestBody DemoUpdateRequest demoUpdateRequest) {
  ......
}

3.4. DELETE 请求

@DeleteMapping("/demos/{demoId}")等价于@RequestMapping(value="/demos/{demoId}",method=RequestMethod.DELETE)

@DeleteMapping("/demos/{demoId}")
public ResponseEntity deleteDemo(@PathVariable(value = "demoId") Long demoId){
  ......
}

3.5. PATCH 请求

一般实际项目中,我们都是 PUT 不够用了之后才用 PATCH 请求去更新数据。

  @PatchMapping("/demo")
  public ResponseEntity updateDemo(@RequestBody DemoUpdateRequest demoUpdateRequest) {
        demoRepository.updateDetail(demoUpdateRequest);
        return ResponseEntity.ok().build();
    }

4. 前后端传值

掌握前后端传值的正确姿势,是你开始 CRUD 的第一步!

4.1. @PathVariable 和 @RequestParam

@PathVariable用于获取路径参数,@RequestParam用于获取查询参数。

举个简单的例子:

@GetMapping("/groups/{groupId}/emps")
public List<Emp> getGroupRelatedEmps(
         @PathVariable("groupId") Long groupId,
         @RequestParam(value = "param", required = false) String param ) {
...
}

如果我们请求的 url 是:/groups/{123}/emps?param=tony

那么我们服务获取到的数据就是:groupId=123,param=tony

4.2. @RequestBody

用于读取 Request 请求(可能是 POST,PUT,DELETE,GET 请求)的 body 部分并且Content-Type 为 application/json 格式的数据,接收到数据之后会自动将数据绑定到 Java 对象上去。系统会使用HttpMessageConverter或者自定义的HttpMessageConverter将请求的 body 中的 json 字符串转换为 java 对象。

我用一个简单的例子来给演示一下基本使用!

我们有一个注册的接口:

@PostMapping("/registe")
public ResponseEntity registe(@RequestBody @Valid DemoRegisterRequest demoRegisterRequest) {
  demoService.save(demoRegisterRequest);
  return ResponseEntity.ok().build();
}

DemoRegisterRequest对象:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserRegisterRequest {
    @NotBlank
    private String name;
    @NotBlank
    private String pwd;
    @FullName
    @NotBlank
    private String nick;
}

我们发送 post 请求到这个接口,并且 body 携带 JSON 数据:

{"name":"tony","nick":"hello","pwd":"123456"}

这样我们的后端就可以直接把 json 格式的数据映射到我们的 UserRegisterRequest 类上。

👉 需要注意的是:一个请求方法只可以有一个@RequestBody,但是可以有多个@RequestParam@PathVariable。 如果你的方法必须要用两个 @RequestBody来接受数据的话,大概率是你的数据库设计或者系统设计出问题了!

5. 读取配置信息

很多时候我们需要将一些常用的配置信息比如阿里云 oss、发送短信、微信认证的相关配置信息等等放到配置文件中。

下面我们来看一下 Spring 为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。

我们的数据源application.yml内容如下::

test=测试
test.address=北京北京
test.name=hello

5.1. @value(常用)

使用 @Value("${property}") 读取比较简单的配置信息:

@Value("${test}")
String test;

5.2. @ConfigurationProperties(常用)

通过@ConfigurationProperties读取配置信息并与 bean 绑定。

@Data
@Component
@ConfigurationProperties(prefix = "test")
class TestConfig {
    
    private String address;

    private String name;
  ......
}

你可以像使用普通的 Spring bean 一样,将其注入到类中使用。

5.3. PropertySource(不常用)

@PropertySource读取指定 properties 文件

@Data
@Component
@PropertySource("classpath:test.properties")

class Test {
    @Value("${address}")
    private String address;
    
    @Value("${name}")
    private String name;
  ......
}

 

6. 参数校验

数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。

JSR(Java Specification Requests) 是一套 JavaBean 参数校验的标准,它定义了很多常用的校验注解,我们可以直接将这些注解加在我们 JavaBean 的属性上面,这样就可以在需要校验的时候进行校验了,非常方便!

校验的时候我们实际用的是 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)的参考实现,springboot 2.3之后消失的hibernate-validator,需要引入手动引入spring-boot-starter-validation。

 

 <dependency>
     <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
 </dependency>

👉 需要注意的是: 所有的注解,推荐使用 JSR 注解,即javax.validation.constraints,而不是org.hibernate.validator.constraints

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)

package com.example.demo.request;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class DemoRegisterReq {

    @NotBlank(message = "name不能为空")
    private String name;

    @NotNull(message = "密码不能为空")
    @Pattern(regexp = "^(?=.*[a-zA-Z0-9].*)(?=.*[a-zA-Z.!@#$%^&*].*)(?=.*[0-9.!@#$%^&*].*).{6,32}$",message = "密码至少包含数字,字母和符号的两种")
    private String pwd;

    @Email(message = "email格式不正确")
    @NotNull(message = "email 不能为空")
    private String email;

}

我们在需要验证的参数上加上了@Valid注解,如果验证失败,它将抛出MethodArgumentNotValidException


@RestController
@RequestMapping("/api")
public class Controller {

    Logger logger = LoggerFactory.getLogger(Controller.class);

    @PostMapping("/demo")
    public Result demo(@RequestBody @Valid DemoRegisterReq demoRegisterReq){
        return Result.ok().data("data",demoRegisterReq);
    }
}

6.3. 验证请求参数(Path Variables 和 Request Parameters)

一定一定不要忘记在类上加上 Validated 注解了,这个参数可以告诉 Spring 去校验方法参数。

@RestController
@RequestMapping("/api")
@Validated
public class Controller {

    @GetMapping("/demo/{id}")
    public Result demo(@Valid @PathVariable("id") @Max(value = 5,message = "超过 id 的范围了") Integer id) {
        return Result.ok().data("id",id);
    }
}

7. 全局处理 Controller 层异常

介绍一下我们 Spring 项目必备的全局处理 Controller 层异常。

相关注解:

  1. @RestControllerAdvice :注解定义全局异常处理类
  2. @ExceptionHandler :注解声明异常处理方法

如何使用呢?拿我们在第 5 节参数校验这块来举例子。如果方法参数不对的话就会抛出MethodArgumentNotValidException,我们来处理这个异常。

@RestControllerAdvice(basePackages = "com.example.demo")
public class GlobalExceptionHandler {

    Logger logger = LoggerFactory.getLogger(GlobalException.class);

    @ExceptionHandler(GlobalException.class)
    public BaseResult handlerGlobalException(GlobalException g){
        logger.error(g.getMessage(),g);
        return BaseResult.error().message(g.getMessage()).code(g.getCode());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResult handlerMethodArgException(MethodArgumentNotValidException m){
        logger.error(m.getMessage(),m);
        return BaseResult.error().message(m.getMessage());
    }
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值