Swagger是一个Restful风格接口的文档在线自动生成和测试的框架(http://swagger.io),Swagger UI可以自动生成接口文档,不需要频繁更新接口文档,保证接口文档与代码的一致,代码改动时,接口文档可以自动修改。
1、添加依赖
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
2、添加swagger UI 配置类
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) //apiInfo指定测试文档基本信息,这部分将在页面展示 .apiInfo(apiInfo()) .select() //apis() 控制哪些接口暴露给swagger, // RequestHandlerSelectors.any() 所有都暴露 可省略 // RequestHandlerSelectors.basePackage("com.info.*") 指定包位置 可省略 .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } //基本信息,页面展示 private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("测试项目标题") .description("接口描述") //版本号 .version("1.0") .build(); } }
3、Controller类上加注解
@RestController @RequestMapping //Api注解,描述信息 可通过tags进行分类 @Api(value = "TestController", description = "TestController", tags = "测试") // swagger UI注解 public class TestController { @PostMapping("/getUserByParam") @ApiOperation(notes = "查看人员", value = "getUserByParam") // swagger UI注解 public User getUserByParam( @ApiParam(name = "name", value = "姓名") @RequestParam("name") String name, @ApiParam(name = "age", value = "年龄") @RequestParam("age") Integer age) { // 省略 } }
4、访问&测试
根据 localhost:8080/swagger-ui.html 地址访问,进入页面可以对对应的接口进行测试,使用非常方便。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/222173.html原文链接:https://javaforall.net
