API接口文档利器:Swagger
Swagger介绍
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务
官网地址 :https://swagger.io/
它的主要作用是:
- 使得前后端分离开发更加方便,有利于团队协作
- 接口的文档在线自动生成,降低后端开发人员编写接口文档的负担
- 功能测试
Spring已经将Swagger纳入自身的标准,建立了Spring-swagger项目,现在叫Springfox。通过在项目中引入Springfox ,即可非常简单快捷的使用Swagger
SpringBoot集成Swagger
- 在shanjupay-common项目中添加依赖,只需要在shanjupay-common中进行配置即可,因为其他微服务工程都直接或间接依赖shanjupay-common。
<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. 在jspringboot工程的confifig包中添加一个Swagger配置类
package cn.yyl.sailing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 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.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @ConditionalOnProperty(prefix = "swagger",value = {"enable"},havingValue = "true") @EnableSwagger2 public class SwaggerConfiguration { @Bean public Docket buildDocket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(buildApiInfo()) .select() // 要扫描的API(Controller)基础包 .apis(RequestHandlerSelectors.basePackage("cn.itcast.sailing.controller")) .paths(PathSelectors.any()) .build(); } /** * @param * @return springfox.documentation.service.ApiInfo * @Title: 构建API基本信息 * @methodName: buildApiInfo */ private ApiInfo buildApiInfo() { Contact contact = new Contact("徐帆","",""); return new ApiInfoBuilder() .title("验证码服务API文档") .description("包含验证码、短信api") .contact(contact) .version("1.0.0").build(); } }
添加SpringMVC配置类:WebMvcConfifig,让外部可直接访问Swagger文档
package cn.yyl.sailing.config; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Component public class WebMvcConfig implements WebMvcConfigurer { /** * 添加静态资源文件,外部可以直接访问地址 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
Swagger常用注解
在Java类中添加Swagger的注解即可生成Swagger接口文档,常用Swagger注解如下:
@Api:修饰整个类,描述Controller的作用 @ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数的描述信息
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数的描述信息
@ApiImplicitParam属性:
上边的属性后边编写程序时用到哪个我再详细讲解,下边写一个swagger的简单例子,我们在MerchantController 中添加Swagger注解,代码如下所示:
package cn.yyl.sailing.controller; import cn.itcast.sailing.common.domain.RestResponse; import cn.itcast.sailing.dto.VerificationInfo; import cn.itcast.sailing.service.VerificationService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; @Api(value = "验证码服务接口") @RestController public class VerificationController { @Autowired private VerificationService verificationService; /** * 生成手机验证码 * * @param name 业务名 * @param payload 业务携带参数,如手机号 ,邮箱 * @param effectiveTime 验证信息有效期(秒) * @return */ @ApiOperation(value = "生成验证信息", notes = "生成验证信息") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "业务名称", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "payload", value = "业务携带参数,如手机号 ,邮箱", required = true, paramType = "body"), @ApiImplicitParam(name = "effectiveTime", value = "验证信息有效期(秒)", required = false, dataType = "String", paramType = "query") }) @PostMapping(value = "/generate") public RestResponse<VerificationInfo> generateVerificationInfo(@RequestParam("name") String name, @RequestBody Map<String, Object> payload, @RequestParam("effectiveTime") int effectiveTime) { VerificationInfo verificationInfo = verificationService.generateVerificationInfo(name, payload, effectiveTime); return RestResponse.success(verificationInfo); } /*** * 校验手机验证码 * @param name 业务名称 * @param verificationKey 验证key * @param verificationCode 验证码 * @return */ @ApiOperation(value = "校验", notes = "校验") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "业务名称", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "verificationKey", value = "验证key", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "verificationCode", value = "验证码", required = true, dataType = "String", paramType = "query") }) @PostMapping(value = "/verify") public RestResponse<Boolean> verify(String name, String verificationKey, String verificationCode) { Boolean isSuccess = verificationService.verify(name, verificationKey, verificationCode); return RestResponse.success(isSuccess); } @ApiOperation("测试") @GetMapping(path = "/hello") public String hello() { return "hello"; } @ApiOperation("测试") @ApiImplicitParam(name = "name", value = "姓名", required = true, dataType = "string") @PostMapping(value = "/hi") public String hi(String name) { return "hi," + name; } }
Swagger测试
启动商户应用和商户中心服务,访问:http://localhost:57010/你的服务访问地址/swagger-ui.html
服务访问地址在yml配置中:
打开页面如下:
点击其中任意一项即可打开接口详情,如下图所示:
点击“Try it out”开始测试,并录入参数信息,然后点击“Execute"发送请求,执行测试返回结果:“hi,李四”
Swagger生成API文档的工作原理:
1、springboot项目启动时会扫描到SwaggerConfiguration类
2、在此类中指定了扫描包路径com.包名.controller,会找到在此包下及子包下标记有 @RestController注解的controller类
3、根据controller类中的Swagger注解生成API文档