Lison <cundream@163.com>, v1.0.0, 2019.10.13
Swagger2是一款RESTFUL接口的文档在线自动生成和功能测试功能软件 Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单 。
修改pom.添加依赖:
<io.springfox.swagger.version>2.8.0</io.springfox.swagger.version> <!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${io.springfox.swagger.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${io.springfox.swagger.version}</version> </dependency> <!-- <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.0</version> </dependency>-->添加配置类
/** * @author : Lison * @Date: 2019/10/16 15:08 * @Description: */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2) .useDefaultResponseMessages(false) .select() .apis(RequestHandlerSelectors.basePackage("com.github.cundream")) .paths(PathSelectors.regex("(?!auth).*$")) .build() .securityContexts(securityContexts()); } private List<SecurityContext> securityContexts() { return Lists.newArrayList( SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("^(?!auth).*$")) .build() ); } private List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope}; SecurityReference securityReference = new SecurityReference("X-Authorization", authorizationScopes); return Lists.newArrayList(securityReference); } private ApiInfo getApiInfo(){ return new ApiInfoBuilder() .title("API接口文档") .description("swagger2 api") .termsOfServiceUrl("http://localhost/swagger-ui.html") .version("1.0") .contact(new Contact("Lison", "http://localhost/swagger-ui.html", "cundream@163.com")) .build(); } } .apis(RequestHandlerSelectors.basePackage("com.github.cundream")) 会将包下的所有被@Api标记的类带有@RequestMapping或者XxxMapping都会给暴露给swagger .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) 只有在类上使用@Api注解标注并且在方法上使用@ApiOperation注解才会暴露给swagger,这种方式没有包名的限制,可以将需要暴露的接口分散到各个包里,只要类上有@Api注解方法上有@ApiOperation注解就能暴露出来,如果不想暴露出来就不用使用这两个注解@Api用来标识Class
@ApiOperation(value = "获取用户信息", notes = "获取用户信息") @ApiResponses({ @ApiResponse(code = 200, message = "success"), @ApiResponse(code = 10001, message = "secret_key与token不符合"), @ApiResponse(code = 10002, message = "获取用户信息错误", response = Exception.class) }) @PostMapping("/getUserinfo") public String getUsesrInfo(@ApiParam(name = "secret_key", value = "秘钥", required = true) @RequestParam String secret_key, @ApiParam(name = "token", value = "token", required = true) @RequestParam String token, @ApiParam(name = "type", value = "用户类型", required = true) @RequestParam String type){ return "{'type': " + type + ", 'url': 'rtmp://localhost/user', 'urlHD': 'rtmp://localhost/hd/user'}"; }@ApiOperation(value = “接口方法的名称”, notes = “备注说明”) @ApiParam(name = “参数名称”, value = “备注说明”, required = 是否必须):标注在方法的参数上 用于描述参数的名称、备注、是否必须等信息 @ApiImplicitParams: 用于包含多个@ApiImplicitParam @ApiResponse(code = 0, message = “success”),
code:响应码,例如400message:信息,一般是对code的描述response:抛出异常的类 @ApiOperation(value = "修改用户信息", notes = "修改用户信息") @ApiImplicitParams({ @ApiImplicitParam(dataTypeClass = String.class, paramType = "header", name = "id", value = "id标识", required = true), @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "userName", value = "登陆名", required = true), @ApiImplicitParam(dataTypeClass = String.class, paramType = "path", name = "passWord", value = "密码", required = true), @ApiImplicitParam(dataTypeClass = String.class, paramType = "body", name = "realName", value = "名字", required = true) }) @PutMapping("/updateUserInfo") public String updateUser(@RequestHeader String id, @RequestParam String userName, @PathVariable String passWord, @RequestBody String realName){ return "{'id': " + id + ", 'userName':" + userName + ", 'passWord':" + passWord + ", 'realName':" + realName +"}"; }@ApiImplicitParam用于描述方法的参数,标注在方法上,和@ApiParam功能一样,只是标注的位置不同而已
paramType:参数类型,即参数放在哪个地方 header–>请求参数的获取:@RequestHeader,参数放在请求头query–>请求参数的获取:@RequestParam,参数追加在url后面path(用于restful接口)–>请求参数的获取:@PathVariablebody 使用@RequestBody接收数据 POST有效,参数放在请求体中 name:参数名dataType:参数的数据类型required:参数是否必须传value:参数的描述defaultValue:参数的默认值 @ApiImplicitParams: 用于包含多个@ApiImplicitParam @ApiModelProperty(value = "当前页", required = true) private Integer page; @ApiModelProperty(value = "每页记录数", required = true) private Integer pageSize;@ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候) @ApiModelProperty:描述一个model的属性
value 参数名称required 是否必须 booleanhidden 是否隐藏 boolean@ApiIgnore:用于或略该接口,不生成该接口的文档
启动项目后访问http://localhost:8082/bootbuliding/swagger-ui.html
集成第三方的 swagger 来替换原生的 swagger,美化文档样式
pom.xml
去除原有的swagger依赖更换为如下配置
<dependency> <groupId>com.battcn</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>${battcn.swagger.version}</version> </dependency>application.yml
spring: swagger: #是否开启 enabled: true title: SpringBootBuilding系统构建 description: 这是一个描述 version: 1.0.0-SNAPSHOT contact: name: Lison email: cundream@163.com # swagger扫描的基础包,默认:全扫描 #base-package: #需要处理的基础URL规则,默认:/** #base-path: #需要排除的URL规则,默认:空 #exclude-path: security: filter-plugin: true username: Lison password: 123456 #是否启用 swagger登陆验证 global-response-messages: GET[0]: code: 400 message: Bad Request,一般为请求参数不对 GET[1]: code: 404 message: NOT FOUND,一般为请求路径不对 GET[2]: code: 500 message: ERROR,一般为程序内部错误 POST[0]: code: 400 message: Bad Request,一般为请求参数不对 POST[1]: code: 404 message: NOT FOUND,一般为请求路径不对 POST[2]: code: 500 message: ERROR,一般为程序内部错误项目GitHub地址