Swagger使用
1. Swagger是什么?
官方说法:Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。
使用Swagger2有助于我们编写一份详细的RESTful业务接口文档,过去经常会使用Word或者Excel,但是接口非常多,细节又复杂,如果由程序员高质量的输出一个文档,经常耗时长而且效果也不好。Swagger2能将代码和注释说明很好结合在一块。既减轻了研发人员的负担,又能输出高质量的文档。
2. spring boot 集成 Swagger
spring-boot系统集成swagger需要进行如下操作:
添加maven依赖,需要在系统的pom中添加如下依赖:
<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>
2.添加swagger配置文件,配置文件如下:
@Configuration //注解,让Spring来加载该类配置 public class Swagger2Config { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo())//添加api信息 .select() // 选择那些路径和api会生成document .apis(RequestHandlerSelectors.basePackage("com.mxyinhao.broker"))// 对api进行监控(填写controller目录) .paths(PathSelectors.any())// 对所有路径进行监控 .build(); } private ApiInfo apiInfo() {
return new ApiInfoBuilder() .title("测试接口") .termsOfServiceUrl("http://www.mxyinhao.com/")
.contact("作者名")
.version("0.0.1-SNAPSHOT")
.build();
}
}
3.入口处添加标签
@EnableAutoConfiguration//开启spring自动配置功能 @SpringBootApplication @EnableSwagger2//注解来启用Swagger2。 public class BrokerPortalApplication { public static void main(String[] args) { SpringApplication.run(BrokerPortalApplication.class, args); } }