温馨提示×

Linux上Swagger如何与Spring Boot集成

小樊
33
2025-03-05 23:31:02
栏目: 智能运维
Linux服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Linux上将Swagger与Spring Boot集成,可以按照以下步骤进行:

1. 添加依赖

首先,在你的Spring Boot项目的pom.xml文件中添加Swagger和Swagger UI的依赖。

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>

    <!-- Swagger UI -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>

2. 配置Swagger

创建一个配置类来配置Swagger。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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();
    }
}

3. 启动应用

确保你的Spring Boot应用已经启动。你可以在终端中运行以下命令来启动应用:

mvn spring-boot:run

4. 访问Swagger UI

一旦应用启动,你可以通过浏览器访问Swagger UI。默认情况下,Swagger UI的地址是:

http://localhost:8080/swagger-ui.html

如果你在Linux上使用的是不同的端口,请相应地调整URL。

5. 验证Swagger集成

打开浏览器并访问上述URL,你应该能够看到Swagger UI界面,其中列出了你的API端点。你可以点击这些端点来查看详细的API文档和测试功能。

注意事项

  • 确保你的Spring Boot版本与Swagger版本兼容。
  • 如果你使用的是Spring Boot 3.x,可能需要使用SpringDoc OpenAPI(以前称为Swagger)来替代Swagger 2,因为Swagger 2不支持Spring Boot 3.x。

通过以上步骤,你就可以在Linux上成功地将Swagger与Spring Boot集成,并使用Swagger UI来管理和测试你的API。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Linux下Swagger与Spring Boot如何集成

0