在Linux環境下,將Swagger與Spring Boot集成可以幫助你自動生成API文檔,方便前后端開發人員查看和測試接口。以下是詳細的步驟:
首先,在你的Spring Boot項目的pom.xml文件中添加Swagger和Swagger UI的依賴。
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Swagger UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
創建一個配置類來配置Swagger。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
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()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API Documentation")
.description("API Documentation for Spring Boot Application")
.version("1.0.0")
.build();
}
}
確保你的Spring Boot應用已經啟動。你可以使用以下命令來啟動應用:
./mvnw spring-boot:run
在瀏覽器中訪問以下URL來查看Swagger UI界面:
http://localhost:8080/swagger-ui.html
如果你希望自定義Swagger UI的外觀或行為,可以在配置類中進行相應的設置。例如,你可以添加自定義的CSS或JavaScript文件。
在Swagger UI界面中,你可以看到所有定義的API,并可以直接在界面上進行測試。
springfox-boot-starter而不是springfox-swagger2和springfox-swagger-ui。通過以上步驟,你就可以在Linux環境下成功地將Swagger與Spring Boot集成,并利用Swagger UI來管理和測試你的API。