要在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,你可以根据需要选择其他版本。
创建一个名为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。RequestHandlerSelectors.basePackage
方法用于指定需要进行Swagger文档生成的Controller所在的包名。PathSelectors.any()
表示所有路径都需要生成文档。
启动你的Spring Boot应用程序,然后在浏览器中访问以下URL:
http://localhost:8080/swagger-ui.html
这里假设你的应用程序运行在8080端口上。你应该能看到Swagger UI界面,其中列出了你的API文档。
现在你已经成功地将Swagger集成到了你的Spring Boot项目中。你可以使用Swagger UI来测试和浏览你的API。