在 spring mvc 项目中更改 swagger 基本路径

change swagger base path in spring mvc project

我已经在我的 Spring MVC 项目中配置了 Swagger。

在 web.xml 中,我已经将 /rest/* 用于 servlet-mapping :

 <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

我可以使用下面的 url 访问 swagger api-doc,一切正常:

http://localhost:8080/rest/v2/api-docs

但是 problem 正在使用 swagger-ul 访问 api。 Swagger 使用 http://localhost:8080/(在我的本地主机中)访问 API.

我尝试创建 swagger.properties 文件来更改基本路径但没有成功。 ('http://www.3pillarglobal.com/insights/restful-api-documentation-using-swagger-and-spring-mvc')

Swagger-ui 在我将 /rest/* 更改为 /* 时工作正常,但由于某些原因我不能这样做。

如何更改 swagger 基本路径以使其正常工作?

如果你的 Swagger 已经在 localhost:8080/rest/ 下工作,我认为你唯一缺少的是你可以打开 swagger-ui index.html 文件,看对于 url 参数并将其更改为任何 url 公开 Swagger 定义的内容:

url = "http://localhost:8080/rest/v2/api-docs/swagger.json";

或者确保每当 swagger-ui index.html 被调用时,它都有这样的东西:

http://localhost:8080/swagger-ui/index.html?url=/rest/v2/api-docs/swagger.json

现在,如果您想更改暴露 Swagger 定义 url 的路径,您可以创建一个从 ApiListingResource 扩展的 class 并覆盖路径,如下所示:

@Path("/rest/v2/api-docs/swagger.{type:json|yaml}")
public class UMSApiListingResource extends ApiListingResource {
}

注意:虽然我使用的是 RestEasy 而不是 Spring MVC,但它应该非常相似。

首先确保您使用的是 springfox 的最新版本(撰写本文时为 2.4.0)。我注意到 link 引用了一个非常旧版本的 springfox。

更新后,您可以使用摘要指定 pathMapping

....
docket.pathMapping("/rest")
...