pom
依赖
<!--knife4j-->
<dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.3</version>
</dependency>
application.yml
knife4j:# 开启增强功能enable: true# 是否屏蔽生产环境production: true# 设置是否开启账密验证以及账密,改为true后访问页面时需输入账密basic:enable: falseusername: adminpassword: admin
配置类
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
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.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfig {// 创建Docket存入容器,Docket代表一个接口文档@Beanpublic Docket webApiConfig(){return new Docket(DocumentationType.SWAGGER_2).useDefaultResponseMessages(false)// 创建接口文档的具体信息.apiInfo(webApiInfo())// 创建选择器,控制哪些接口被加入文档.select()// 指定@ApiOperation标注的接口被加入文档,改为你自己的包路径.apis(RequestHandlerSelectors.basePackage("com.sun.controller")).paths(PathSelectors.any()).build();}// 创建接口文档的具体信息,会显示在接口文档页面中private ApiInfo webApiInfo(){return new ApiInfoBuilder()// 文档标题.title("参数校验Demo")// 文档描述.description("demo测试")// 版本.version("1.0").build();}
}
示例
@ApiModel("SysUser实体类")
@Data
public class SysUser {@ApiModelProperty(value = "id", required = true)private Integer id;@ApiModelProperty(value = "name", required = true)private String name;@ApiModelProperty(value = "birth", required = true)private Date birth;}
@Api(tags = "sysUser管理")
@RestController
@RequestMapping(value = "sysUser", produces = "application/json; charset=utf-8")
public class SysUserController {@ApiOperation("参数校验测试")@ApiImplicitParam(name = "sysUser", required = true)@PostMapping("test")public Result<SysUser> test(@RequestBody SysUser sysUser) {return AjaxResult.success(sysUser);}@ApiOperation("接口测试")@ApiImplicitParams({@ApiImplicitParam(name = "name", required = true)})@GetMapping("test2")public Result<String> test2(@RequestParam("name") String name) {return AjaxResult.success("OK: " + name);}}
访问测试
浏览器输入:http://IP:端口/doc.html
常用注解
@Api(tags = "sysUser管理")
// 放在controller类上,描述当前controller
@ApiOperation("接口测试")
// 放在接口上,描述当前接口
@ApiImplicitParam(name = "sysUser", required = true)
// 放在接口上,描述当前接口参数--->单个参数时
@ApiImplicitParams({@ApiImplicitParam(name = "name", required = true),@ApiImplicitParam(name = "age", required = true)
})
// 放在接口上,描述当前接口参数--->多个参数时
@ApiModel("SysUser实体类")
// 放在实体类上,描述当前实体类
@ApiModelProperty(value = "id", required = true)
// 放在实体类的属性上,描述当前属性