springboot2.x集成swagger 404 not found的问题
有时候我们参考别人的博客和文章,来实现集成swagger的问题。你看文章的版本太老,所以手贱使用最新版,导致404.参考网上的文章也是无解,最后再springfox官方github找到了原因。
博客使用的2.9.x,我使用最新的3.0.0然后怎么访问都是404,最后发现访问地址的问题。
swagger3.x 的访问地址: http://xxx:8080/swagger-ui/
swagger2.x 的访问地址: http://xxx:8080/swagger-ui.html
最后附录:
swagger2.x 配置
1、在pom.xml 文件
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2、配置SwaggerConfig.java文件
@EnableSwagger2
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//包名
.apis(RequestHandlerSelectors.basePackage("com.xx.demo"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档")
.description("API文档")
.contact(new Contact("无编程", "http://wube.me", "xx@gmail.com"))
.termsOfServiceUrl("http://wube.me")
.version("1.0")
.build();
}
}
3、添加访问资源文件
@Configuration
public class WebConfig implements WebMvcConfigurer {
//其他方法
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
// 解决 SWAGGER 404报错
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
4、访问地址:http://xxx:8080/swagger-ui.html
swagger3.x 配置
1、在pom.xml 文件
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2、添加SwaggerConfig.java文件
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//包名
.apis(RequestHandlerSelectors.basePackage("com.xx.demo"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档")
.description("API文档")
.contact(new Contact("无编程", "http://wube.me", "xx@gmail.com"))
.termsOfServiceUrl("http://wube.me")
.version("1.0")
.build();
}
}
3、访问地址:http://xxx:8080/swagger-ui/
注:
如果使用shiro 或者其他安全框架,记得放行以下资源(以shiro为例 )
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/doc.html/**", "anon");
filterMap.put("/swagger-ui.html/**", "anon");
filterMap.put("/swagger-resources/**", "anon");
filterMap.put("/v2/api-docs/**", "anon");
filterMap.put("/webjars/**", "anon");
filterMap.put("/swagger-resources/configuration/ui/**", "anon");
filterMap.put("/swagger-resources/configuration/security/**", "anon");
shiroFilter.setFilterChainDefinitionMap(filterMap);
网友评论