SpingBoot整合Swagger和Hibernate-Validate练习

需求:用SpingBoot+Swagger+Hibernate-Validate集成一个demo,用Swagger查看Controller的接口文档。Swagger接口包括Controller的请求和返回,用Hibernate-Validate校验Controller的请求参数的合法性。目前只需要校验非空即可。

1.新建一个Springboot项目,在Pom文件中引入依赖

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-validationartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-boot-starterartifactId>
            <version>3.0.0version>
        dependency>

2.创建一个实体类 User.java,并在字段上添加校验注解

package com.example.swaggerdemo.domain;

import javax.validation.constraints.*;

public class User {

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

    @NotNull(message = "年龄不能为空哦")
    @Max(message = "最大为150哦",value = 150)
    @Min(message = "最小为0哦",value = 0)
    private Integer age;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

@NotBlank 只能注解String字符串类型 @NotNull可以注解在Integer类型

3.在启动类上添加swagger注解,开启swagger

package com.example.swaggerdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;

@SpringBootApplication
@EnableOpenApi
public class SwaggerdemoApplication {

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

}

@EnableOpenApi 注解用于开启swagger

4.编写UserController控制类

package com.example.swaggerdemo.controller;

import com.example.swaggerdemo.domain.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/system/user")

//@Api(tags = "用户管理",value = "用户管理")
@Tag(name="用户管理")
public class UserController {

    //@ApiOperation(value = "获取员工信息",notes = "传入字段不能为空哦")
    @Operation(tags = "获取员工信息",summary = "传入字段不能为空哦")
    @PostMapping("/getMessage")
    public String getMessage(@RequestBody @Validated User user){
        return "成功啦--名字:"+user.getName()+"年龄:"+user.getAge();
    }
}

5.编写统一异常处理控制器

package com.example.swaggerdemo;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理POST请求参数校验异常
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String,Object>> validExceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String, Object> errorMap = fieldErrors.stream()
                .collect(Collectors.toMap(item -> item.getField(), item -> item.getDefaultMessage()));
        return ResponseEntity.badRequest().body(errorMap);
    }
}

6.效果

在浏览器访问http://localhost:9999/swagger-ui/

SpingBoot整合Swagger和Hibernate-Validate练习_第1张图片

使用接口测试工具ApiPost发送请求

SpingBoot整合Swagger和Hibernate-Validate练习_第2张图片
SpingBoot整合Swagger和Hibernate-Validate练习_第3张图片

7.源码

Gitee仓库:https://gitee.com/yangxumin/springbootswagger.git

你可能感兴趣的:(hibernate,java,spring,boot)