【问题标题】:What is the correct way of integrating Swagger2 with Spring MVC?将 Swagger2 与 Spring MVC 集成的正确方法是什么?
【发布时间】:2018-10-28 13:21:01
【问题描述】:

用 Spring MVC 而不是 spring boot 配置 Swagger2 的正确方法是什么。

目前我添加了以下组件

Maven Dependency
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.7.0</version>
    </dependency>
    <!--Dependency for swagger ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
    </dependency>

在调度程序 servlet 上下文中

<bean id="swagger2Config" class="springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration"/>

<mvc:resources location="/resources/" mapping="/resources/**"
    order="1" />
<mvc:resources location="classpath:/META-INF/resources/"  mapping="swagger-ui.html" />
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"  />

<mvc:default-servlet-handler />

并添加了配置

@EnableSwagger2
public class SwaggerConfiguration 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/");
}

}

当我尝试启动应用程序时,我的应用程序上下文是示例

http://localhost:8080/sample/swagger-ui.html, 

我遇到了错误

Unable to infer base url. This is common when using dynamic servlet 
registration or when the API is behind an API Gateway. The base url is the 
root of where all the swagger resources are served. For e.g. if the api is 
available at http://example.org/api/v2/api-docs then the base url is 
http://example.org/api/. Please enter the location manually: 

如果我尝试过 http://localhost:8080/sample/v2/api-docs/

我遇到了异常

Handler processing failed; nested exception is java.lang.NoSuchMethodError
on org.springframework.web.util.UriComponentsBuilder.fromHttpRequest

我是否还遗漏了其他任何东西以使其正常工作。

顺便说一句,我使用的是 Spring 3.2.9 和 Servlet API 2.5

谢谢大家

【问题讨论】:

    标签: spring-mvc swagger swagger-ui


    【解决方案1】:

    您的@EnableSwagger2 注释似乎在启动期间没有被扫描。尝试在您的调度程序 servlet xml 文件中使用组件扫描。像下面这样,

    <context:component-scan base-package="your.package.name" />
    

    传递 SwaggerConfiguration 类所在的包。这应该可以解决问题。

    【讨论】:

    【解决方案2】:

    实际上基于stackoverflow.com/questions/33518672/...和github.com/springfox/springfox/blob/v1.0.2/README.md,Spring 3.x 与 Swagger 2 不兼容。所以我最终使用Swagger 1. 我正在遵循 github.com/martypitt/swagger-springmvc-example 中给出的示例。成功集成 Swagger 1 后,我会更新

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      相关资源
      最近更新 更多