每个项目接口都离不开接口文档,一个界面美观可供调试的的接口文档不仅是开发人员的所追求的,更是使用者所向往的。
目前swagger2已具备了非常强大的文档和调试能力,而且越来越多的开发人员已在使用swagger2来作为文档生成工具。
使用swagger2需要在pom文件中进行依赖的添加
io.springfox
springfox-swagger2
2.2.2
io.springfox
springfox-swagger-ui
2.2.2
在包名com.dd.xx目录下(Application同级目录下)创建swagger2配置文件
Swagger2内容如下:
@Configuration
@EnableSwagger2
public class Swagger2 {
// 访问路径 http://localhost:9090/swagger-ui.html
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.dd.web")) // 控制器所在目录
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs") // 文档标题
.description("zw swagger2文档") // 文档描述
.termsOfServiceUrl("http://127.0.0.1:9090/") // 服务路径
.contact("zww")
.version("1.0")
.build();
}
}
@ApiOperation(value = "获取用户列表", notes ="")
@RequestMapping(value = {""}, method = RequestMethod.GET)
public List getUserList(){
List r = new ArrayList(users.values());
return r;
}
@ApiOperation(value="创建用户", notes="根据User对象创建用户")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@RequestMapping(value="", method=RequestMethod.POST)
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable Long id) {
return users.get(id);
}
@ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path"),
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
})
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable Long id, @RequestBody User user) {
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
/** 用户ID **/
@ApiModelProperty(value = "用户ID")
private Long id;
@ApiModelProperty(value = "用户名称")
private String name;
@ApiModelProperty(value = "用户年龄")
private Integer age;