【发布时间】:2016-11-25 09:50:05
【问题描述】:
毋庸置疑,我知道有很多关于同一主题的问题,但我已经坚持尝试解决这个问题 2 天了,而且我读过的大部分内容都已经过时了。
所以是的..这就是我现在所拥有的:
分级:
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 工作)。
有很多这样的教程,他们声称上面的东西会让 swagger-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
还有大量其他教程,它们会指导您将 dist 文件夹从 swagger-ui git 添加到您的项目中。
也像这样映射:
@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/");
}
}
同样失败,抛出 Scope 'request' 对当前线程无效;例外。
在尝试了一些来自 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 的,所以你的 webapp 中不需要手动安装 html 或 css 文件。
-
感谢您的帮助。陷入同样的问题。
标签: java spring swagger-ui swagger-2.0 springfox