快速搭建swagger

在pom中写入如下依赖配置

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>

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

在根目录下新建config文件夹
然后新建配置类Swagger2
@Configuration
@EnableSwagger2
public class Swagger2 {

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("程序的根目录"))
            .paths(PathSelectors.any())
            .build();
}

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("标题")
            .description("详细说明")
            .version("1.0")
            .build();
}

}

在你需要的controller中输入基本的语句

@ApiOperation(value="右边的值:注册", notes="注册用户",tags = "左边大标签",httpMethod = "可以不写 也可以写,如POST")
@ApiResponses(value = {@ApiResponse(code = 200, message = "修改返回参数信息如成功", response = Void.class),
@ApiResponse(code = 400, message = "参数错误", response = Void.class),
@ApiResponse(code = 500, message = "Internal Server Error", response = Void.class)
})

如下:
@RestController
@RequestMapping("/user")
public class RegisterController {

@ApiOperation(value="注册", notes="注册用户",tags = "注册用户",httpMethod = "POST")
@ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Void.class),
        @ApiResponse(code = 400, message = "参数错误", response = Void.class),
        @ApiResponse(code = 500, message = "Internal Server Error", response = Void.class)
})
@PostMapping(value = "/register/{name}")
public String postUser(@PathVariable("name") String name) {
    return "hello"+name;

}

}

Swagger中参数说明

@Api 定义在类上,说明类的作用
@ApiOperation 定义在方法上,说明方法的作用
@ApiParam 定义在参数上,对参数进行设置 如默认值,是否必传等等
@ApiResponses 响应的参数集 包含一个或多个@ApiResponse
@ApiResponse 响应的参数 包含code 以及说明
@ApiModel 对返回类进行标记
@ApiModelProperty 对返回类中的属性进行标记说明
@ResponseHeader 返回头部 一般不常用

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容