ubuntu

Ubuntu Swagger配置有哪些技巧

小樊
45
2025-04-03 07:00:11
栏目: 智能运维

在Ubuntu上配置Swagger的技巧主要包括安装和配置Swagger Editor和Swagger UI,以及使用Springfox自动化生成API文档。以下是详细的步骤和技巧:

安装Swagger Editor和Swagger UI

  1. 安装Node.js和npm

    sudo apt update
    sudo apt install -y nodejs npm
    
  2. 安装Swagger Editor

    mkdir -p /opt/swagger
    cd /opt/swagger
    wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.16.1.tar.gz
    tar -xvf v3.16.1.tar.gz
    rm v3.16.1.tar.gz
    cd Swagger-editor-3.16.1
    npm install
    
  3. 启动Swagger Editor

    node index.js
    

    然后在浏览器中访问 http://localhost:8081

  4. 安装Swagger UI

    mkdir -p /opt/swagger
    cd /opt/swagger
    wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.48.0.tar.gz
    tar -xvf v3.48.0.tar.gz
    rm v3.48.0.tar.gz
    cd swagger-ui-3.48.0
    npm install
    
  5. 启动Swagger UI

    node index.js
    

    然后在浏览器中访问 http://localhost:8080

使用Springfox自动化生成API文档

  1. 添加Springfox依赖: 在 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: 创建一个配置类,例如 SwaggerConfig.java

    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.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    }
    
  3. 访问Swagger UI: 启动Spring Boot应用后,在浏览器中访问 http://localhost:8080/swagger-ui/,然后输入配置文件中指定的Swagger JSON文件地址。

其他技巧

通过以上步骤和技巧,你可以在Ubuntu上高效地配置和管理Swagger,提升前后端开发的协作效率。

0
看了该问题的人还看了