SpringBoot整合Swagger踩坑-項目啟動報錯與swagger-ui請求404無法訪問
項目依賴與配置
依賴
常見依賴接入方式如下:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
springfox推薦依賴接入方式如下:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
建議使用推薦的方式,可以協(xié)助我們解決404異常的問題。
配置
依賴導(dǎo)入完成后創(chuàng)建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匹配路徑。匹配方式不同,導(dǎo)致錯誤。
解決思路:將SpringBoot的匹配路徑方式更改為AntPathMatcher,兩者相同即可。添加配置信息如下:
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
重新啟動項目成功。
訪問默認路徑http://localhost:8080/swagger-ui.html 404異常
資源無法訪問原因:seagger信息被攔截,自定義WebMvcConfigurer解決即可。文章來源:http://www.zghlxwxcb.cn/news/detail-429852.html
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 添加靜態(tài)資源處理器
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/").resourceChain(false);
}
/**
* 添加視圖控制器
* @param registry
*/
@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的結(jié)果。swagger的配置在此不多做討論。文章來源地址http://www.zghlxwxcb.cn/news/detail-429852.html
到了這里,關(guān)于SpringBoot整合Swagger踩坑-項目啟動報錯與swagger-ui.html請求404無法訪問的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!