要在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>
這里我們使用的是2.9.2版本的Swagger,你可以根據需要選擇其他版本。
創建一個Java類,例如SwaggerConfig.java
,并添加以下代碼:
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("Spring Boot Swagger 示例")
.description("Spring Boot + Swagger 的集成示例")
.version("1.0")
.build();
}
}
在這個配置類中,我們定義了一個名為api
的Docket
Bean。這個Bean用于配置Swagger的基本信息,如API標題、描述和版本。我們還指定了要掃描的包(在這里是com.example.demo.controller
),以便Swagger能夠找到并生成API文檔。
啟動你的Spring Boot應用程序,然后在瀏覽器中訪問以下URL:
http://localhost:8080/swagger-ui.html
這將打開Swagger UI界面,你可以在這里查看和測試你的API。
注意:如果你使用的是Spring Boot 2.6及以上版本,你可能需要添加以下配置以避免與Spring Boot Actuator的沖突:
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
// ...
}
并將@EnableSwagger2
替換為@EnableSwagger2WebMvc
。