要在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>
这些依赖将帮助你在Spring Boot项目中集成Swagger。
创建一个新的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();
}
}
在这个类中,我们创建了一个名为api
的Docket
bean,它将负责配置Swagger。你需要将basePackage
方法的参数更改为你的控制器类所在的包。
启动你的Spring Boot应用程序,然后在浏览器中访问以下URL:
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();
}
现在你已经成功地将Swagger集成到了你的Spring Boot项目中。你可以使用Swagger UI来查看和测试你的API。