springboot整合接口文档:从swagger2到knife4j

springboot整合接口文档:从swagger2到knife4j

前言

Swagger是一套功能强大但易于使用的API开发人员工具套件,适用于团队和个人,支持从设计和文档到测试和部署的整个API生命周期的开发。一句话总结其作用:降低开发团队间的沟通成本,不用手动创建文档,自动记录接口细节。
接下来详细说明springboot整合swagger2及其升级版knife4j。

(一)springboot整合swagger2

1.1 添加依赖

注意springboot版本与swagger2版本是否匹配
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
        </dependency>

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

1.2 添加Swagger2配置类

@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.test_swagger.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("test_swagger")
                .description("swagger2测试")
                .termsOfServiceUrl("http://www.xx.com/")
                .version("1.0")
                .build();
    }

}

1.3 controller

自定义接口:获取用户列表、创建用户、获取用户详细信息、删除用户
@RestController
@RequestMapping(value="/users")
public class UserController {

    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    @ApiOperation(value="获取用户列表", notes="")
    @RequestMapping(value={""}, method=RequestMethod.GET)
    public List<User> getUserList() {
        List<User> r = new ArrayList<User>(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")
    @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"),
            @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";
    }

    @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value="/{id}", method= RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }

}

1.4 entity

User实体类
@Data
public class User {

    private Long id;
    private String name;
    private Integer age;

}

1.5 验证

启动项目,访问 http://localhost:8080/swagger-ui.html

springboot整合接口文档:从swagger2到knife4j

可以通过Try it out!进行调试

springboot整合接口文档:从swagger2到knife4j

(二)springboot整合knife4j

Knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案,前身是swagger-bootstrap-ui。

优势:
1.前端界面更加友好,提高操作体验
2.增加了接口排序、Swagger资源保护、导出Markdown、参数缓存等众多强大功能

2.1 添加依赖

注意springboot版本与knife4j版本是否匹配
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.7</version>
        </dependency>

2.2 添加配置类

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {

    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("test_knife4j")
                        .description("knife4j测试")
                        .termsOfServiceUrl("http://www.xx.com/")
                        .version("1.0")
                        .build())
                .groupName("2.X版本")
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.example.test_knife4j.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
}

2.3 controller entity

如上1.3controller 1.4entity所示

2.4 验证

启动项目,访问http://localhost:31613/doc.html 

springboot整合接口文档:从swagger2到knife4j
springboot整合接口文档:从swagger2到knife4j

springboot整合接口文档:从swagger2到knife4j

总结:

在项目中,不论是引入swagger2还是knife4j对API文档进行管理,都是不错的选择。鉴于knife4j的强大功能,推荐优先使用knife4j。

上一篇:【模式识别】SVM实现人脸表情分类


下一篇:【报错记录】解决SpringBoot使用knife4j无法引入@EnableSwagger2WebMvc