Linux环境下Swagger支持多语言API文档的实现方法
适用于Java Spring Boot项目,通过Spring的国际化机制实现Swagger文档内容的动态切换。
src/main/resources目录下创建.properties格式的资源文件(如messages_en.properties、messages_zh_CN.properties),用键值对存储翻译内容。例如:messages_en.properties:swagger.title=API Documentationmessages_zh_CN.properties:swagger.title=API文档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;
}
}
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();
}
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参数切换语言,验证翻译是否生效。适用于直接使用Swagger UI的项目,通过配置Swagger UI的语言包实现界面多语言。
swagger-ui-dist包:npm install swagger-ui-dist --save
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>
lang目录下的语言文件(如zh-CN.js)复制到项目中,修改翻译内容后引用。通过Node.js中间件根据请求头动态生成不同语言的OpenAPI规范,实现文档内容的实时切换。
express和swagger-jsdoc创建项目:npm install express swagger-jsdoc --save
getLocalizedTitle、getLocalizedDescription等函数,根据语言代码返回对应文本: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']; }
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)验证文档内容是否切换。Knife4j是Swagger的增强工具,通过自定义配置实现界面多语言。
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-springdoc-ui</artifactId>
<version>3.0.3</version>
</dependency>
messages_zh_CN.properties等文件,存储界面文本翻译。@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();
}
}
http://localhost:8080/doc.html),通过语言切换按钮验证界面多语言。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.properties、messages_zh_CN.properties),存储翻译内容。@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参数切换语言,验证文档内容。