swagger2文档使用

时光怂恿深爱的人放手 提交于 2019-12-03 15:00:50

①、导入依赖

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>2.2.2</version>

</dependency>

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger-ui</artifactId>

<version>2.2.2</version>

</dependency>

 

②、创建swagger2配置类

@Configuration              //声明配置类
@EnableSwagger2             //开启在线文档
public class SwaggerConfig {
    //1 声明api  文档的属性 构建器
    public ApiInfo apiInfo(){
        return new ApiInfoBuilder().title("swagger2文档生成测试").description("测试使用")
                .termsOfServiceUrl("http://ujiuye.com/").contact("java0708")
                .version("1.0").build();
    }
    //2 配置核心配置信息
    public Docket insertDocket(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage("com.offcn.controller"))
                .paths(PathSelectors.any()).build();
    }
}

 

 

③、修改controller层文档注释

通过

@ApiOperation 注解来给API增加说明  通过 @ApiImplicitParams@ApiImplicitParam 注解来给参数增加说明

 

/**

 * 更新指定id用户信息

 * @param id

 * @param user

 * @return

 */

@PutMapping("/{id}")

@ApiOperation(value="更新指定id用户信息", notes="根据id更新用户信息")

@ApiImplicitParams({

         @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),

         @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")

     })

public String updateUser(@PathVariable("id") Long id,User user) {

user.setId(id);

userRepository.saveAndFlush(user);

return "success";

}

 

/***

 * 删除指定id用户

 * @param id

 * @return

 */

@DeleteMapping("/{id}")

@ApiOperation(value="删除指定id用户信息", notes="根据id删除用户信息")

    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long")

public String deleteUser(@PathVariable("id") Long id) {

 

userRepository.deleteById(id);

return "success";

 

}

④、查看swagger2文档

访问地址:http://localhost:8080/swagger-ui.html 

点开每个接口,可以查看接口详情

 

swagger2注解介绍

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的 等等,如:

@ApiIgnore:使用注解忽略该API,不会参与文档生成

@ApiOperation:描述该api,如: @ApiOperation(value=”创建用户”, notes=”根据User 对象创建用户”)

请求方法:@RequestMapping(value = user, method = RequestMethod.POST)

参数x信息:@ApiImplicitParam(name = user, value = “用户详细实体user, required = true, dataType = User)

@Api:修饰整个类,描述Controller的作用

@ApiParam:单个参数描述

@ApiModel:用对象来接收参数

@ApiResponsesHTTP响应整体描述

@ApiProperty:用对象接收参数时,描述对象的一个字段

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!