使用Spring时,在Swagger UI上收到404错误

4

我正在将Swagger UI与Spring Boot应用程序集成。当我点击swagger-ui.html时,我会收到404错误。我的配置类如下:

@Configuration
@EnableSwagger2
//@Import(SwaggerConfiguration.class)
public class SwaggerConfig  {
    @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
        }
...

错误信息:

{"status":404,"message":"HTTP 404 Not Found","link":"https://jersey.java.net/apidocs/2.8/jersey/javax/ws/rs/NotFoundException.html"}

大家好,请帮个忙。 - user7367999
我认为默认的URL是http://localhost:8080/swagger-ui.html。你能访问http://localhost:8080/swagger-resources吗?或者http://localhost:8080/v2/api-docs? - mh377
7个回答

9

我遇到了一个类似的问题,/swagger-ui.html(或新的端点版本/swagger-ui/)返回404错误,但/v2/api-docs返回有效的json。解决方法是将swagger版本从3.0.0降级到2.9.2。


1
希望这有所帮助,请查看我的工作Swagger配置如下:
@Configuration
@EnableSwagger2
@Profile({"!production"})
public class SwaggerConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private ServletContext servletContext;


    @Bean
    public Docket api() {

        return new Docket(DocumentationType.SWAGGER_2)
                .host("localhost")
                .directModelSubstitute(LocalDate.class, Date.class)
                .pathProvider(new RelativePathProvider(servletContext) {
                    @Override
                    public String getApplicationBasePath() {
                        return "/";
                    }
                })
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

1

我曾经遇到同样的问题,通过将 springfox-swagger2 和 springfox-swagger-ui 依赖项替换为 springfox-boot-starter:3.0.0 并删除 @EnableSwagger2 注释来解决了该问题。请注意,Swagger 的 URL 也从 http://localhost:8080/swagger-ui.html 更改为 http://localhost:8080/swagger-ui/index.html。


1
如果您使用的是版本大于3,则只需使用/swagger-ui/而不是swagger-ui.html

0
请将以下依赖项添加到pom.xml文件中。
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

0

我在使用spring-boot的springfox-boot-starter:3.0.0时,遇到了几乎相似的问题,即Swagger UI为空白,并且查看控制台时会抛出404错误:

http://{ip}:{port}/custom/url/swagger-ui/index.html/swagger-ui-bundle.js?v=3.0.0 net::ERR_ABORTED 404

错误原因是我在文档URL末尾添加了“/”

我原本写的是:

"http://{ip}:{port}/custom/url/swagger-ui/index.html/"

而应该写:

"http://{ip}:{port}/custom/url/swagger-ui/index.html"

请注意末尾的“/”。

0
你的配置类中是否有 @EnableWebMvc?如果是,你将需要手动进行资源配置,如下所示:
@Override
public void addResourceHandlers (ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/swagger-ui.html**")
            .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
    registry.
            addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接