swagger+springboot简单应用
1.简介:
knife4j 是swagger-ui 的增强,优化了api文档界面; 官网: https://doc.xiaominfo.com/knife4j/documentation/ ;
2.springboot工程添加swagger:
环境准备:
<!--注入web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.5.0</version> </dependency> <!--注入lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.14</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
依赖引入:
<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.3</version> <exclusions> <exclusion> <artifactId>swagger-annotations</artifactId> <groupId>io.swagger</groupId> </exclusion> </exclusions> </dependency> <dependency> <artifactId>swagger-annotations</artifactId> <groupId>io.swagger</groupId> <version>1.5.22</version> </dependency>
创建配置类:
package com.example.common; import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 @EnableKnife4j @Configuration public class SwaggerConfig { @Value("server.servlet.context-path") private String contextPath; @Value("${spring.profiles.active}") private String deployMode; @Bean(value = "defaultApi2") public Docket defaultApi2() { Docket docket = new Docket(DocumentationType.SWAGGER_2) .apiInfo(new ApiInfoBuilder() //.title("swagger-bootstrap-ui-demo RESTful APIs") .description("# swagger-bootstrap-ui-demo RESTful APIs") .version("1.0") .build()) .pathMapping(!deployMode.toLowerCase().equals("dev") ? contextPath : "/") //分组名称 .groupName("2.X版本") .select() //这里指定Controller扫描包路径 .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); return docket; } }
创建实体:
package com.example.vo; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.time.LocalDateTime; import java.util.List; @Data @ApiModel("用户信息实体") public class UserInfoVo { @ApiModelProperty(value = "id标识", example = "1") private String id; @ApiModelProperty(value = "id标识数组", example = "['1','2']") private String[] ids; @ApiModelProperty(value = "姓名", example = "张三") private String name; @ApiModelProperty(value = "年龄", example = "18") private Integer age; @ApiModelProperty(value = "性别(M(男)/F(女))", example = "M") private String sex; @ApiModelProperty(value = "手机号码", example = "15200000000") private String phone; @ApiModelProperty(value = "状态", example = "1") private Integer auditStatus; @ApiModelProperty(value = "状态数组", example = "[1,2]") private Integer[] auditStatuss; @ApiModelProperty(value = "状态集合", example = "[1,2]") private List<Integer> auditStatusList; @ApiModelProperty(value = "创建人") private String createdBy = "system"; @ApiModelProperty(value = "创建时间") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime createdDate; @ApiModelProperty(value = "更新人") private String updatedBy = "system"; @ApiModelProperty(value = "更新时间") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime updatedDate; }
创建controller:
package com.example.controller; import com.alibaba.fastjson.JSON; import com.example.vo.UserInfoVo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.v3.oas.annotations.parameters.RequestBody; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @Api(value = "首页模块") @RequestMapping("/test") public class TestController { @RequestMapping("/hello") public String sayHello() { log.info("Hello world!"); return "Hello world!"; } @ApiOperation(value = "获取用户信息") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "姓名"), @ApiImplicitParam(name = "phone", value = "电话")}) @GetMapping("/getUser") public UserInfoVo getUser(@RequestParam("name") String name, @RequestParam("phone") String phone) { log.info("getUser 入参: name:{},phone:{}", name, phone); UserInfoVo userInfoVo = new UserInfoVo(); if (StringUtils.isNotEmpty(name)) { userInfoVo.setName(name); } if (StringUtils.isNotEmpty(phone)) { userInfoVo.setPhone(phone); } return userInfoVo; } @ApiOperation(value = "获取用户信息") @PostMapping("/getUserByCondition") public UserInfoVo getUserByCondition(@Validated @RequestBody UserInfoVo userInfoVo) { log.info("getUserByCondition 入参: {}", JSON.toJSONString(userInfoVo)); return userInfoVo; } }
注意: 使用swagger注释对象并使用example时,注意数组集合类型的属性格式是否正确,否则会出现swagger无法解析,界面无法打开;
验证: http://localhost:8080/doc.html
参考文档: https://doc.xiaominfo.com/knife4j/documentation/swaggermodels.html