问题
Following the instructions here:
http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
I added these dependencies to my project:
compile "io.springfox:springfox-swagger2:2.7.0"
compile "io.springfox:springfox-swagger-ui:2.7.0"
and configured SpringFox Swagger like this:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
but the Swagger UI seems not to get enabled. I tried:
- http://localhost:8080/swagger-ui.html
- http://localhost:8080/api/swagger-ui.html
- http://localhost:8080/v2/api-docs/swagger-ui.html
and all I get is:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Sep 11 09:43:46 BST 2017
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
and on the logs I see:
2017-09-11 09:54:31.020 WARN 15688 --- [nio-8080-exec-6] o.s.web.servlet.PageNotFound : Request method 'GET' not supported
2017-09-11 09:54:31.020 WARN 15688 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
http://localhost:8080/swagger-resources returns:
[{"name": "default",
"location": "/v2/api-docs",
"swaggerVersion": "2.0"}]
What am I missing?
回答1:
I ran into this issue because I had endpoints with request mappings that had path variables of this form: /{var}. Turns out that this is an issue for both GET and POST endpoints i.e. GET /{var} and POST /{var} block swagger-ui. Once I made the paths more specific, I got swagger-ui to work.
Quote from https://github.com/springfox/springfox/issues/1672
When spring finds a simple path with just one variable swagger cannot intercept the URLs.
Found by investigating various ideas in comments.
回答2:
I also ran into this and the issue was that we had a controller without path mapping (thus mapping to "/"). That was blocking the requests to the swagger-ui resources.
回答3:
Adding @RequestMapping("/")
in controller level(after @RestController\@Controller
annotation) helps me to get rid of the Request method 'GET' not supported
issue. Thanks to Dhermanns's suggestion
回答4:
Add @RequestMapping("/")
at the controller level, It works.
来源:https://stackoverflow.com/questions/46151540/added-springfox-swagger-ui-and-its-not-working-what-am-i-missing