当WebMvcConfigurationSupport存在时,不会生成Swagger UI



我正在尝试在我的春季启动项目中生成Swagger UI。JSON API文档生成了,但是Swagger UI没有,至少当我输入Swagger UI地址时,我得到了404。我的依赖关系:

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>

然而,当我删除这个配置(不做任何其他事情):

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Override
protected void addFormatters(FormatterRegistry registry) {
registry.addConverter(new SomeEnumConverter());
registry.addConverter(new AnotherEnumConverter());
}
}

Swagger UI工作了。Swagger UI在转换器方面有问题吗?有解决这个问题的方法吗?

你需要添加@EnableWebMvc注释

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Override
protected void addFormatters(FormatterRegistry registry) {
registry.addConverter(new SomeEnumConverter());
registry.addConverter(new AnotherEnumConverter());
}
}

但是我认为现在配置WebMvc的官方方式是实现WebMvcConfigurer。你可以在官方文档中看到几个例子。我认为它不需要@EnableWebMvc,如果你使用Spring Boot。

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
protected void addFormatters(FormatterRegistry registry) {
registry.addConverter(new SomeEnumConverter());
registry.addConverter(new AnotherEnumConverter());
}
}

对于仍然在寻找这个的人,我使用WebMvcConfigurationSupport而不需要@EnableWebMvc来运行它。我使用的是OpenAPI 3.0,而不是Springfox,有以下依赖项:

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

我最初只得到JSON和UI上的404。

最终工作的是向我的WebConfig添加正确的资源处理程序并配置我的SecurityConfig以允许每个人无限制地访问。

我的WebConfig中的资源处理程序:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/4.10.3/swagger-initializer.js")
.addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/4.10.3/index.html")
.addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/4.10.3/swagger-ui.css")
.addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/4.10.3/index.css")
.addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/4.10.3/swagger-ui-bundle.js")
.addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/4.10.3/swagger-ui-standalone-preset.js");
}

重要的是要专门添加每一个(版本和所有东西,**不起作用)。否则它不会在云端运行。

我还需要添加路径"/v3/api-docs/**", "/swagger-ui/**"我的SecurityConfig允许访问这些资源。在我的例子中,我在这里添加了它们:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.addFilterBefore(...
.authorizeRequests().antMatchers("/v3/api-docs/**", "/swagger-ui/**", "...")...
}

:

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.GET, "/v3/api-docs/**", "/swagger-ui/**", "...");
}

最新更新