温馨提示×

centos swagger与Spring Boot集成

小樊
49
2025-07-27 00:18:30
栏目: 智能运维

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

1. 创建Spring Boot项目

首先,你需要创建一个Spring Boot项目。你可以使用Spring Initializr(https://start.spring.io/)来快速生成项目结构。

  • 选择项目类型为Maven或Gradle。
  • 选择Java版本(建议使用Java 8或更高版本)。
  • 添加依赖项:Spring Web, Springfox Swagger2, Springfox Swagger UI。

2. 配置Swagger

在你的Spring Boot项目中,创建一个配置类来启用Swagger。

使用Springfox Swagger2

  1. 添加依赖: 在你的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. 配置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应用

在你的Spring Boot应用的主类上添加@SpringBootApplication注解,并启动应用。

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } 

4. 访问Swagger UI

启动应用后,打开浏览器并访问以下URL:

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

你应该能够看到Swagger UI界面,其中列出了你的API文档。

5. 编写API文档

在你的控制器类中使用Swagger注解来编写API文档。例如:

import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") @Api(tags = "示例API") public class ExampleController { @GetMapping("/hello") @ApiOperation("返回Hello World") public String hello() { return "Hello World"; } } 

6. 部署到CentOS

如果你需要将应用部署到CentOS服务器上,可以使用以下步骤:

  1. 打包应用: 使用Maven或Gradle打包你的Spring Boot应用。

    mvn clean package 
  2. 上传到服务器: 将打包好的JAR文件上传到你的CentOS服务器。

  3. 运行应用: 在服务器上运行以下命令来启动应用:

    java -jar your-application.jar 
  4. 配置防火墙: 确保你的CentOS服务器的防火墙允许访问8080端口。

    sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent sudo firewall-cmd --reload 

通过以上步骤,你就可以在CentOS系统上成功集成Swagger与Spring Boot,并通过Swagger UI来查看和管理你的API文档。

0