ubuntu

Ubuntu环境下Swagger如何集成Spring Boot

小樊
87
2025-02-16 10:35:37
栏目: 智能运维

在Ubuntu环境下将Swagger集成到Spring Boot项目中,可以按照以下步骤进行操作:

1. 创建Spring Boot项目

如果你还没有一个Spring Boot项目,可以使用Spring Initializr来创建一个。

  1. 访问 Spring Initializr
  2. 配置你的项目:
    • Group: 通常是你的域名反写,例如 com.example
    • Artifact: 项目的名称,例如 swagger-demo
    • Name: 项目名称,例如 swagger-demo
    • Description: 项目描述。
    • Package name: 包名,例如 com.example.swaggerdemo
    • Packaging: 选择 JarWar
    • Java: 选择你使用的Java版本,例如 1117
  3. 添加依赖:
    • Dependencies 部分添加 Spring WebSpringfox Swagger2
  4. 点击 Generate 下载项目压缩包。
  5. 解压并导入到你的IDE中(例如IntelliJ IDEA或Eclipse)。

2. 添加Swagger依赖

在你的 pom.xml 文件中添加以下依赖:

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

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

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

3. 配置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.swaggerdemo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

4. 创建一个简单的Controller

创建一个简单的Controller来测试Swagger:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Swagger!";
    }
}

5. 运行Spring Boot应用

在终端中运行以下命令来启动Spring Boot应用:

./mvnw spring-boot:run

6. 访问Swagger UI

打开浏览器并访问以下URL来查看Swagger UI:

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

你应该能够看到你的API文档和测试界面。

总结

通过以上步骤,你已经成功地在Ubuntu环境下将Swagger集成到了Spring Boot项目中。你可以根据需要进一步配置Swagger,例如添加更多的API文档、自定义Swagger UI等。

0
看了该问题的人还看了