v2版本
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
jar包结构
默认情况下就是访问静态资源
http://localhost:8080/swagger-ui.html
假设要打开js则地址是
http://localhost:8084/webjars/springfox-swagger-ui/springfox.js(包的层级不一样, idea中的截图不明显)
===============================================================
v3版本
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-core</artifactId>
<version>1.1.49</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.1.45</version>
</dependency>
查看ui包中源码
SwaggerConfig.java 中配置了静态资源的访问

SwaggerWelcome.java 中配置了url重定向
DEFAULT_SWAGGER_UI_PATH的值是

所以 v3版本用地址
http://localhost:8080/swagger-ui.html
其实是自动重定向到
http://localhost:8080/swagger-ui/index.html
项目里面的 接口json数据则是从OpenApiResource.java 中获取的


===============================================================
在接手一个老系统时想添加 swagger-ui 发现访问 http://localhost:8080/swagger-ui.html 一直报错
javax.servlet.ServletException: Could not resolve view with name 'redirect:/swagger-ui/index.html?url=/v3/api-docs&validatorUrl=' in servlet with name 'dispatcherServlet'
错误提示的是没有视图
如果直接访问http://localhost:8080/swagger-ui/index.html 则正常
最终定位到是老系统中有配置了 WebMvcConfigurationSupport 这个配置类会让 springMvc的自动装配类失效 WebMvcAutoConfiguration
所以有3种解决方案:
1.实现WebMvcConfigurer接口, 把原本继承WebMvcConfigurationSupport的代码, 调整下即可
2.用一个新的项目去启动 swagger-ui, 把老系统的 http://项目地址:端口/v3/api-docs 地址填进去
3.如果不想多启动1个项目, 且不需要原系统WebMvcConfigurationSupport中的配置时, 则可以覆盖掉原有的WebMvcConfigurationSupport
/**
* WebMvcConfigurationSupport 只能存在一个, 当前的会覆盖其他的
*
*/
@Configuration
public class WebMvcConfigOverride extends WebMvcConfigurationSupport {
@Bean
public InternalResourceViewResolver viewResolver(){
return new InternalResourceViewResolver();// 用于解析重定向 redirect:
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("/webjars/").resourceChain(false);
}
}
参考
继承WebMvcConfigurationSupport后自动配置不生效的问题及如何配置拦截器_fmwind的博客-CSDN博客_webmvcconfigurationsupport
WebMvcConfigurerAdapter已过时,使用WebMvcConfigurationSupport或者WebMvcConfigurer来代替 - 就这个名字好 - 博客园
本文详细介绍了在Spring Boot项目中集成Swagger UI的不同版本方法,并针对v3版本在老系统中出现的访问错误提供了三种可行的解决方案。
1415

被折叠的 条评论
为什么被折叠?



