系列文章目录
第一章 SpringBoot起步
第二章 springboot 配置文件、多环境配置、运行优先级
第三章 springboot 统一日志
第四章 SpringBoot加载静态文件资源
第五章 springboot 拦截器
第六章 实现自定义全局异常处理
第七章 springboot 数据库应用
第八章 springboot 整合Druid
第九章 springboot 整合MyBatis - xml、注解篇
第十一章 整合Mybatis plus
第十二章 SpringBoot整合swagger-bootstrap-ui
文章目录
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/065f17d1a4472a41e3a1f5d56d3a13ae.png)
前言
SpringBoot整合swagger,使用swagger-bootstrap-ui美化页面。
1、环境配置
1.1、导入依赖包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
1.2、在config目录下增加Swagger3Config配置
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
@EnableOpenApi
@Configuration
public class Swagger3Config {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.OAS_30)
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(false)
.pathMapping("/")
.select()
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("Swagger3接口文档")
.description("前后端分离的接口文档")
.version("1.0")
.build();
}
@Bean
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(
List<T> mappings) {
List<T> copy = mappings.stream().filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
}
catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
}
}
1.3、为Swagger3配置ResourceHandlers
含【Swagger3资源配置】、【静态资源配置】
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//加载public文件夹数据
registry.addResourceHandler("/public/**")
.addResourceLocations("classpath:/public/");
//加载static文件夹数据
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
// swagger配置
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
2、应用
2.1、@Api 应用在Controller上
tags :API的展示顺序,例如:1. 2. 3. 4.
@Slf4j
@Api(value = "用户服务", tags = "1.用户模块")
@RestController
@CrossOrigin("*")
@RequestMapping("/user")
public class UserController {
}
@Slf4j
@Api(value = "订单模块", tags = "2.订单模块")
@RestController
@RequestMapping("/order")
public class OrderController {
}
2.2、@ApiOperation 应用在Method上
@ApiOperation(value = "获取订单信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageObj", value = "分页信息", paramType = "query", dataType = "com.hqyj.springbootmybatis.util.PageObj" )
})
@GetMapping("/getOrderList")
public HttpResult getCurrentUserOrderList(PageObj pageObj) {
log.info("当前查询第几页:{} , 一页数据量:{}" , pageObj.getCurrentPage() , pageObj.getPageSize());
List<Order> list = new ArrayList<>();
return HttpResultGenerator.success(list);
}
3、访问
项目路径 + /doc.html : http://localhost/doc.html
4、升级knife4j
Swagger使用起来对raw格式支持不友好,可以直接升级到knife4j,采用knife4j-spring-boot-starter 3.0版本,在Springboot2.7基础上增加knife4j功能。
4.1、环境配置
4.1.1、导入依赖包
<!-- Spring Boot 项目starter,快速使用knife4j增强文档 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
4.1.2、在config目录下增加SwaggerConfig 配置
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
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.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
/**
* Knife4j 3.X 配置类.
* Knife4j 访问首页: http://localhost/doc.html#
* @author Kelvin
* @date 2023-5-21 23:43:39
*/
@EnableKnife4j
@Configuration
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
// 在 Swagger 3.X 以下版本报错时可以加此注解解决,但是在3.X版本以上的,加此注解会导致页面无法打开
//@EnableWebMvc
public class SwaggerConfig {
private static final String SWAGGER_TITLE = "XXX项目 API 接口文档";
private static final String VERSION = "3.0.3";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.enable(true)
// .useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.groupName("3.X 版本")
.select()
// 方式一: 配置扫描 所有想在swagger界面的统一管理接口,都必须在此包下
// .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
// 方式二: 只有当类上有 @RestController 注解时才能生成对应的接口文档
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
// 方式三: 只有当方法上有 @ApiOperation 注解时才能生成对应的接口文档
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(SwaggerConfig.SWAGGER_TITLE)
.description("# XXX项目API接口文档简介")
.termsOfServiceUrl("http://127.0.0.1/#/login")
.contact(new Contact("联系人", "联系人网站", "联系人邮箱"))
.version(SwaggerConfig.VERSION)
.build();
}
@Bean
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> copy = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
assert field != null;
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
}
}
4.1.3、为knife4j配置ResourceHandlers
含【Swagger3资源配置】、【静态资源配置】
如果配置有拦截器,需要把"/doc.html"、“/favicon.ico”、“/swagger-resources/" 、 "/v3/” 、 "/v2/“、”/webjars/"等加入放行链。
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurationSupport {
/**
* 资源映射
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//加载public文件夹数据
registry.addResourceHandler("/public/**")
.addResourceLocations("classpath:/public/");
//加载static文件夹数据
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
// swagger配置
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
* 注册自定义的拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CommonInterceptor()).addPathPatterns("/**")//拦截所有请求
.excludePathPatterns("/","/user/login","*.html","/static/**","/doc.html",
"/favicon.ico","/swagger-resources/**" , "/v3/**" , "/v2/**" , "/webjars/**");//放行的请求;
}
}