-
Swagger與SpringMVC項目整合
為了方便的管理項目中API接口,在網上找了好多關於API接口管理的資料,感覺目前最流行的莫過於Swagger了,功能強大,UI界面漂亮,並且支持在線測試等等,所以本人仔細研究了下Swagger的使用,下面就如何將Swagger與個人的SpringMVC項目進行整合做詳細說明:
最終API管理界面:
詳細步驟:
Step1:項目中引入相關jar包:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <version.spring>3.2.9.RELEASE</version.spring> <version.jackson>2.4.4</version.jackson> </properties> <dependencies> .... <dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> <version>0.9.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${version.jackson}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${version.jackson}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${version.jackson}</version> </dependency> </dependencies>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
Step2:添加自定義config文件
package com.spg.apidoc.common.configer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.mangofactory.swagger.configuration.SpringSwaggerConfig; import com.mangofactory.swagger.models.dto.ApiInfo; import com.mangofactory.swagger.plugin.EnableSwagger; import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; /** * 項目名稱:apidoc * * @description: * @author Wind-spg * @create_time:2015年2月10日 上午10:27:51 * @version V1.0.0 * */ @Configuration @EnableSwagger // Loads the spring beans required by the framework public class MySwaggerConfig { private SpringSwaggerConfig springSwaggerConfig; /** * Required to autowire SpringSwaggerConfig */ @Autowired public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) { this.springSwaggerConfig = springSwaggerConfig; } /** * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc * framework - allowing for multiple swagger groups i.e. same code base * multiple swagger resource listings. */ @Bean public SwaggerSpringMvcPlugin customImplementation() { return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns( ".*?"); } private ApiInfo apiInfo() { ApiInfo apiInfo = new ApiInfo( "My Apps API Title", "My Apps API Description", "My Apps API terms of service", "My Apps API Contact Email", "My Apps API Licence Type", "My Apps API License URL"); return apiInfo; } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
Step3:將此配置加入到Spring容器中,如下:
<bean class="com.spg.apidoc.common.configer.MySwaggerConfig" />
- 1
Step4:在代碼中添加相關APIAnnotation,如下:
@ResponseBody @RequestMapping( value = "addUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8") @ApiOperation(value = "添加用戶", httpMethod = "POST", response = BaseResultVo.class, notes = "add user") public String addUser(@ApiParam(required = true, name = "postData", value = "用戶信息json數據") @RequestParam( value = "postData") String postData, HttpServletRequest request) { LOGGER.debug(String.format("at function, %s", postData)); if (null == postData || postData.isEmpty()) { return super.buildFailedResultInfo(-1, "post data is empty!"); } UserInfo user = JSON.parseObject(postData, UserInfo.class); int result = userService.addUser(user); return buildSuccessResultInfo(result); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
說明:
其中@ApiOperation和@ApiParam為添加的API相關注解,個參數說明如下:
@ApiOperation(value = “接口說明”, httpMethod = “接口請求方式”, response = “接口返回參數類型”, notes = “接口發布說明”;其他參數可參考源碼;
@ApiParam(required = “是否必須參數”, name = “參數名稱”, value = “參數具體描述”Step5:添加Swagger UI配置
在GitHub上下載SwaggerUI項目,將dist下所有內容拷貝到本地項目webapp下面,結果目錄如下圖所示:
Step6:修改index.html
將index.html中http://petstore.swagger.wordnik.com/v2/swagger.json修改為http://localhost:8080/{projectname}/api-docs
到此為止,所有配置完成,啟動你的項目,訪問http://localhost:8080/{projectName}/index.html即可看到如下所示頁面:
項目最終demo可見個人GitHub
https://github.com/itboyspg/spg-code/tree/master/apidoc
參考:
https://github.com/martypitt/swagger-springmvc
https://github.com/swagger-api/swagger-ui項目jar包下載:http://download.csdn.net/detail/fengspg/8550451
http://blog.csdn.net/fengspg/article/details/43705537
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-core_2.10</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.10.0</version>
</dependency>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
import com.wordnik.swagger.model.ApiInfo;
@Configuration
@EnableSwagger
public class MySwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
/**
* Required to autowire SpringSwaggerConfig
*/
@Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
/**
* Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc framework - allowing for multiple
* swagger groups i.e. same code base multiple swagger resource listings.
*/
@Bean
public SwaggerSpringMvcPlugin customImplementation(){
SwaggerSpringMvcPlugin ssmp = new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
.apiInfo(apiInfo())
.swaggerGroup("api-docs").build();
return ssmp;
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(
"tk API SPECIFICATION",
"This is the tk api specification,here you can dig into the details of api and do api testing as well.",
"",
"",
"",
"");
return apiInfo;
}
}
<mvc:annotation-driven/>
<bean id="apiDoc" class="com.tk.framework.rest.framework.swaggerconfig.MySwaggerConfig"/>
<!-- Enable scanning of spring @Configuration classes -->
<context:annotation-config/>
<!-- Enable the default documentation controller-->
<context:component-scan base-package="com.mangofactory.swagger.controllers"/>
<!-- Pick up the bundled spring config-->
<context:component-scan base-package="com.mangofactory.swagger.configuration"/>
@RestController
@RequestMapping(value = "/1/users")
@Api(value = "User", description = "User service api", position = 1)
public class UserResourceV1 extends BaseResources
{
private static final Logger logger = LoggerFactory.getLogger(UserResourceV1.class);
@Autowired
private UserService userService;
@ResourceDescription(Resource="user", Operation="getUser")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ApiOperation(httpMethod = "GET", nickname="getUser", value = "get user by userId")
public ResponseModel getUser(@ApiParam(value = "id for greeting", required = true)@PathVariable String id) throws RestException
{
UserModel u = null;
try
{
u = userService.findById(id);
}
catch (Exception e)
{
logger.error(e.getMessage());
throw new RestException(e.getMessage());
}
ResponseModel r = new ResponseModel();
r.setStatus(200);
r.setResult(u);
return r;
}
}
為Model添加Swagger的Annotation,這樣Swagger Scanner可以獲取更多關於Model對象的信息。 :@ApiModel(value="User")
@Entity
@Table(name = "user")
public class UserModel {
/**
* id
*/
@ApiModelProperty(required = true)
private String id;
/**
* 姓名
*/
@ApiModelProperty(required = true)
private String name;
/**
* 年齡
*/
@ApiModelProperty(required = true, allowableValues="range[1,100]")
private Integer age;
/**
* 性別
*/
@ApiModelProperty(required = true, allowableValues = "F,M")
private String sex;
@ApiModelProperty(required = true)
private String password;
……

window.swaggerUi = new SwaggerUi({
url: "/api/api-docs",
dom_id: "swagger-ui-container",



