要在Spring Boot項目中集成Swagger,你需要遵循以下步驟:
在你的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>
如果你使用的是Gradle,請在build.gradle文件中添加以下依賴:
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'
創建一個新的Java類,例如SwaggerConfig.java,并添加以下代碼:
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();
}
}
將com.example.demo.controller替換為你的控制器類所在的包名。
啟動你的Spring Boot應用程序,然后在瀏覽器中訪問以下URL:
http://localhost:8080/swagger-ui.html
你應該能看到Swagger UI界面,其中列出了你的API端點。你可以使用這個界面來測試你的API。
注意:以上步驟適用于Spring Boot 2.x和Swagger 2.x。如果你使用的是Spring Boot 3.x,你需要使用springdoc-openapi庫來替代springfox-swagger。