以下是如何将 swagger 配置迁移到自定义代码 如果您将微服务托管在 Cloud Foundry 或 IBM Bluemix 或某些 PaaS 云解决方案上,这将特别有用
pom.xml 中的依赖关系
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jersey2-jaxrs</artifactId>
<version>1.5.0</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
招摇配置
package com.ibm.api;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.config.DefaultJaxrsConfig;
public class SwaggerConfigReader extends DefaultJaxrsConfig {
/**
*
*/
private static final long serialVersionUID = 1638783798880874518L;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
//contextPath will be null for host2 and /xyz for host1.
String contextPath = config.getServletContext().getContextPath();
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.0");
beanConfig.setTitle(Result.IMPLEMENTATION + " API Documentation");
beanConfig.setSchemes(new String[] {
"http", "https"
});
beanConfig
.setResourcePackage("com.ibm.api");
beanConfig.setBasePath(contextPath + "/rest");
beanConfig.setScan(true);
}
}
Web.xml 条目
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>io.swagger.jaxrs.listing,com.ibm.api</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SwaggerBootstrap</servlet-name>
<servlet-class>com.ibm.api.SwaggerConfigReader</servlet-class>
<init-param>
<param-name>scan.all.resources</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
</web-app>
请注意com.ibm.api.SwaggerConfigReader
注册为 swagger 配置并com.ibm.api
注册在要扫描其余 API 的包中。另请注意beanConfig.setBasePath(contextPath + "/rest");
现在您的 swagger.JSON 配置将显示为http://localhost:8080/jax_rs/rest/swagger.json
. 将 swagger UI 指向此 URL,您将看到 swagger 文档。
代码在这里:https ://github.com/sanketsw/jax_rs_REST_Example