不用說我知道關於這個主題有很多問題,但我一直在試圖解決這個問題2天,現在我閱讀的大部分內容都已經過時。Spring Swagger-ui integration
所以啊..這就是我現在所擁有的:
搖籃:
dependencies {
compile 'org.springframework.cloud:spring-cloud-starter-hystrix'
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-actuator'
compile 'org.springframework.boot:spring-boot-starter-security'
compile 'org.springframework.ws:spring-ws-core'
compile 'io.springfox:springfox-swagger2:2.4.0'
compile 'io.springfox:springfox-swagger-ui:2.4.0'
}
主要類:
@EnableSwagger2
public class Application {
public static void main(String[] args) {
SpringApplication.run(FeedServiceApplication.class, args);
}
@Bean
public Docket swaggerSettings() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/");
}
當我訪問:http://localhost:8080/v2/api-docs,我得到的JSON文件正好。另外,當我從github下載swagger-ui時,將源設置爲上面的鏈接並在桌面上運行它,它也可以正常工作。不起作用的是把這兩樣東西放在一起(讓它在http://localhost:8080/swagger-ui.html工作)。
有很多教程,如這些,他們要求上述的東西會讓招搖的UI工作:
http://kubecloud.io/guide-using-swagger-for-documenting-your-spring-boot-rest-api/
http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
一噸,他們要你去其他教程從swagger-ui git添加dist文件夾到您的項目中。
此外映射是這樣的:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("**/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("**/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
失敗,那麼投擲範圍「請求」不是當前線程活性;例外。
在嘗試了一些來自YouTube的教程之後,上面鏈接了很多教程,我看過的所有內容都是「找不到頁面」。如果有人能解釋我錯過了什麼,我會非常感激。
TL:DR如何讓swagger-ui.html工作?
編輯:找到了解決方案。
如果有人遇到這種情況,問題是如果你有一個請求參數爲@RequestMapping("/{param}")
的請求映射,那麼dispatcherServlet不再將/ **映射到ResourceHttpRequestHandler。下面的代碼解決了這個問題。
@Configuration
@EnableAutoConfiguration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter{
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build();
}
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
你必須使用的swagger-ui是由springfox提供的那個,它使用webjar,因此沒有html或css文件可以手動安裝到你的webapp中。 –
感謝您的幫助。陷入了同樣的問題。 –