前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot 国际化处理

springboot 国际化处理

作者头像
用户9131103
发布2023-09-01 18:38:25
3470
发布2023-09-01 18:38:25
举报
文章被收录于专栏:工作经验工作经验
代码语言:javascript
复制
package com.ruoyi.common.i18n;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.util.PropertyPlaceholderHelper;

import com.ruoyi.common.utils.ReflectASMUtils;
import com.ruoyi.common.utils.SpringUtils;
import com.ruoyi.common.utils.StringUtils;

public class I18nUtils {

    private final static MessageSource messageSource = SpringUtils
            .getBean(AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME);

    private static final PropertyPlaceholderHelper FieldPlaceholderHelper = new PropertyPlaceholderHelper("#{", "}");

    private static final PropertyPlaceholderHelper PlaceholderHelper = new PropertyPlaceholderHelper("{", "}", ":",
            true);

    public static void replaceI18nFields(List<?> objs) {
        replaceI18nFields(objs, LocaleContextHolder.getLocale());
    }

    /**
     * 将列表所有对象中@I18nField标注的字段替换为指定国际化语言值
     * 
     * @param objs
     * @param locale
     */
    public static void replaceI18nFields(List<?> objs, Locale locale) {
        if (Objects.isNull(objs)) {
            return;
        }
        objs.forEach(obj -> replaceI18nFields(obj, locale));
    }

    public static void replaceI18nFields(Object obj) {
        replaceI18nFields(obj, LocaleContextHolder.getLocale());
    }

    /**
     * 将对象有@I18nField标注的字段替换为指定国际化语言值
     * 
     * @param obj
     * @param locale
     */
    public static void replaceI18nFields(Object obj, Locale locale) {
        if (Objects.isNull(obj)) {
            return;
        }
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.isAnnotationPresent(I18nField.class)) {
                I18nField i18nField = field.getAnnotation(I18nField.class);
                try {
                    if (StringUtils.isNotEmpty(i18nField.value())) {
                        String langStr = i18nField.value();
                        // 先将#{fieldName}占位替换为obj字段值
                        langStr = FieldPlaceholderHelper.replacePlaceholders(langStr, placehoderName -> {
                            Object fieldV = ReflectASMUtils.invokeGetter(obj, placehoderName);
                            return Objects.nonNull(fieldV) ? fieldV.toString() : StringUtils.EMPTY;
                        });
                        String langValue = get(langStr, locale);
                        ReflectASMUtils.invokeSetter(obj, field.getName(), langValue);
                    } else {
                        Object fieldV = ReflectASMUtils.invokeGetter(obj, field.getName());
                        if (Objects.nonNull(fieldV)) {
                            String langKey = fieldV.toString();
                            String langValue = get(langKey, locale);
                            ReflectASMUtils.invokeSetter(obj, field.getName(), langValue);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取国际化键名对应的当前默认语言值
     * 
     * @param str
     * @return
     */
    public static String get(String str) {
        return get(str, LocaleContextHolder.getLocale());
    }

    /**
     * 获取国际化键名指定的语言值
     * 
     * @param str
     * @param locale
     * @param args
     * @return
     */
    public static String get(String str, Locale locale, Object... args) {
        if (StringUtils.isEmpty(str)) {
            return str;
        }
        return PlaceholderHelper.replacePlaceholders(str, langKey -> messageSource.getMessage(langKey, args, locale));
    }
}

代码语言:javascript
复制
package com.jinw.cms.i18n;

import com.jinw.utils.cms.StringUtils;

import java.lang.annotation.*;

/**
 * 类字段添加此注释,根据国际化字典表获取当前语言环境翻译.@see I18nUtils.replaceI18nFields
 *
 * @author liux
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface I18nField {

    /**
     * 国际化表键名,为空时使用字段值获取当前语言环境值
     * <p>
     * 可使用占位符来获取当前对象其他字段属性值,例如实体类的ID字段值,可使用#{fieldName},大括号内是字段名,会被替换为指定字段的值。
     * </p>
     */
    public String value() default StringUtils.EMPTY;
}
代码语言:javascript
复制
spring:
  # 资源信息
  messages:
    encoding: utf-8
    # 国际化资源文件路径(配置文件路径)
    basename: i18n/messages
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-08-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档