Swagger2简介
Swagger是一个开源的API文档生成和交互式测试平台,它可以用来描述、生产和测试RESTful APIs。在Spring Cloud微服务架构中,使用Swagger可以帮助开发者快速生成API文档,方便前端开发和团队协作。Swagger2是Swagger的第二个版本,相较于第一版,Swagger2在性能和功能上都进行了大幅度的提升。
Swagger2在Spring Cloud中的应用
1. 搭建Spring Boot项目
首先,我们需要搭建一个基本的Spring Boot项目。可以通过Spring Initializr(https://start.spring.io/)快速生成项目结构,并在添加依赖时选择Spring Web、Spring Cloud和Swagger2相关的依赖。
2. 添加Swagger2依赖
在项目的pom.xml文件中添加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>
3. 创建Swagger配置类
在项目中创建一个Swagger配置类,用于配置Swagger2的相关属性。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
}
4. 添加Swagger注解
在Controller层,使用Swagger提供的注解来标记API接口,并添加描述信息。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@Api(value = "Swagger示例", description = "Swagger示例接口")
public class SwaggerController {
@GetMapping("/swagger")
@ApiOperation(value = "Swagger示例方法", notes = "Swagger示例方法")
public String getSwagger() {
return "这是Swagger示例方法";
}
}
5. 启动项目
启动项目后,访问http://localhost:8080/swagger-ui.html,即可看到生成的API文档。
Swagger2配置
1. 全局配置
在SwaggerConfig类中,我们可以通过Docket对象配置Swagger的全局属性,如:
enable():是否启用SwaggeruseDefaultResponseMessages():是否使用默认的响应消息select():用于配置哪些API需要被包含在文档中
2. 分组配置
Swagger2支持将API接口进行分组,便于管理。在SwaggerConfig类中,可以通过apis()方法配置分组。
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build()
.pathMapping("/") // 设置默认访问路径
.apiInfo(apiInfo()) // 设置API信息
.useDefaultResponseMessages(false) // 禁用默认的响应消息
.group("基础接口") // 设置分组名称
3. 分组文档配置
在Controller层,可以通过@Api注解设置API分组。
@Api(value = "基础接口", description = "基础接口分组")
@RestController
public class SwaggerController {
// ...
}
总结
通过本文的介绍,相信你已经对Swagger2在Spring Cloud中的应用与配置有了较为全面的认识。在实际项目中,根据需求灵活配置Swagger2,可以大大提高开发效率,降低团队沟通成本。