温馨提示×

Linux Swagger如何支持多语言API文档

小樊
47
2025-10-18 01:38:12
栏目: 智能运维

Linux环境下Swagger支持多语言API文档的实现方法

1. 基于Spring Boot+Springfox Swagger的国际化配置

适用于Java Spring Boot项目,通过Spring的国际化机制实现Swagger文档内容的动态切换。

  • 准备多语言资源文件:在src/main/resources目录下创建.properties格式的资源文件(如messages_en.propertiesmessages_zh_CN.properties),用键值对存储翻译内容。例如:
    messages_en.propertiesswagger.title=API Documentation
    messages_zh_CN.propertiesswagger.title=API文档
  • 配置Spring国际化:创建InternationalizationConfig类,定义MessageSource Bean加载资源文件:
    @Configuration
    public class InternationalizationConfig {
        @Bean
        public MessageSource messageSource() {
            ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
            messageSource.setBasename("classpath:messages"); // 资源文件路径
            messageSource.setDefaultEncoding("UTF-8");
            return messageSource;
        }
    }
    
  • 配置Swagger动态获取翻译:在Swagger配置类中,通过MessageSource获取当前语言的文本:
    @Bean
    public Docket api(LocaleResolver localeResolver) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title(messageSource.getMessage("swagger.title", null, LocaleContextHolder.getLocale()))
                        .description(messageSource.getMessage("swagger.description", null, LocaleContextHolder.getLocale()))
                        .build())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    
  • 配置Spring MVC本地化:添加WebConfig类支持请求头语言切换:
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
        @Bean
        public LocaleResolver localeResolver() {
            SessionLocaleResolver resolver = new SessionLocaleResolver();
            resolver.setDefaultLocale(Locale.US);
            return resolver;
        }
        @Bean
        public LocaleChangeInterceptor localeChangeInterceptor() {
            LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
            interceptor.setParamName("lang"); // 通过lang参数切换语言
            return interceptor;
        }
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(localeChangeInterceptor());
        }
    }
    
  • 测试:启动应用后访问http://localhost:8080/swagger-ui.html,通过?lang=zh参数切换语言,验证翻译是否生效。

2. 基于Swagger UI原生多语言支持

适用于直接使用Swagger UI的项目,通过配置Swagger UI的语言包实现界面多语言。

  • 安装Swagger UI:使用npm安装swagger-ui-dist包:
    npm install swagger-ui-dist --save
    
  • 配置Swagger UI语言:在HTML文件中引入Swagger UI脚本,并设置locale参数:
    <script src="node_modules/swagger-ui-dist/swagger-ui-bundle.js"></script>
    <script>
      window.onload = function() {
        const ui = SwaggerUIBundle({
          url: "your-api-spec.json",
          dom_id: '#swagger-ui',
          preset: 'swagger-ui',
          layout: 'StandaloneLayout',
          locale: "zh-CN", // 设置默认语言(支持en、zh-CN、fr等)
          deepLinking: true
        });
      };
    </script>
    
  • 扩展语言包:若需要自定义语言,可将Swagger UI的lang目录下的语言文件(如zh-CN.js)复制到项目中,修改翻译内容后引用。

3. 动态生成多语言API规范(适用于Node.js项目)

通过Node.js中间件根据请求头动态生成不同语言的OpenAPI规范,实现文档内容的实时切换。

  • 安装依赖:使用expressswagger-jsdoc创建项目:
    npm install express swagger-jsdoc --save
    
  • 创建多语言映射函数:定义getLocalizedTitlegetLocalizedDescription等函数,根据语言代码返回对应文本:
    const titles = { en: 'API Documentation', zh: 'API文档', ja: 'APIドキュメント' };
    const descriptions = { en: 'This is the API documentation.', zh: '这是API文档。', ja: 'これはAPIドキュメントです。' };
    function getLocalizedTitle(lang) { return titles[lang] || titles['en']; }
    function getLocalizedDescription(lang) { return descriptions[lang] || descriptions['en']; }
    
  • 动态生成OpenAPI规范:在Express路由中,根据Accept-Language请求头生成对应的规范:
    const express = require('express');
    const swaggerJsdoc = require('swagger-jsdoc');
    const app = express();
    app.get('/api-docs', (req, res) => {
      const acceptLanguage = req.headers['accept-language'] || 'en';
      const options = {
        definition: {
          openapi: '3.0.0',
          info: {
            title: getLocalizedTitle(acceptLanguage),
            description: getLocalizedDescription(acceptLanguage),
            version: '1.0.0'
          }
        },
        apis: ['./routes/*.js']
      };
      const specs = swaggerJsdoc(options);
      res.json(specs);
    });
    app.listen(3000, () => console.log('Server running on port 3000'));
    
  • 测试:访问http://localhost:3000/api-docs,通过修改请求头的Accept-Language字段(如zh-CN,zh;q=0.9)验证文档内容是否切换。

4. 使用Knife4j增强Swagger多语言支持

Knife4j是Swagger的增强工具,通过自定义配置实现界面多语言。

  • 集成Knife4j:在Spring Boot项目中添加Knife4j依赖:
    <dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>knife4j-springdoc-ui</artifactId>
      <version>3.0.3</version>
    </dependency>
    
  • 配置多语言资源文件:创建messages_zh_CN.properties等文件,存储界面文本翻译。
  • 启用Knife4j多语言:在Swagger配置类中,添加Knife4j的@EnableKnife4j注解,并配置资源文件路径:
    @Configuration
    @EnableKnife4j
    public class SwaggerConfig {
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.OAS_30)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    }
    
  • 测试:访问Knife4j的UI界面(如http://localhost:8080/doc.html),通过语言切换按钮验证界面多语言。

5. 使用Springdoc-openapi的多语言支持

Springdoc是新一代的Swagger工具,原生支持多语言,配置更简洁。

  • 添加依赖:在pom.xml中添加Springdoc依赖:
    <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>2.1.0</version>
    </dependency>
    
  • 配置多语言资源文件:创建messages.properties系列文件(如messages_en.propertiesmessages_zh_CN.properties),存储翻译内容。
  • 自定义OpenAPI信息:通过@Bean方法获取当前语言的文本,设置到OpenAPI对象中:
    @Bean
    public OpenAPI customOpenAPI(LocaleResolver localeResolver) {
        return new OpenAPI()
                .info(new Info()
                        .title(messageSource.getMessage("swagger.title", null, LocaleContextHolder.getLocale()))
                        .description(messageSource.getMessage("swagger.description", null, LocaleContextHolder.getLocale()))
                        .version("1.0.0"));
    }
    
  • 配置请求本地化:添加WebConfig类支持请求头语言切换(同方法1)。
  • 测试:访问http://localhost:8080/swagger-ui/index.html,通过?lang=zh参数切换语言,验证文档内容。

0