温馨提示×

CentOS Swagger如何进行国际化支持

小樊
34
2025-12-25 13:18:33
栏目: 智能运维

在CentOS系统中,Swagger的国际化支持可以通过以下步骤实现:

1. 准备工作

确保你已经安装了Swagger,并且有一个运行中的Spring Boot应用。

2. 添加国际化资源文件

src/main/resources目录下创建多个语言的资源文件,例如:

  • messages_en.properties (英文)
  • messages_zh_CN.properties (简体中文)

在这些文件中定义你的国际化消息键值对。

messages_en.properties:

greeting=Hello
welcome=Welcome to our API

messages_zh_CN.properties:

greeting=你好
welcome=欢迎使用我们的API

3. 配置Spring Boot国际化

application.propertiesapplication.yml中配置国际化资源文件的位置:

application.properties:

spring.messages.basename=messages

application.yml:

spring:
  messages:
    basename: messages

4. 配置Swagger国际化

在Swagger配置类中添加国际化支持。你需要创建一个LocaleResolver来解析请求的区域设置,并将其应用到Swagger UI中。

创建LocaleResolver

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.US);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}

配置Swagger国际化

在你的Swagger配置类中,注入LocaleResolver并使用它来设置Swagger UI的区域设置。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;
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;

import java.util.Locale;

@Component
@EnableSwagger2
public class SwaggerConfig {

    @Autowired
    private MessageSource messageSource;

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yourpackage"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Your API Title")
                .description("Your API Description")
                .version("1.0.0")
                .contact(new Contact("Your Name", "https://yourwebsite.com", "your.email@example.com"))
                .build();
    }

    public String getLocalizedMessage(String code) {
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage(code, null, locale);
    }
}

5. 修改Swagger UI模板

如果你使用的是自定义的Swagger UI模板,可以在模板中添加国际化支持。例如,在swagger-ui.html中:

<!DOCTYPE html>
<html>
<head>
    <title>{{ getLocalizedMessage('swagger.title') }}</title>
    <!-- 其他头部信息 -->
</head>
<body>
    <div id="swagger-ui"></div>
    <script src="webjars/springfox-swagger-ui/swagger-ui-bundle.js"></script>
    <script src="webjars/springfox-swagger-ui/swagger-ui-standalone-preset.js"></script>
    <script>
        window.onload = function() {
            const ui = SwaggerUIBundle({
                url: "{{ swaggerUrl }}",
                dom_id: '#swagger-ui',
                deepLinking: true,
                presets: [
                    SwaggerUIBundle.presets.apis,
                    SwaggerUIStandalonePreset
                ],
                plugins: [
                    SwaggerUIBundle.plugins.DownloadUrl
                ],
                layout: "StandaloneLayout"
            });

            window.ui = ui;
        };
    </script>
</body>
</html>

6. 测试国际化

启动你的Spring Boot应用,并访问Swagger UI页面。通过URL参数lang=enlang=zh_CN来切换语言,查看国际化效果。

通过以上步骤,你可以在CentOS系统中为Swagger实现国际化支持。

0