版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010046908/article/details/55047193
1、Swagger2是什么?
Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。
2、Swagger2官网
3.Swagger2的入门教程
3.1Swagger2的maven依赖
<!-- 构建Restful API -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
3.2RestApiConfig的配置
package com.lidong.dubbo.web.util;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @项目名称:lidong-dubbo
* @类名:RestApiConfig
* @类的描述: Restapi的基本配置
* @作者:lidong
* @创建时间:2017/2/11 上午10:01
* @公司:chni
* @QQ:1561281670
* @邮箱:lidong1665@163.com
* @使用方法:Restful API 访问路径: http://localhost:8080/lidong-dubbo-web/swagger-ui.html
*/
@EnableWebMvc
@EnableSwagger2
@Configuration
@ComponentScan(basePackages ="com.lidong.dubbo")
public class RestApiConfig extends WebMvcConfigurationSupport {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.lidong.dubbo.web"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringMVC中使用Swagger2构建RESTful APIs")
.termsOfServiceUrl("https://github.com/lidong1665")
.contact(new Contact("请叫我小东子","http://blog.csdn.net/u010046908","lidong1665@163.com"))
.version("1.0.0")
.build();
}
}
3.3在Controller中添加
@ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value = "getUserForid/{id}", method = RequestMethod.GET)
@ResponseBody
public String getUser(@PathVariable int id) {
try {
return JsonUtil.bean2json(userService.getUserById(id));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}