1 建立基本SpringMVC工程
1.1 建立SpringMVC Maven工程
web.xml
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>Servlet Context</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<!-- 攔截所有請求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
1.2 創建一個TestController
package com.study.swagger.control;
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(value="/hello", method=RequestMethod.GET)
@ResponseBody
public String sayHello(String name){
return "hello " + name;
}
}
1.3 配置spring bean
applicatonContext.xml
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.study.swagger.control" />
確保該Controller能夠正常訪問:
2 引入Swagger2
2.1 引入Swagger2依賴
<!-- Swagger2 Dependency -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
2.2 新增Swagger配置類
package com.study.swagger.config;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket swaggerSpringMvcPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Impler Apis")
.description("Impler Apis details")
.license("copyright?impler.cn")
.version("1.0")
.build();
}
}
2.3 配置swagger bean
<context:component-scan base-package="com.study.swagger.config" />
2.4 添加@ApiOperation注解
在Controller Bean中的@RequestMapping標識的方法上添加@ApiOperation注解。
package com.study.swagger.control;
@Controller
@RequestMapping("/test")
public class TestController {
@ApiOperation(value = "sayHello")
@RequestMapping(value="/hello", method=RequestMethod.GET)
@ResponseBody
public String sayHello(String name){
return "hello " + name;
}
}
2.5 部署啟動
訪問http://localhost:8080/swagger/v2/api-docs:
返回的JSON信息中,paths對應Controller中RequestMapping配置的路徑
3 引入Swagger UI
上面的配置保證了Swagger后臺運作正常。Swagger UI實際就是一套完整的操作頁面。可以到https://github.com/swagger-api/swagger-ui將這些靜態文件下載下來,然后放到webapp根目錄。但是這樣顯然會增加項目結構復雜度。這里采用另外一種方式,即以依賴jar包的方式引入這些靜態文件。
3.1 引入Swagger UI依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
該jar包的結構如下:
這種方式的好處就是不會對現有項目結構造成污染,配置方便。
3.2 部署啟動
直接訪問Swagger UI的首頁:http://localhost:8080/swagger/swagger-ui.html。
點開某個接口連接,輸入入參信息,點擊Try it Out!按鈕即可。
完整示例:https://github.com/Impler/SwaggerIntegration/tree/master/swagger-suffix
4 包含后綴的URL配置
上述配置的Spring DispatcherServlet攔截所有請求,包括靜態資源,即url-pattern為/。但是現實中有很多將DispatcherServlet專門用來處理.do、.action等后綴結尾的請求,即。url-pattern為.do、.action。對靜態資源的請求則交由default servlet來處理。
web.xml
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
經過觀察網絡請求發現,Swagger UI在頁面加載時會發送如下4個請求:
- /swagger-resources/configuration/ui:swagger配置信息
- /swagger-resources:swagger資源路徑,默認default
- /swagger-resources/configuration/security:swagger安全性信息
- /v2/api-docs:項目內的接口信息(重要)
這些請求url均在swagger-ui的jar包內的靜態文件中定義,我們一般不去修改。但是swagger的這些請求又需要DispatcherServlet來分發處理,所以需要為這些url配置額外的url-pattern。
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
<!-- 為swagger配置額外的pattern-->
<url-pattern>/v2/api-docs</url-pattern>
<url-pattern>/swagger-resources</url-pattern>
<url-pattern>/swagger-resources/configuration/security</url-pattern>
<url-pattern>/swagger-resources/configuration/ui</url-pattern>
</servlet-mapping>
/v2/api-docs請求響應返回的json串的path屬性中包含項目內接口的所有url信息,其實現是在springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl
Bean中,通過掃描所有Controller類中@RequestMapping注解來獲取的。所以這里借助Spring強大的AOP功能,在swagger返回后臺接口信息前攔截,然后在所有的接口url中拼接指定的請求后綴。
package com.study.swagger.config;
/**
* 將接口url中追加模式后綴.do
* @author impler
* @date 2017年9月30日
*/
@Aspect
@EnableAspectJAutoProxy
@Component
public class SwaggerApiSuffixAspect {
@AfterReturning(pointcut="execution(public io.swagger.models.Swagger springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl.mapDocumentation(..))",
returning="swagger")
public void doBeforeBussinessCheck(Swagger swagger){
Map<String, Path> paths = swagger.getPaths();
if(null != paths){
Map<String, Path> newPaths = new HashMap<String, Path>(paths);
paths.clear();
Iterator<String> it = newPaths.keySet().iterator();
while(it.hasNext()){
String oldKey = it.next();
// 添加模式后綴 .do
String newKey = oldKey + ".do";
paths.put(newKey, newPaths.get(oldKey));
}
newPaths = null;
}
}
}
完整示例:https://github.com/Impler/SwaggerIntegration/tree/master/swagger-suffix