在Linux环境下对Swagger进行版本控制,可以通过以下几种方法实现:
初始化Git仓库:
git init
添加Swagger文件到仓库并提交初始版本:
git add swagger.yaml
git commit -m "Initial commit of Swagger definition"
后续修改Swagger文件后,重复添加和提交操作:
git add swagger.yaml
git commit -m "Swagger definition updated"
使用分支管理不同版本的API:
git checkout -b feature/v1.1
git checkout main
git merge feature/v1.1
添加Swagger依赖:
在pom.xml中添加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>
创建Swagger配置类: 定义多个Docket实例,每个实例对应一个API版本。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket apiV1() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("v1")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.ant("/api/v1/**"))
                .build();
    }
    @Bean
    public Docket apiV2() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("v2")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.ant("/api/v2/**"))
                .build();
    }
}
在控制器中添加版本信息: 为每个API接口添加相应的版本信息。
@RestController
@RequestMapping("/api/v1")
public class ApiControllerV1 {
    @GetMapping("/hello")
    public String hello() {
        return "Hello from API v1!";
    }
}
@RestController
@RequestMapping("/api/v2")
public class ApiControllerV2 {
    @GetMapping("/hello")
    public String hello() {
        return "Hello from API v2!";
    }
}
配置Swagger UI: 在配置方法中配置Swagger UI以展示所有版本的API文档。
app.UseSwaggerUI(c -> {
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
    c.SwaggerEndpoint("/swagger/v2/swagger.json", "API V2");
});
通过上述方法,可以在Linux系统中的Swagger中进行有效的版本控制,确保不同版本的API文档能够被正确管理和访问。