Swagger2+knife4j增强

·  阅读 997

原由

  1. 我懒,而且手写API确实很累并且容易出错,通过注解生成API以此达到代码动,API动的效果。
  2. swagger2的原生UI很丑,knife4j更符合国人的审美和习惯。

导包

<!--swagger2本体-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<!--knife4j增强swagger2的UI-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>2.0.2</version>
</dependency>
复制代码

开始编写代码

目录结构

Swagger2Demo目录结构.png

Swagger2配置文件

@Configuration
@EnableSwagger2  //启动swagger2
@EnableKnife4j  //启动Knife4j UI增强(可不写)
@Import(BeanValidatorPluginsConfiguration.class)  //启动Knife4j UI增强(可不写)
public class SwaggerConfig {

    @Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                //在下面的方法中设置API的一些基本信息:标题、描述、版本号
                .apiInfo(buildApiInfo())
                //启动用于api选择的生成器
                .select()
                //拦截要生成API的包的名称
                .apis(RequestHandlerSelectors.basePackage("com.dclup.controller"))
                //拦截要声称API的具体接口,any代表所有
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo buildApiInfo() {
        //创建联系人对象
        Contact contact=new Contact("二狗","https://dclup.com","78133262@qq.com");
        return new ApiInfoBuilder()
                //文档标题
                .title("用户接口")
                //文档描述
                .description("用户的增删改查")
                //联系人
                .contact(contact)
                //版本号
                .version("1.0")
                //构建文档
                .build();
    }
}
复制代码

Model

UserDto

@Data
@ApiModel(description = "User接收数据对象")
public class UserDto {
    @ApiModelProperty(value ="用户id",name="userId",dataType="Long",required = false,example = "1",hidden = true )
    private Long userId;
    @ApiModelProperty(value ="用户密码",name="password",dataType="String",required = false,example = "123456" )
    private Long password;
}
复制代码

hidden属性:不将此API显示在API中

UserVo

@Data
public class UserVo {
    @ApiModelProperty(value ="用户id",name="userId",dataType="Long",required = false,example = "1")
    private Long userId;
    @ApiModelProperty(value ="姓名",name="userName",dataType="String",required = false,example = "王五")
    private String userName;
    @ApiModelProperty(value ="电话",name="phoneNumber",dataType="String",required = false,example = "199-1234-5678")
    private String phoneNumber;
    @ApiModelProperty(value ="地址",name="phoneNumber",dataType="String",required = false,example = "中国")
    private String address;
}
复制代码

Controller

  1. tags:就是左侧一组一组的下拉框,一个controller对应一个tags
  2. 写了tags就不用写value了,会覆盖
@RestController
@RequestMapping("/swagger")
@Api(value = "用户Controller(这里是类描述信息)",tags = "用户(这里是类的标签)")
public class SwaggerController {


    /**
     * 根据id获取一个用户信息
     * @param userId
     * @param response
     * @return
     */
    @GetMapping("/user/{userId}")
    @ApiOperation(value = "根据id获取一个用户信息",notes = "id必传")
    public UserVo getUserById(
            @PathVariable("userId") Long userId,
            HttpServletResponse response
    ){
        //模拟查询数据
        if(userId.equals(1L)){
            UserVo userVo = new UserVo();
            userVo.setUserId(1L);
            userVo.setUserName("赵四");
            userVo.setAddress("中国");
            userVo.setPhoneNumber("199-1234-5678");
            return userVo;
        }else {
            response.setStatus(404);
        }
        return null;
    }

    /**
     * 添加一个用户
     * @param userDto
     * @param response
     * @return
     */
    @PostMapping("/user")
    @ApiOperation(value = "添加一个用户",notes = "数据格式要对")
    public UserVo addUser(
            @RequestBody UserDto userDto,
            HttpServletResponse response
            ){
        UserVo userVo = new UserVo();
        userVo.setUserId(2L);
        userVo.setUserName("大侠");
        userVo.setAddress("中国");
        userVo.setPhoneNumber("199-9876-5432");
        return userVo;
    }
}

复制代码

启动项目

输入:localhost:{port}/doc.html,查看接口文档

参考

www.yangcloud.online/archives/sp… doc.xiaominfo.com/

个人博客

dclup.com

代码

github.com/yam-congee/…

分类:
后端
标签:
分类:
后端
标签:
收藏成功!
已添加到「」, 点击更改