温馨提示×

Linux Swagger集成Spring Boot步骤是什么

小樊
34
2025-06-12 19:40:37
栏目: 智能运维

在Linux系统中集成Swagger与Spring Boot的步骤如下:

  1. 添加依赖: 在Spring Boot项目的pom.xml文件中添加Swagger和Springfox的依赖。例如:

    <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. 配置Swagger: 创建一个名为SwaggerConfig.java的Java配置类,并添加如下代码:

    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应用: 使用以下命令启动您的Spring Boot应用:

    ./mvnw spring-boot:run 

    或者如果你使用的是Gradle:

    ./gradlew bootRun 
  4. 访问Swagger UI: 启动应用后,在浏览器中访问以下URL:

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

    您将看到Swagger UI界面,其中包含了所有已注册的API接口信息。

  5. API文档配置: 在控制器类和方法中添加Swagger注解,生成更详细的API文档。

通过这些步骤,您可以在Linux环境中成功集成Swagger与Spring Boot,并使用Swagger UI来测试和文档化您的API。

0