在Linux中集成Swagger與Spring Boot的步驟如下:
首先,在Spring Boot項目的pom.xml
文件中添加Swagger和Swagger UI的依賴。對于Spring Boot 2.x,可以使用springfox-swagger2
和springfox-swagger-ui
這兩個庫。
Maven依賴示例:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
</dependencies>
創建一個Java類來配置Swagger。這個類需要使用@Configuration
注解,并且包含一個方法來定義Swagger的Docket
Bean。
SwaggerConfig.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();
}
}
使用Maven命令來構建和運行Spring Boot應用程序:
./mvnw spring-boot:run
確保你有適當的權限來執行這個命令,可能需要使用sudo
。
在瀏覽器中訪問以下URL查看Swagger UI界面:
http://localhost:8080/swagger-ui.html
這里的端口號8080
是Spring Boot應用程序的默認端口,如果你的應用程序運行在不同的端口上,請相應地更改URL。
在控制器類和方法上添加Swagger注解,生成更詳細的API文檔。例如:
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("返回一個簡單的問候語")
public String sayHello() {
return "Hello, World!";
}
}
修改控制器或方法后,Swagger會自動更新API文檔。您可以隨時訪問Swagger UI界面查看最新文檔。
通過以上步驟,您就可以在Linux環境中成功集成Swagger與Spring Boot,并且可以通過Swagger UI界面來查看和測試您的API。