You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Quarkus中Jakarta验证消息阿塞拜疆语本地化部分失效问题

解决Quarkus中Jakarta标准验证消息本地化失效问题

针对你遇到的自定义约束消息正常本地化,但Jakarta标准约束(如NotEmpty)仍显示英文的问题,可从以下几个方面排查修复:

1. 修复自定义插值器的键匹配逻辑

Jakarta Validation的标准约束消息模板是带大括号的占位符(比如{jakarta.validation.constraints.NotEmpty.message}),而你的资源包中使用的是不带大括号的键。当前插值器直接用带大括号的模板去匹配资源包键,导致无法命中,最终使用默认英文消息。

修改LocaleBasedMessageInterpolator的interpolate方法,先提取不带大括号的键再匹配:

@Override
public String interpolate(String messageTemplate, Context context, Locale locale) {
    Locale effectiveLocale = locale != null ? locale : Locale.getDefault();
    ResourceBundle bundle = ResourceBundle.getBundle("i18n.validation", effectiveLocale);
    
    // 提取消息模板中的实际键(去除前后大括号)
    String key = messageTemplate;
    if (messageTemplate.startsWith("{") && messageTemplate.endsWith("}")) {
        key = messageTemplate.substring(1, messageTemplate.length() - 1);
    }

    // 优先使用自定义资源包中的消息,否则保留原模板
    String localizedMessage = bundle.containsKey(key) ? bundle.getString(key) : messageTemplate;
    return defaultInterpolator.interpolate(localizedMessage, context, effectiveLocale);
}

2. 在Quarkus中注册自定义插值器

需要让Quarkus明确使用你的自定义插值器,在application.properties中添加配置:

quarkus.hibernate-validator.message-interpolator=com.your.package.LocaleBasedMessageInterpolator

注意替换com.your.package为你实际的类包路径。

3. 确保应用默认Locale设置为阿塞拜疆语

如果Locale.getDefault()未正确设置为阿塞拜疆语(az),会导致加载错误的资源包。可通过两种方式设置:

  • 在application.properties中配置全局默认Locale:
    quarkus.default-locale=az
    
  • 或在代码初始化时主动设置:
    @PostConstruct
    void initLocale() {
        Locale.setDefault(new Locale("az"));
    }
    

4. 验证资源包的命名与位置

确认validation_az.properties文件路径为src/main/resources/i18n/validation_az.properties,文件名无拼写错误(注意下划线分隔语言代码),且编译后该文件存在于classpath的i18n目录下。

完成以上调整后,标准约束的本地化消息应该能正常显示为阿塞拜疆语。

内容的提问来源于stack exchange,提问作者Maharramoff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 06:55:17