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

pel*_*osa 13 spring swagger-ui spring-boot openapi springdoc

我正在将 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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序属性:

#swagger-ui config
springdoc.swagger-ui.path=/swagger-ui
springdoc.swagger-ui.operationsSorter=method
springdoc.swagger-ui.tagsSorter=alpha
Run Code Online (Sandbox Code Playgroud)

pom.xml:

<dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.6.13</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

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

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

我开始实施 swagger 的配置,显然它不起作用。

单击查看错误屏幕

pel*_*osa 41

解决。

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

  • 哈哈 - 该链接也给出了 404 - 同上 swagger-ui/index.html :-) (4认同)

小智 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>
Run Code Online (Sandbox Code Playgroud)

注意:这将自动将 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();
    }
Run Code Online (Sandbox Code Playgroud)