0%

springboot集成swagger

引入依赖

<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>

配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Demo API Doc")
                .description("This is a restful api document of Demo.")
                .version("1.0")
                .build();
    }
}

访问UI

常用注解:

  • @Api()用于类;
    表示标识这个类是swagger的资源
  • @ApiOperation()用于方法;
    表示一个http请求的操作
    - @ApiParam()用于方法,参数,字段说明;
    表示对参数的添加元数据(说明或是否必填等)
    - @ApiModel()用于类
    表示对类进行说明,用于参数用实体类接收
  • @ApiModelProperty()用于方法,字段
    表示对model属性的说明或者数据操作更改
  • @ApiIgnore()用于类,方法,方法参数
    表示这个方法或者类被忽略
  • @ApiImplicitParam() 用于方法
    表示单独的请求参数
  • @ApiImplicitParams()用于方法,包含多个 @ApiImplicitParam

示例

@RestController
@RequestMapping("/xxtest")
@Api(tags = "这里修改大类的名字", description = "这里修改大类的描述")
public class SysRoleController {

    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "请求Header的名称", required = true, dataType = "String",paramType = "header"),
    })
    @ApiOperation(value = "修改接口的描述")
    @PostMapping("/test")
    public Response add(@RequestParam(value = "name") @ApiParam(value = "这里写参数名字") String name) {
        return roleService.add(name);
    }

    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "认证Token", required = true, dataType = "String",paramType = "header"),
        @ApiImplicitParam(name = "name", value = "也可以在这里写参数的名称", dataType = "integer",paramType = "query"),
    })
    @ApiOperation(value = "修改接口的描述")
    @PostMapping("/test")
    public Response add(@RequestParam(value = "name") String name) {
        return roleService.add(name);
    }
}

@ApiModel(description = "测试实体")
public class TestEntity {
    @ApiModelProperty(value = "名称")
    private String name;
    @ApiModelProperty(value = "ID")
    private Integer id;
}