sprintboot 和swagger2整合生成文档

时间:2022-05-10 11:46:52

1、创建springboot 工程

2、引入maven依赖

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

  3、创建配置文件

sprintboot 和swagger2整合生成文档

配置文件内容如下:

package com.yyj.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration
@EnableSwagger2
public class Swagger2 {
//swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage("com.yyj.demo.controller"))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("Spring Boot 测试使用 Swagger2 构建RESTful API")
//创建人
.contact(new Contact("MarryFeng", "http://www.baidu.com", ""))
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
} }

  

4、编写测试类

@Api( tags = {"用户相关接口"})
@RestController
@RequestMapping("/user")
public class UserController { @ApiOperation(value="创建用户")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@PostMapping("/upateUser")
public UUNotify upateUser(@RequestBody User user){
System.out.println(user); return new UUNotify();
}
}

  

entity实体类

package com.yyj.demo.entity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data; public class User {
@ApiModelProperty(value = "用户id", required = false)
private Integer id;
private String name; }

  get set方法自己生成,我本机用的lombok,所以他能自动生成

5、启动工程访问页面

http://localhost:8080/swagger-ui.html

sprintboot 和swagger2整合生成文档