官网文档:https://swagger.io/docs/
1、是一款让你更好的书写API文档的规范且完整框架。
2、提供描述、生产、消费和可视化RESTful Web Service。
3、是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业API管理的方方面面。
swagger通过注解生成接口文档,包括接口名、请求方法、参数、返回信息的等等。
@Api:修饰整个类,描述Controller的作用@ApiOperation:描述一个类的一个方法,或者说一个接口@ApiParam:单个参数描述@ApiModel:用对象实体来作为入参@ApiProperty:用对象接实体收参数时,描述对象的一个字段@ApiResponse:HTTP响应其中1个描述@ApiResponses:HTTP响应整体描述@ApiIgnore:使用该注解忽略这个API@ApiError :发生错误返回的信息@ApiImplicitParam:一个请求参数@ApiImplicitParams: 多个请求参数1、@Api修饰整个类,描述Controller的作用
2、@ApiOperation ,用于描述一个方法或者接口
可以添加的参数形式:@ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”)
3、@ApiParam单个参数描述
@ApiParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”,dateType="变量类型”,paramType="请求方式”)
4、@ApiImplicitParam 一个请求参数
@ApiImplicitParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”,dateType="变量类型”,paramType="请求方式”)
@ApiOperation(value = “根据用户名获取用户的信息”,notes = “查询数据库中的记录”,httpMethod = “POST”,response = String.class) @ApiImplicitParam(name = “userName”,value = “用户名”,required = true,dataType = “String”,paramType = “query”) 5、@ApiImplicitParams 多个请求参数
参数和@ApiImplicitParam一致,只是这个注解可以添加多个参数而已
@ApiImplicitParams({ @ApiImplicitParam(name = “nickName”,value = “用户的昵称”,paramType = “query”,dataType = “String”,required = true), @ApiImplicitParam(name = “id”,value = “用户的ID”,paramType = “query”,dataType = “Integer”,required = true) }) public String getUserInfoByNickName(String nickName, Integer id) { return “1234”; }
添加依赖
<!--Swagger2--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>编写配置类:SwaggerConfig .java
@Configuration @EnableSwagger2 public class SwaggerConfig { /** * 多人开发对个分组 * @return */ public Docket docket1(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("fly"); } /** * 配置Swagger的Docket的bean实例 * @param environment * @return */ @Bean public Docket docket(Environment environment){ //设置要显示swagger的环境 Profiles profiles=Profiles.of("dev","test"); //获取项目环境 boolean flag = environment.acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) //enable:false关闭swagger .enable(flag) .groupName("flyfly") .select() //RequestHandlerSelectors,配置要扫描的接口方式:basePackage:指定要扫描的包 //any():扫描全部;none():不扫描;withClassAnnotation:扫描类上的注解,参数是一个反射对象 //withMethodAnnotation:扫描方法上的注解 .apis(RequestHandlerSelectors.basePackage("com.fly.controller")) //paths():过滤路径 //.paths(PathSelectors.ant("/fly/**")) .build(); } /** * 配置swagger的apiInfo信息 * @return */ private ApiInfo apiInfo() { //作者信息 Contact DEFAULT_CONTACT = new Contact("flyfly", "", "xxx"); return new ApiInfo("飞飞的Swagger Api文档", "xx系统", "v1.0", "urn:tos", DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } }打开浏览器,输入http://localhost:8080/swagger-ui.html(端口号随你项目启动的端口号为准)
完成