要在Spring Boot应用程序中集成Swagger,您需要遵循以下步骤:
在您的pom.xml文件中添加以下依赖项(如果您使用的是Maven):
<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();
}
}
在这个例子中,我们告诉Swagger扫描com.example.demo.controller包下的所有控制器。您可以根据需要更改包名。
启动您的Spring Boot应用程序后,您可以通过访问以下URL来查看Swagger UI:
http://localhost:8080/swagger-ui.html
现在,您可以在Swagger UI中查看和测试您的API。
注意:如果您使用的是Spring Boot 2.6或更高版本,您可能需要添加以下配置以避免与Spring Boot Actuator的冲突:
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My API")
.description("My API description")
.version("1.0.0")
.build();
}
这就是在Spring Boot应用程序中集成Swagger的方法。现在您可以为您的API生成文档并通过Swagger UI进行测试。