一:Swagger介紹
Swagger是當前最好用的Restful API文檔生成的開源項目,通過swagger-spring項目
實現了與SpingMVC框架的無縫集成功能,方便生成spring restful風格的接口文檔,
同時swagger-ui還可以測試spring restful風格的接口功能。
二:Swagger與Spring MVC集成步驟
1.Maven關鍵配置
- <dependency>
- <groupId>com.mangofactory</groupId>
- <artifactId>swagger-springmvc</artifactId>
- <version>1.0.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>4.1.6.RELEASE</version>
- </dependency>
2. 插件配置
CustomJavaPluginConfig
3.復制swagger的相關js等靜態資源到webapp目錄。
swagger-ui.js之類的。
我copy過一次,但是有問題,最后從網上下載了一個項目,可以直接用的那種。
然后自己再逐步改造。
4.啟動項目

三、常見swagger注解一覽與使用
最常用的5個注解
@Api:修飾整個類,描述Controller的作用
@ApiOperation:描述一個類的一個方法,或者說一個接口
@ApiParam:單個參數描述
@ApiModel:用對象來接收參數
@ApiProperty:用對象接收參數時,描述對象的一個字段
其它若干
@ApiResponse:HTTP響應其中1個描述
@ApiResponses:HTTP響應整體描述
@ApiClass
@ApiError
@ApiErrors
@ApiParamImplicit
@ApiParamsImplicit
四、關鍵代碼和實際例子
例子1:
- @ApiOperation(value = "獲得用戶列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "list", method = RequestMethod.POST)
- public Result<User> list(
- @ApiParam(value = "分類ID", required = true) @RequestParam Long categoryId,
- @ApiParam(value = "token", required = true) @RequestParam String token) {
- Result<User> result = new Result<User>();
- User user = new User();
- result.setData(user);
- return result;
- }
@ApiParam(value = "token", required = true) @RequestParam String token
Web前端/移動端HTTP請求方式:直接把參數附帶到URL后面,或者用AJAX方法,表單提交。
例子2:
- @ApiOperation(value = "update用戶", notes = ")", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "update", method = RequestMethod.GET/*,produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE*/)
- public Result<String> update(User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
當參數太多的時候,需要定義太多的參數,排版看起來很不舒服。
這個時候,可以使用對象來接收。
@ApiModel(value = "用戶對象",description="user2")
public class User extends CommonParam{
}
Web前端/移動端HTTP請求方式:直接把參數附帶到URL后面,或者用AJAX方法,表單提交。
這里面存在一個小問題,當后端用對象User來接收參數的時候,Swagger自帶的工具是這樣的:

這種形式,並不是表單提交,或者把參數附加到URL的后面。
我們只能手動構造URL,附帶參數去提交。
如果需要測試的話!
例子3:
- public Result<String> add(@RequestBody User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
Web前端/移動端HTTP請求方式:必須把參數,放到request請求的body中去。
后端不能直接用request.getParam("token")這種。
獲得request body中的數據,手動轉換成目標數據。
String charReader(HttpServletRequest request) throws IOException {
BufferedReader br = request.getReader();
String str, wholeStr = "";
while ((str = br.readLine()) != null) {
wholeStr += str;
}
return wholeStr;
}
個人推薦:
1.參數不多的時候,用例子1,用@ApiParam注解生成文檔。
swagger可視化界面,可以直接設置參數,發送請求來測試
2.參數比較多的時候,用例子2,用對象來接收參數,在對象里針對每個字段,@ApiModelProperty注解生成文檔。
swagger可視化界面,可以直接設置參數,但是無法接收到。
因此,推薦使用其它HTTP請求或POST模擬工具,發送請求,模擬測試。
不推薦例子3,不通用,局限性比較大。
五、若干截圖




六、源代碼
- package cn.fansunion.swagger.serverapi.controller;
- import org.springframework.http.MediaType;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
- import com.wordnik.swagger.annotations.Api;
- import com.wordnik.swagger.annotations.ApiOperation;
- import com.wordnik.swagger.annotations.ApiParam;
- /**
- * 小雷FansUnion-一個有創業和投資經驗的資深程序員-全球最大中文IT社區CSDN知名博主-排名第119
- * 博客:http://blog.csdn.net/fansunion
- *
- */
- @Api(value = "user", description = "用戶管理", produces = MediaType.APPLICATION_JSON_VALUE)
- @Controller
- @RequestMapping("user")
- public class UserController {
- // 列出某個類目的所有規格
- @ApiOperation(value = "獲得用戶列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "list", method = RequestMethod.POST)
- public Result<User> list(
- @ApiParam(value = "分類ID", required = true) @RequestParam Long categoryId,
- @ApiParam(value = "分類ID", required = true) @RequestParam Long categoryId2,
- @ApiParam(value = "token", required = true) @RequestParam String token) {
- Result<User> result = new Result<User>();
- User user = new User();
- result.setData(user);
- return result;
- }
- @ApiOperation(value = "添加用戶", notes = "獲取商品信息(用於數據同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "add", method = RequestMethod.POST)
- // @RequestBody只能有1個
- // 使用了@RequestBody,不能在攔截器中,獲得流中的數據,再json轉換,攔截器中,也不清楚數據的類型,無法轉換成java對象
- // 只能手動調用方法
- public Result<String> add(@RequestBody User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
- @ApiOperation(value = "update用戶", notes = "獲取商品信息(用於數據同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "update", method = RequestMethod.GET)
- public Result<String> update(User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
- private String findUser(User user) {
- String token = user.getToken();
- return token;
- }
- }
- package cn.fansunion.swagger.serverapi.controller;
- import com.wordnik.swagger.annotations.ApiModel;
- import com.wordnik.swagger.annotations.ApiModelProperty;
- /**
- * 小雷FansUnion-一個有創業和投資經驗的資深程序員-全球最大中文IT社區CSDN知名博主-排名第119
- * 博客:http://blog.csdn.net/fansunion
- *
- */
- @ApiModel(value = "用戶對象", description = "user2")
- public class User extends CommonParam {
- @ApiModelProperty(value = "商品信息", required = true)
- private String name;
- @ApiModelProperty(value = "密碼", required = true)
- private String password;
- @ApiModelProperty(value = "性別")
- private Integer sex;
- @ApiModelProperty(value = "密碼", required = true)
- private String token;
- public String getToken() {
- return token;
- }
- public void setToken(String token) {
- this.token = token;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public Integer getSex() {
- return sex;
- }
- public void setSex(Integer sex) {
- this.sex = sex;
- }
- }
- package cn.fansunion.swagger.serverapi.swagger;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
- import org.springframework.web.servlet.config.annotation.EnableWebMvc;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
- import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
- import com.mangofactory.swagger.models.dto.ApiInfo;
- import com.mangofactory.swagger.paths.SwaggerPathProvider;
- import com.mangofactory.swagger.plugin.EnableSwagger;
- import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
- @Configuration
- @EnableWebMvc
- @EnableSwagger
- public class CustomJavaPluginConfig extends WebMvcConfigurerAdapter {
- private SpringSwaggerConfig springSwaggerConfig;
- @Autowired
- public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
- this.springSwaggerConfig = springSwaggerConfig;
- }
- /**
- * 鏈式編程 來定制API樣式 后續會加上分組信息
- *
- * @return
- */
- @Bean
- public SwaggerSpringMvcPlugin customImplementation() {
- return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
- .apiInfo(apiInfo()).includePatterns(".*")
- .useDefaultResponseMessages(false)
- // .pathProvider(new GtPaths())
- .apiVersion("0.1").swaggerGroup("user");
- }
- private ApiInfo apiInfo() {
- ApiInfo apiInfo = new ApiInfo("小雷移動端API接口平台",
- "提供詳細的后台所有Restful接口", "http://blog.csdn.net/FansUnion",
- "FansUnion@qq.com", "小雷博客", "http://blog.csdn.net/FansUnion");
- return apiInfo;
- }
- @Override
- public void configureDefaultServletHandling(
- DefaultServletHandlerConfigurer configurer) {
- configurer.enable();
- }
- class GtPaths extends SwaggerPathProvider {
- @Override
- protected String applicationPath() {
- return "/restapi";
- }
- @Override
- protected String getDocumentationPath() {
- return "/restapi";
- }
- }
- }