ubuntu

Swagger与Ubuntu如何协同工作

小樊
42
2025-05-05 13:50:01
栏目: 智能运维

Swagger与Ubuntu可以协同工作,主要用于API文档的生成和测试。Swagger是一个工具集,包括Swagger Editor和Swagger UI,它们可以帮助开发者设计、构建、文档化和使用RESTful web服务。Ubuntu是一个流行的Linux发行版,提供了稳定的环境和丰富的软件包管理工具。

在Ubuntu上安装Swagger

使用npm安装Swagger UI

  1. 安装Node.js和npm
sudo apt update
sudo apt install -y nodejs npm
  1. 下载并安装Swagger UI
wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.48.0.tar.gztar -xvf v3.48.0.tar.gz
cd swagger-ui-3.48.0
npm install
npm install -g http-server
http-server -p 8081

之后可以在浏览器中访问 http://localhost:8081 来使用Swagger UI。

使用Docker安装Swagger

  1. 安装Docker
sudo apt update
sudo apt install docker.io
  1. 拉取Swagger UI Docker镜像
docker pull swaggerapi/swagger-ui-express
  1. 运行Swagger UI容器
docker run -p 8080:8080 swaggerapi/swagger-ui-express

之后可以在浏览器中访问 http://localhost:8080 来使用Swagger UI。

在Ubuntu上集成Swagger与Spring Boot项目

  1. 创建Spring Boot项目: 使用Spring Initializr创建一个新的Spring Boot项目,并添加Spring Web和Springfox Swagger2依赖。

  2. 添加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>
  1. 配置Swagger: 创建一个配置类来启用Swagger并定义一些基本信息:
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();
    }
}
  1. 运行Spring Boot应用: 在终端中运行以下命令来启动Spring Boot应用:
./mvnw spring-boot:run
  1. 访问Swagger UI: 打开浏览器并访问 http://localhost:8080/swagger-ui.html,你应该能够看到你的API文档和测试界面。

通过以上步骤,你可以在Ubuntu上成功地将Swagger集成到Spring Boot项目中,并进行API文档的生成和测试。

0
看了该问题的人还看了