Swagger在Debian中的集成步驟(以Spring Boot項目為例)
首先更新Debian系統軟件包列表,并安裝Java(Swagger運行的基礎環境)、Maven(項目管理與構建工具):
sudo apt update && sudo apt upgrade -y
sudo apt install -y openjdk-11-jdk maven git
# 驗證安裝
java -version # 確認Java版本(需11及以上)
mvn -version # 確認Maven版本
通過Spring Initializr(https://start.spring.io/)生成基礎Spring Boot項目,選擇以下依賴:
springdoc-openapi-starter-webmvc-ui)。進入項目根目錄,編輯pom.xml文件(若使用Gradle則修改build.gradle):
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version> <!-- 使用最新穩定版 -->
</dependency>
<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>
Springdoc OpenAPI無需手動編寫配置類,只需在application.yml(或application.properties)中啟用UI:
springdoc:
swagger-ui:
enabled: true
path: /swagger-ui.html # 可自定義路徑(默認即可)
operationsSorter: method # 按HTTP方法排序(可選)
創建配置類(如SwaggerConfig.java),啟用Swagger并指定掃描路徑:
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) // 替換為你的控制器包路徑
.paths(PathSelectors.any())
.build();
}
}
在controller包下創建REST控制器(如HelloController.java),使用Swagger注解描述接口:
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
@Api(tags = "示例API", description = "基礎CRUD操作接口") // 接口分類與描述
public class HelloController {
@GetMapping("/hello")
@ApiOperation(value = "問候接口", notes = "返回'Hello, World!'字符串", response = String.class)
public String sayHello() {
return "Hello, World!";
}
@PostMapping("/data")
@ApiOperation(value = "數據提交接口", notes = "接收JSON字符串并返回確認信息")
public String sendData(@RequestBody String data) {
return "Received: " + data;
}
}
在項目根目錄下執行Maven命令,生成可執行的JAR文件:
mvn clean package
# 打包完成后,JAR文件位于target目錄(如demo-0.0.1-SNAPSHOT.jar)
將生成的JAR文件傳輸到Debian服務器(使用scp命令):
scp target/demo-0.0.1-SNAPSHOT.jar user@your-server-ip:/opt/swagger-app/
登錄服務器,使用Java命令啟動應用:
ssh user@your-server-ip
cd /opt/swagger-app/
java -jar demo-0.0.1-SNAPSHOT.jar
# 應用啟動后,控制臺會顯示端口信息(默認8080)
在瀏覽器中輸入以下URL訪問Swagger文檔:
http://your-server-ip:8080/swagger-ui.htmlhttp://your-server-ip:8080/swagger-ui.html進入頁面后,可查看接口列表、輸入參數、發送測試請求,并查看響應結果。
注意事項:
src/main/resources/static目錄下的靜態文件(Springfox)或通過application.yml配置(Springdoc)。