spring boot swagger-ui.html 404
阿新 • • 發佈:2018-10-31
很奇怪的問題,找了好久。
因為spring boot+swagger實現起來很簡單。看下面三部曲:
1.pom新增兩個swagger依賴.
<!-- Swagger依賴包 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency> <!-- Swagger end -->
2.新增SwaggerAutoConfiguration.
@Configuration
@EnableSwagger2
public class SwaggerAutoConfiguration{
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.....web"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("**平臺對外介面")
.description("1.提供**後臺使用的介面 2.提供對其他服務呼叫的服務")
.contact(new Contact("xtj332", "https://blog.csdn.net/xtj332", " [email protected]"))
.version("1.0")
.build();
}
}
3.瀏覽器訪問 http://127.0.0.1:8080/swagger-ui.html
但是!竟然返回大大的404!!!
排查過程:
從spring boot官網生成一個簡單的spring-boot-web專案,進行上面三步,不會出現問題。
猜測是自己新增或更改了什麼webmvc之類的東西,比如引入jar包,新增config。
最後發現同事寫了一個跨域的東西:
@Configuration public class WebApiConfig extends WebMvcConfigurationSupport { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH") .allowCredentials(true).maxAge(3600); }
把這個configuration註釋掉就可以了。
原因:
這個自定義的類繼承自WebMvcConfigurationSupport,如果你在IDE中搜索這個類的實現類,可以發現spring boot有一個子類EnableWebMvcConfiguration,並且是自動config的.我們知道,如果一個類使用者自己在容器中生成了bean,spring boot就不會幫你自動config。所以,問題的原因是我們把spring boot自定義的那個bean覆蓋了。
那麼我想既然使用跨域又使用swagger該怎麼辦呢?只需加上下面的程式碼。
@Configuration
public class WebApiConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
.allowCredentials(true).maxAge(3600);
}
延展:
才開始接觸spring boot,感覺是簡化了spring的一些配置,並且幫開發者管理jar包版本。慢慢覺得更強大好用的地方是starter幫你自動生成bean,方便開發者。但是這也帶來了一些惡果,強大的封裝造成有些問題不好排查,想做一些改動引起很大的問題。