在Linux環境下,將Swagger與Spring Boot結合使用可以讓你更方便地構建和測試RESTful API。以下是詳細的步驟指南:
首先,你需要創建一個Spring Boot項目。你可以使用Spring Initializr(https://start.spring.io/)來快速生成項目結構。
Spring Web和Springfox Swagger2(或Springdoc OpenAPI,后者更現代且易于使用)。解壓下載的項目壓縮包,并使用你喜歡的IDE(如IntelliJ IDEA、Eclipse等)導入項目。
添加依賴:
在pom.xml文件中添加以下依賴:
<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: 創建一個配置類來配置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();
}
}
訪問Swagger UI:
啟動Spring Boot應用程序后,訪問http://localhost:8080/swagger-ui.html即可看到Swagger UI界面。
添加依賴:
在pom.xml文件中添加以下依賴:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.2</version>
</dependency>
配置OpenAPI: Springdoc OpenAPI會自動配置Swagger UI,無需額外配置。
訪問OpenAPI UI:
啟動Spring Boot應用程序后,訪問http://localhost:8080/swagger-ui/index.html即可看到OpenAPI UI界面。
編寫一個簡單的Controller來測試Swagger:
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
@Api(tags = "示例接口")
public class ExampleController {
@GetMapping("/hello")
@ApiOperation("返回Hello World")
public String hello() {
return "Hello World";
}
}
在終端中運行以下命令啟動Spring Boot應用程序:
./mvnw spring-boot:run
打開瀏覽器,訪問http://localhost:8080/swagger-ui.html(或http://localhost:8080/swagger-ui/index.html),你應該能看到Swagger UI界面,并且可以測試你的API。
通過以上步驟,你就可以在Linux環境下成功地將Swagger與Spring Boot結合使用,從而更方便地構建和測試RESTful API。