在Linux系統下對Swagger進行版本管理,可以通過以下幾種方法實現:
git init
git add swagger.yaml
git commit -m "Initial commit of Swagger definition"
git add swagger.yaml
git commit -m "Swagger definition updated"
git checkout -b feature/v1.1
# 在新分支上進行開發
git checkout main
git merge feature/v1.1
添加Swagger依賴:
在 pom.xml
中添加SpringFox的依賴:
<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: 在Spring Boot配置類中配置Swagger,啟用版本控制:
@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();
}
}
在Controller中添加版本信息:
@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:
app.UseSwaggerUI(c -> {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
c.SwaggerEndpoint("/swagger/v2/swagger.json", "API V2");
});
通過上述方法,你可以在Linux系統上有效地對Swagger進行版本控制,確保不同版本的API文檔能夠被正確管理和訪問。