【问题标题】:Swagger2 + Spring REST API not workingSwagger2 + Spring REST API 不起作用
【发布时间】:2016-03-27 00:34:23
【问题描述】:

我有一个 Spring Rest 控制器和它的 NOT spring boot 应用程序。它只是一个 REST API 项目。我想将 swagger2 集成到我的项目中。我尝试了 Net 和演示中的所有示例,但没有运气。当我尝试执行 http://localhost:8085/context/swagger-ui.html 时,出现 404 错误。请在下面找到我的配置,如果有任何差异,请告诉我。非常感谢任何帮助。

jars - 在 /WEB-INF/lib 下

google-collections-1.0.jar springfox-core-2.2.2.jar springfox-schema-2.2.2.jar springfox-spi-2.2.2.jar springfox-spring-web-2.2.2.jar springfox-staticdocs-2.2.2.jar springfox-swagger-common-2.2.2.jar springfox-swagger-ui-2.2.2.jar springfox-swagger2-2.2.2.jar

我的招摇配置类 -

@EnableSwagger2
public class SwaggerConfiguration {

}

我的 springconfig 类

@EnableWebMvc
@ComponentScan(basePackageClasses = controller.class)
@Import(SwaggerConfiguration.class)
public class SpringConfiguration extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}

根据 springfox-java 演示,下面的我的应用程序初始化程序类。我尝试了使用和不使用以下课程,但无论哪种方式都不起作用。

Application Initializer class

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class[]{controller.class};
}

@Override
protected String[] getServletMappings() {
    return new String[]{"/*"};
}
}

我可以访问我的其余网址,但不能在同一上下文中访问 swagger-ui.html。

请让我知道我在这里缺少什么?

【问题讨论】:

  • 您能在启动日志中看到类似的内容吗:将“{[/swagger-resources/configuration/ui]}”映射到 org.springframework.http.ResponseEntity

标签: java spring swagger-2.0 springfox


【解决方案1】:

我添加了手动选择控制器:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("my.package.to.api"))
                .paths(regex("/product.*")) //optional 
                .build();

    }
}

【讨论】:

    【解决方案2】:

    给出的细节不足以重现/分析问题。

    但是,今天我遇到了类似的问题,当然使用了SpringBoot,并解决了自己如下: 由于我的示例有一个控制器类和一个具有 main 方法的应用程序类,我创建了如下包,它得到了解决:

    • 你好
      • 控制器
        • HelloController
      • 大摇大摆
        • SwaggerConfig2
      • HelloApplication

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 2015-11-08
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多