使用 Spring 的 Swagger UI 出现 404 错误(springdoc-openapi 配置)

问题描述 投票:0回答:4

我正在将 swagger UI 添加到我的 Spring boot 应用程序中。当我尝试访问 swagger-ui.html 时。我收到 404 错误。

配置类:

@Configuration
public class SwaggerConfig {

    @Bean
    public OpenAPI springShopOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("JOYAS-STOCK API Docs")
                        .description("JOYAS-STOCK REST API documentation")
                        .version("v1.0.0"));
    }
}

应用程序属性:

#swagger-ui config
springdoc.swagger-ui.path=/swagger-ui
springdoc.swagger-ui.operationsSorter=method
springdoc.swagger-ui.tagsSorter=alpha

pom.xml:

<dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.6.13</version>
</dependency>

错误信息: 白标错误页面 此应用程序没有 /error 的显式映射,因此您将其视为后备。

发生意外错误(类型=未找到,状态=404)。

我先从swagger的配置开始执行 显然它不起作用。

click to see screen of the error

spring spring-boot swagger-ui openapi springdoc
4个回答
41
投票

已解决。

问题出在版本上,它们不兼容!我正在使用 springdoc-openapi v1 和 spring boot 3。 这是错误的!对于 Spring Boot 3,应使用 springdoc-openapi v2。 请参阅文档:https://springdoc.org/v2/


11
投票

使用 Spring Boot 3,您需要使用 springdoc-openapi v2。
对于 spring-boot 和 swagger-ui 之间的集成,请将库添加到您的项目依赖项列表中(无需额外配置)

<dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>2.0.4</version>
   </dependency>

注意:这将自动将 swagger-ui 部署到 spring-boot。

如果你使用 Spring Security 并希望在不进行安全检查的情况下访问 swagger UI (

/swagger-ui/index.htm
)

private static final String[] AUTH_WHITELIST = {
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**",
            "/v3/api-docs/**",
            "/api/public/**",
            "/api/public/authenticate",
            "/actuator/*",
            "/swagger-ui/**"
    };
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> authorize
                        .requestMatchers(AUTH_WHITELIST).permitAll()
                        .anyRequest().authenticated()
                )
                .httpBasic(withDefaults());
        return http.build();
    }

0
投票

我遇到了与加载 Swagger 配置文件相关的问题。如果您检查浏览器的控制台,您可能会看到类似于以下内容的错误消息:

Failed to load resource: the server responded with a status of 403 ()
spec-actions.js:19 undefined /api-docs/swagger-config
i @ spec-actions.js:19

问题在于 application.yml 文件中定义的配置如下:

springdoc:
  api-docs:
    path: /api-docs
  swagger-ui:
    path: /swagger-ui.html

要解决此问题,需要允许 /api-docs/** URL。


0
投票

我添加了以下链接[https://springdoc.org/][1]中出现的依赖项,错误已解决。

© www.soinside.com 2019 - 2024. All rights reserved.