在Linux系統中集成Swagger與Spring Boot的步驟如下:
添加依賴:
在Spring Boot項目的pom.xml文件中添加Swagger和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:
創建一個名為SwaggerConfig.java的Java配置類,并添加如下代碼:
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();
}
}
啟動Spring Boot應用: 使用以下命令啟動您的Spring Boot應用:
./mvnw spring-boot:run
或者如果你使用的是Gradle:
./gradlew bootRun
訪問Swagger UI: 啟動應用后,在瀏覽器中訪問以下URL:
http://localhost:8080/swagger-ui.html
您將看到Swagger UI界面,其中包含了所有已注冊的API接口信息。
API文檔配置: 在控制器類和方法中添加Swagger注解,生成更詳細的API文檔。
通過這些步驟,您可以在Linux環境中成功集成Swagger與Spring Boot,并使用Swagger UI來測試和文檔化您的API。