常见依赖接入方式如下:
io.springfox springfox-swagger2 3.0.0 io.springfox springfox-swagger-ui 3.0.0
springfox推荐依赖接入方式如下:
io.springfox springfox-boot-starter 3.0.0
建议使用推荐的方式,可以协助我们解决404异常的问题。
配置依赖导入完成后创建SwaggerConfig.java配置:
@Configuration
@EnableSwagger2//启用Swagger2
public class SwaggerConfig {
}
启动项目报错
报错信息:
org.springframework.context.ApplicationContextException: Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException
at ……
Caused by: java.lang.NullPointerException: null
at ……
… 14 common frames omitted
错误原因:SpringBoot2.6.x使用PathPatternMatcher匹配路径,Swagger引用的Springfox基于AntPathMatcher匹配路径。匹配方式不同,导致错误。
解决思路:将SpringBoot的匹配路径方式更改为AntPathMatcher,两者相同即可。添加配置信息如下:
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
重新启动项目成功。
访问默认路径http://localhost:8080/swagger-ui.html 404异常资源无法访问原因:seagger信息被拦截,自定义WebMvcConfigurer解决即可。
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/swagger-ui/").setViewName("/swagger-ui/index.html");
}
}
访问http://localhost:8080/swagger-ui/index.html即可看到页面如下:
如果没有按照springfox推荐的依赖接入方式,会看到如下界面:
该页面为未启用swagger时,访问swagger的结果。swagger的配置在此不多做讨论。



