spring和swagger

mac2024-04-17  29

swagger本身是一个框架,可以用来设计Api,可以提供一个UI界面展示Api文档,也可以通过UI交互发送数据到服务端进行接口测试。

spring是一个java框架,众所周知。

而springfox,则将swagger集成到spring中。

springboot集成swagger2的步骤:

1.maven构建的springboot项目,在pom中引入以下两个依赖来集成swagger:

<!-- swagger --> <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>

2.在Application.java同级创建Swagger2的配置类Swagger2,代码示例如下:

package com.mark; 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; /** * @author mark * @date 2019/10/27 11:50 * @description swagger配置类 */ @Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.mark")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .description("接口文档") .build(); } }

3.controller方法上添加注解,@ApiOperation描述接口作用,@ApiImplicitParams和@ApiImplicitParam标识接口入参,@ApiResponses和@ApiResponse标识接口返回状态码,比如200代表成功,-1代表失败。示例代码如下:

package com.mark.web.hello; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.web.bind.annotation.*; /** * @author mark * @date 2019/10/24 20:39 */ @RestController public class HelloController { @ApiOperation(value = "Get Hello") @ApiImplicitParam(name = "name", value = "姓名", defaultValue = "My Friend") @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), @ApiResponse(code = -1, message = "Fail") }) @GetMapping("/hello") public String sayHello(@RequestParam(name = "name", required = false, defaultValue = "My Friend") String name) { return "Hello " + name; } }

4.Model属性加上注解@ApiModelProperty标识属性含义,示例代码如下:

package com.mark.domain.user; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @author guolimin.lc */ @Data public class User { @ApiModelProperty(value = "主键") private Long id; @ApiModelProperty(value = "姓名") private String name; @ApiModelProperty(value = "年龄") private Integer age; }

备注:使用swagger之后,接口返回数据一般就不再定义list或map了,而是基本上都返回model,这样做是为了swagger的文档可以正确显示接口返回数据。

最新回复(0)