swagger2是什么?能做什么?为什么使用它?
swagger2是一个能用过注解的形式帮助我们生产api开发文档的工具包,同时也能够方便我们对api的一个实时管理和方便对api接口的调试,对于调用者也能更加直观发现问题,在api对接的过程中能提高我们对接时的效率。
效果图
Maven依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
配置swagger2
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//声明为配置文件,让spring加载
@EnableSwagger2//支持swagger2插件配置
public class Swagger2Config {
//apiInfo对象主要是设置我们api文档的标题,描述,访问的地址,创建者等信息
@Bean
public ApiInfo apiInfo(){
return new ApiInfoBuilder().title("This is a system interface").description("This is a system interface").termsOfServiceUrl("127.0.0.1:7878").contact("Elvis").version("1.0").build();
}
//docket容器设置我们的文档基础信息,api包的位置,以及路劲的匹配规则(包含四种:全匹配,不匹配,正则匹配和ant匹配)
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.swaggerdemo.swaggerdemo.controller")).paths(PathSelectors.regex("/rest/.*")).build();
}
}
测试控制层代码
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
public class ArticleRestController {
@RequestMapping(value = "/rest/article", method = POST, produces = "application/json")
@ApiOperation(value = "接口说明",httpMethod = "post",notes = "接口发布说明")
@ApiParam(name = "参数",value = "这是描述参数")
public String testSwagger2(@RequestBody String name) {
return name;
}
}