一篇教你学会SpringBoot集成Swagger2

125 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

学习要求

良好的java基础, 熟悉SpringBoot框架,熟悉RESTful接口开发

教学目标

了解并掌握SpringBoot集成Swagger2

##环境

springboot2.4.3 + swagger2

集成步骤

1>创建SpringBoot项目

image.png

pom.xml文件

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.3</version>
    <relativePath/>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

EmployeeController

@RestController
@RequestMapping("employees")
public class EmployeeController {
    @GetMapping
    public List<Employee> list(){
        return Arrays.asList(new Employee(1L,"dafei", 18),new Employee(2L,"xiaofei", 16));
    }
    @GetMapping("/detail")
    public Employee detail(Long id){
        return new Employee(id, "dafei", 18);
    }
   
    @DeleteMapping
    public JsonResult delete(Long id){
        System.out.println("删除了.....");
        return JsonResult.success();
    }
    @PutMapping
    public Employee update(Employee employee){
        employee.setName(employee.getName() +"_update");
        return employee;
    }
    @PostMapping
    public Employee add(Employee employee){
        employee.setId(1L);
        return employee;
    }
}

Employee

public class Employee {
    private Long id;
    private String name;
    private int age;
 
    public Employee() {
    }
 
    public Employee(Long id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
}

JsonResult

public class JsonResult {
    private int code;
    private String msg;
    private Object data;
    public JsonResult(int code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    public static JsonResult success(){
        return new JsonResult(200, "操作成功", null);
    }
    public static JsonResult success(Object data){
        return new JsonResult(200, "操作成功", data);
    }
 
    public static JsonResult error(String msg){
        return new JsonResult(500, msg, null);
    }
 
 
}

App

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

2>导入swagger2依赖

在pom.xml文件中导入jar包

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>
 
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>

3>配置swagger2

新建swagger2包,添加SwaggerConfig配置类

image.png

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
 
    @Bean
    public Docket productApi() {
 
        //添加head参数start
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        //这个位置设置请求头:比如令牌
        tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());
 
        return new Docket(DocumentationType.SWAGGER_2).select()
                // 扫描的包路径
                .apis(RequestHandlerSelectors.basePackage("com.langfeiyes.restful.controller"))
                // 定义要生成文档的Api的url路径规则
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars)
                // 设置swagger-ui.html页面上的一些元素信息。
                .apiInfo(metaData());
    }
 
    private ApiInfo metaData() {
        return new ApiInfoBuilder()
                // 标题
                .title("SpringBoot集成Swagger2")
                // 描述
                .description("xxx项目接口文档")
                // 文档版本
                .version("1.0.0")
                .license("Apache License Version 2.0")
                .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0")
                .build();
    }
 
    //ui页面
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

 4>启动项目并测试

右键运行App类,访问:http://localhost:8080/swagger-ui.html

image.png

使用介绍

image.png

image.png

image.png

image.png

image.png

image.png

image.png

常用注解

@Api/@ApiOperation

@Api:用在类上,说明该类的作用

@RestController
@RequestMapping("employees")
@Api(value = "用户资源",tags = "用户资源控制器")
public class EmployeeController {
   ....
}

image.png

@ApiOperation:用在方法上,说明方法的作用

@ApiOperation(value = "员工添加",notes = "其实就是新增员工")
@PostMapping
public Employee add(Employee employee){
	employee.setId(1L);
	return employee;
}

image.png

 @ApiImplicitParams/@ApiImplicitParam

@ApiImplicitParams:用在方法上包含一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

@ApiImplicitParams({
		@ApiImplicitParam(value = "昵称",name = "name",dataType = "String",required = true),
		@ApiImplicitParam(value = "年龄",name = "age",dataType = "int",required = true)
})
@PostMapping("/add")
public Employee add2(String name, int age){
	return new Employee(1L, name, age);
}

image.png

@ApiModel/@ApiModelProperty

@ApiModel:描述一个Model的信息 (这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候) @ApiModelProperty:描述一个model的属性

@ApiModel(value="员工",description="平台注册员工模型")
public class Employee {
    @ApiModelProperty(value="主键",name="id",dataType = "long",required = true)
    private Long id;
    @ApiModelProperty(value="名称",name="name",dataType = "String",required = true)
    private String name;
    @ApiModelProperty(value="年龄",name="age",dataType = "int",required = true)
    private int age;
 
    ....
 
}
@PutMapping
public Employee update(Employee employee){
	employee.setName(employee.getName() +"_update");
	return employee;
}

image.png

@ApiResponses

@ApiResponses:用于表示一组响应 @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息(200相应不写在这里面) code:数字,例如400 message:信息,例如"请求参数没填好" response:抛出的异常类

@ApiResponses({
		@ApiResponse(code=200,message="员工查询成功")
})
@GetMapping("/detail")
public Employee detail(Long id){
	return new Employee(id, "dafei", 18);
}

image.png 好,到这SpringBoot集成Swagger2操作就OK拉