随着互联网技术的发展,现在的网站架构基本都由原来的后端渲染,变成了:前端渲染、先后端分离的形态,而且前端技术和后端技术在各自的道路上越走越远。 前端和后端的唯一联系,变成了API接口;API文档变成了前后端开发人员联系的纽带,变得越来越重要,swagger就是一款让你更好的书写API文档的框架。提供了在线文档的查阅和测试功能,可以很容易的构建出RESTful风格的api。
第一步添加pom依赖:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency>创建Seagger2的配置文件:加注解@Configuration表示这是一个配置类,@EnableSwagger2注解表述开启Swagger2的功能。配置类红加入了一个Bean是Docket,包含了apiInfo().,即基本api文档的信息,以及包扫描的基本信息。
@Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.wx.learnspringboot")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("springboot利用swagger构建api文档") .description("简单优雅的restfun风格,www.baidu.ocm") .termsOfServiceUrl("www.baidu.ocm") .version("1.0") .build(); } }创建一个实体类:
public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
编写测试的Controller
@RestController public class TestController { static ConcurrentHashMap<String,User> userlist=new ConcurrentHashMap<String,User>(); @ApiOperation(value = "创建用户",notes = "创建用户") @RequestMapping(value = "/createUser",method = RequestMethod.POST) public User postUser(User user){ return user; } @ApiOperation(value = "查询用户",notes = "查询用户") @RequestMapping(value = "/getUser/{id}",method = RequestMethod.GET) public User postUser(@PathVariable Long id){ User user=new User(); user.setName("123"); user.setAge(12); return user; } }一定访问这个链接:http://127.0.0.1:8080/swagger-ui.html#/
测试:
swagger注解含义: