整合swagger、knife4j
1.导入pom依赖
<properties> <!-- 版本统一管理--> <!--Swagger Resources--> <knife4j.version>2.0.4</knife4j.version> <springfox.version>2.9.2</springfox.version> <swagger.version>1.6.1</swagger.version> </properties> <dependencyManagement> <dependencies> <!--knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案--> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>${knife4j.version}</version> </dependency> <!--API开发框架--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox.version}</version> <exclusions> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>${swagger.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-bean-validators</artifactId> <version>${springfox.version}</version> </dependency> </dependencies> </dependencyManagement>
2. Swagger代码配置类
package com.config; import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; import com.google.common.collect.Lists; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.annotation.Order; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.List; /** * @Author: 马家立 * @Date: 2020/12/25 10:44 * @Description: Swagger配置 */ @Configuration @EnableSwagger2 @EnableKnife4j @Import(BeanValidatorPluginsConfiguration.class) public class SwaggerConfiguration { @Bean(value = "userApi") @Order(value = 1) public Docket groupRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(getApiInfo()) .useDefaultResponseMessages(false) .select() .apis(RequestHandlerSelectors.basePackage("com.controller")) .paths(PathSelectors.any()) .build().securityContexts(getSecurityContexts()).securitySchemes(getSecuritySchemes()); } /** * @Author: 马家立 * @Date: 2020/12/25 10:24 * @Description: API详情配置 */ private ApiInfo getApiInfo() { return new ApiInfoBuilder() .title("基于springcloud的接口文档") .description("<div style='font-size:14px;color:red;'>knife4j swagger RESTful APIs</div>") .termsOfServiceUrl("http://127.0.0.1/") .version("1.0") .build(); } /** * @Author: 马家立 * @Date: 2020/12/25 10:33 * @Description: 安全上下文。即存储认证授权的相关信息,实际上就是存储"当前用户"账号信息和相关权限 */ private List<SecurityContext> getSecurityContexts() { return Lists.newArrayList(securityContext(), securityContext1()); } /** * @Author: 马家立 * @Date: 2020/12/25 10:33 * @Description: 安全上下文。即存储认证授权的相关信息,实际上就是存储"当前用户"账号信息和相关权限 */ private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("/.*")) .build(); } /** * @Author: 马家立 * @Date: 2020/12/25 10:33 * @Description: 安全上下文1。即存储认证授权的相关信息,实际上就是存储"当前用户"账号信息和相关权限 */ private SecurityContext securityContext1() { return SecurityContext.builder() .securityReferences(defaultAuth1()) .forPaths(PathSelectors.regex("/.*")) .build(); } /** * @Author: 马家立 * @Date: 2020/12/25 10:34 * @Description: 安全引用 */ List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; return Lists.newArrayList(new SecurityReference("BearerToken", authorizationScopes)); } /** * @Author: 马家立 * @Date: 2020/12/25 10:34 * @Description: 安全引用1 */ List<SecurityReference> defaultAuth1() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; return Lists.newArrayList(new SecurityReference("BearerToken1", authorizationScopes)); } /** * @Author: 马家立 * @Date: 2020/12/25 10:37 * @Description: 描述API如何保护(基本认证,OAuth2,...)。 */ private ArrayList<SecurityScheme> getSecuritySchemes() { ApiKey apiKey = new ApiKey("BearerToken", "Authorization", "header"); ApiKey apiKey1 = new ApiKey("BearerToken1", "Authorization-x", "header"); return Lists.<SecurityScheme>newArrayList(apiKey, apiKey1); } }
3.具体使用
import cn.hutool.json.JSONObject; import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; import com.github.xiaoymin.knife4j.annotations.ApiSort; import com.github.xiaoymin.knife4j.annotations.DynamicParameter; import com.github.xiaoymin.knife4j.annotations.DynamicResponseParameters;import com.pojo.exam.UserRecentExam; import io.swagger.annotations.*; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Author: 马家立 * @Date: 2020/10/19 14:02 */ @ApiSort(14) @RestController @RequestMapping("/userExam") @Api(tags = "用户考试模块") public class TUserExamController { @ApiOperation(value = "考试历史记录") @ApiResponses(value = { @ApiResponse(code = 200, message = "成功") , @ApiResponse(code = 400, message = "失败") , @ApiResponse(code = 500, message = "服务器出错")}) @ApiOperationSupport(order = 1, responses = @DynamicResponseParameters(properties = { @DynamicParameter(value = "响应码", name = "code"), @DynamicParameter(value = "描述", name = "message"), @DynamicParameter(value = "返回结果", name = "data", dataTypeClass = UserRecentExam.class)// 配置返回结果类 })) @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Long") @PostMapping("/recentExamAndHistory") public ReturnData<Object> recentExamAndHistory(@ApiParam(hidden = true) @RequestBody JSONObject param) throws Exception { Long userId = param.getLong("userId"); /** * 考试历史记录 */ return null; } }
配置返回结果类
import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @Author: 马家立 * @Date: 2020/10/20 10:14 * @Description: TODO 考试历史记录 */ @Data public class UserRecentExam { @ApiModelProperty(value = "考试试卷名称") private String examName; @ApiModelProperty(value = "平均时间") private double avgTime; @ApiModelProperty(value = "总分数") private double totalScore; @ApiModelProperty(value = "平均分") private Long avgScore; @ApiModelProperty(value = "合格率") private Double passRate; }