1

一、Swagger?

1.1 什么是Swagger?

  • 官方说法:Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步

1.2 什么是SpringFox?

  • 官方定义为: Automated JSON API documentation for API's built with Spring,是一个开源的API Doc的框架, 它的前身是swagger-springmvc,可以将我们的Controller中的方法以文档的形式展现
  • 下文中需要导入的几个maven依赖就是通过SpringFox整合Swagger,以此来支持在Spring框架下进行使用

1.3 Swagger2的作用

这里指的Swagger2为,springfox-swagger2。通过这个依赖就可在spring中使用swagger的注解
  1. 可以生成文档形式的api,提供给不同团队
  2. 方便自测,方便领导查阅
  3. 无需过多冗余的word文档或网页文档

二、导入的maven依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

三、自定义配置类

@Configuration
public class Swagger2Config {

    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.im.controller"))//需要生成文档所在的包
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot使用swagger2构建api文档")//文档标题
                .description("简单优雅的restful风格,http://blog.csdn.net/saytime")//描述
                .termsOfServiceUrl("http://blog.csdn.net/saytime")
                .version("1.0")
                .build();
    }
}

四、测试

4.1 User实体类

@ApiModel(value = "用户实体")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class User {

    @JsonIgnore
    @ApiModelProperty(name = "用户车辆",dataType = "Car" ,notes = "用户车辆")
    private Car car;

    public User(Integer userId, String userName, String password, String email, String birthDate) {
        this.userId = userId;
        this.userName = userName;
        this.password = password;
        this.email = email;
        this.birthDate = birthDate;
    }

    @ApiModelProperty(name = "用户id", dataType = "Integer", notes = "用户id")
    private Integer userId;

    @ApiModelProperty(name = "用户名", dataType = "String", notes = "用户名")
    private String userName;

    @ApiModelProperty(name = "密码", dataType = "String", notes = "密码")
    private String password;

    @ApiModelProperty(name = "邮箱", dataType = "String", notes = "邮箱")
    private String email;

    @ApiModelProperty(name = "生日", dataType = "String", notes = "生日")
    private String birthDate;

}
PS:实体类中已经用了@AllArgsConstructor,但还是写了一个带参构造器,是因为笔者自测时用了static{}静态代码块来初始化对象,static{}的优先级是高于注解的,所以若没有自己写带参构造器是无法通过编译的

4.2 UserController

@RestController
@RequestMapping("/user")
@Api(value = "用户服务", description = "用户的基本操作")
public class UserController {

    @ApiOperation(value = "用户列表服务", notes = "查詢所有用戶的列表信息")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<User> list() {
        List<User> userList = new ArrayList<>();
        for (String key : DataNode.users.keySet()) {
            userList.add(DataNode.users.get(key));
        }
        return userList;
    }

    @ApiOperation(value ="根据用户ID查询用户信息",notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name="userId",value = "用户ID",required = true,dataType ="Integer",paramType = "path")
    @RequestMapping(value = "/findOneById/{userId}",method = RequestMethod.GET)
    public User findOneById(@PathVariable("userId") Integer userId) {
        for(String key: DataNode.users.keySet()) {
            User user = DataNode.users.get(key);
            if(user.getUserId().equals(userId)) {
                return user;
            }
        }

        return null;
    }

    @ApiOperation(value = "根据用户名获取用户信息")
    @RequestMapping(value = "/findOneUserName/{userName}",method = RequestMethod.GET)
    @ApiImplicitParam(name = "userName",value = "用户名",required = true,dataType = "String",paramType = "path")
    public User findOneByName( @PathVariable("userName") String userName) {
        for(String key: DataNode.users.keySet()) {
            User user = DataNode.users.get(key);
            if(userName.equals(user.getUserName())) {
                return user;
            }
        }

        return null;
    }

    @ApiOperation(value = "根据用户名获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名称", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/findOneByIdAndName",method = RequestMethod.GET)
    public User findOneByIdAndName(@RequestParam String userName, @RequestParam Integer id) {
        for(String key: DataNode.users.keySet()) {
            User user = DataNode.users.get(key);
            if(user.getUserName().equals(userName) && id.equals(user.getUserId())) {
                return user;
            }
        }

        return null;
    }

    @ApiOperation(value = "根据查询条件获取用户信息")
    @RequestMapping(value = "/findOneByCondition",method = RequestMethod.GET)
    public User findOneByCondition(UserCondition userCondition) {
        for(String key: DataNode.users.keySet()) {
            User user = DataNode.users.get(key);
            if(user.getUserName().equals(userCondition.getUserName()) &&
                    user.getUserId().equals(userCondition.getUserId())) {
                Car car = new Car();
                car.setName("奥迪");
                user.setCar(car);
                return user;
            }
        }
        return null;
    }
}

4.3 测试样列

image

image

五、参考

六、最后

若有不足,敬请指正
虚心若愚,求知若渴

MO_or
25 声望75 粉丝

小菜鸟的成长地。