🧑🎓 个人主页:Silence Lamb
📖 本章内容:【文档管理-Swagger配置】
swagger使用ant_pattern_parser解析路径,但是spring boot在2.6之后(好现实2.6),修改为了path_pattern_parser。所以为了能使swagger正常使用,需要配置如下。
application.yaml
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
1️⃣引入依赖
<!-- swagger3-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
</dependency>
<!-- 防止进入swagger页面报类型转换错误,排除3.0.0中的引用,手动增加1.6.2版本 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.6</version>
</dependency>
2️⃣配置信息
# Swagger配置
swagger:
# 是否开启swagger
enabled: true
# 请求前缀
pathMapping: /dev-api
# 分组
group: Silence-Admin
# 标题
title: 管理系统
# 描述
description: 管理系统
# 网址
url: 博客网址
# 邮箱
email: 邮箱
3️⃣读取配置信息类
@Data
@Component
@ConfigurationProperties(prefix = "swagger")
public class SwaggerProperties {
@ApiModelProperty("是否开启swagger")
private String enabled;
@ApiModelProperty("请求前缀")
private String pathMapping;
@ApiModelProperty("标题")
private String title;
@ApiModelProperty("分组")
private String group;
@ApiModelProperty("描述")
private String description;
@ApiModelProperty("网址")
private String url;
@ApiModelProperty("邮箱")
private String email;
}
4️⃣Swagger配置类
/**
* @author SilenceLamb
* @apiNote swagger文档配置
*/
@Configuration
@EnableWebMvc
public class SwaggerConfig {
@Resource
private SwaggerProperties swaggerProperties;
@Bean
public Docket restApi() {
return new Docket(DocumentationType.OAS_30)
//是否开启swagger
.enable(Boolean.parseBoolean(swaggerProperties.getEnabled()))
//分组
.groupName(swaggerProperties.getGroup())
.apiInfo(apiInfo())
//使用默认响应消息
.useDefaultResponseMessages(true)
//用于代码生成
.forCodeGeneration(false)
.select()
//包路径指定哪些controller使用swagger
.apis(RequestHandlerSelectors.basePackage("com.silence.admin.controller"))
//所有路径都是用
.paths(PathSelectors.any())
.build()
//设置安全模式,swagger可以设置访问token
.securitySchemes(securitySchemes())
//安全上下文
.securityContexts(securityContexts())
//设置请求前缀
.pathMapping(swaggerProperties.getPathMapping());
}
/**
* 安全模式,这里指定token通过Authorization头请求头传递
*/
private List<SecurityScheme> securitySchemes() {
List<SecurityScheme> apiKeyList = new ArrayList<>();
apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
return apiKeyList;
}
/**
* 安全上下文
*/
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.operationSelector(o -> o.requestMappingPattern().matches("/.*"))
.build());
return securityContexts;
}
/**
* 默认的安全上引用
*/
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://ip:port/swagger-ui.html
*
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//设置网页标题
.title(swaggerProperties.getTitle())
//设置描述信息
.description(swaggerProperties.getDescription())
//设置作者信息
.contact(new Contact("作者:SilenceLamb", "博客地址:"+swaggerProperties.getUrl(), "邮箱地址:"+swaggerProperties.getEmail()))
//设置版本号
.version("版本" + "1.0.0")
.build();
}
}
- 拦截规则配置
/**
* @author Michale
* @apiNote 通用拦截规则配置
*/
@SuppressWarnings("all")
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
/**
* 放行静态资源
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/** swagger配置 */
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
/**knife4j配置**/
registry.addResourceHandler("/doc.html/*")
.addResourceLocations("classpath:/META-INF/resources/webjars");
}
/**
* 跨域配置
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// 设置访问源地址
config.addAllowedOriginPattern("*");
// 设置访问源请求头
config.addAllowedHeader("*");
// 设置访问源请求方法
config.addAllowedMethod("*");
// 有效期 1800秒
config.setMaxAge(1800L);
// 添加映射路径,拦截一切请求
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
// 返回新的CorsFilter
return new CorsFilter(source);
}
}
- 报错:documentationPluginsBootstrapper
解决办法:在启动类加一个注解:@EnableWebMvc
5️⃣API详细说明
- 控制层
@ApiOperation(value = "分页课程列表")
@GetMapping("{page}/{limit}")
public AjaxResult pageQuery(
@ApiParam(name = "page", value = "当前页码", required = true) @PathVariable Long page,
@ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable Long limit) {
System.out.println("当前页码" + page);
System.out.println("每页记录数" + limit);
return AjaxResult.success("当前页码" + page,"每页记录数" + limit);
}
- 实体类
@ApiModel(value="EduChapter对象", description="课程")
public class EduChapter implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "章节ID")
@TableId(value = "id", type = IdType.ID_WORKER_STR)
private String id;
@ApiModelProperty(value = "课程ID")
private String courseId;
@ApiModelProperty(value = "章节名称")
private String title;
@ApiModelProperty(value = "显示排序")
private Integer sort;
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
}