当前位置: 首页 > news >正文

SpringBoot 自定义字典翻译组件

本来想在项目里直接用Easy-Trans来做字典翻译,用的时候发现,这个组件不支持原生的mybatis.

于是直接自己写了一个。废话不多说,直接上代码。就两个文件。

import java.lang.annotation.*;/*** 字典翻译注解,用于实体类字段自动翻译*/
@Target(ElementType.FIELD) // 作用于字段
@Retention(RetentionPolicy.RUNTIME) // 运行时生效
@Documented
public @interface DictTrans {/** 字典key(对应Redis中的字典类型) */String dictKey();/** 目标翻译字段名(存储翻译结果的字段) */String targetField();
}

我这里是直接从redis中取出来进行字典进行翻译


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.geek.common.constant.CacheConstants;
import com.geek.common.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;/*** 字典翻译切面,自动处理@DictTrans注解的字段翻译*/
@Aspect
@Component
@Slf4j
public class DictTransAspect {@Resourceprivate RedisCache redisCache;/*** 切入点:拦截Service层所有返回实体/集合的方法* (根据实际工程调整包路径,确保覆盖业务Service)*/@AfterReturning(pointcut = "execution(* com.geek.system.service..*(..))", // 拦截system.service包下所有方法returning = "result" // 方法返回值)public void doDictTrans(Object result) {if (result == null) return;// 处理集合类型(List/Set等)if (result instanceof Collection<?>) {Collection<?> collection = (Collection<?>) result;collection.forEach(this::processEntity);} else {// 处理单个实体processEntity(result);}}/*** 处理单个实体对象的字典翻译*/private void processEntity(Object entity) {if (entity == null) return;Class<?> entityClass = entity.getClass();// 获取实体类所有字段(含父类私有字段)List<Field> allFields = getAllFields(entityClass);for (Field field : allFields) {// 检查字段是否标注@DictTrans注解DictTrans dictTrans = field.getAnnotation(DictTrans.class);if (dictTrans == null) continue;try {// 1. 获取源字段(编码字段)的值field.setAccessible(true); // 允许访问私有字段String sourceValue = (String) field.get(entity);if (sourceValue == null) continue; // 编码值为null则跳过// 2. 从Redis获取JSON数组字符串并解析为映射(修正类型不匹配问题)String dictKey = dictTrans.dictKey();String redisFullKey = CacheConstants.SYS_DICT_KEY + dictKey;// 直接获取JSONArray对象(无需字符串解析)JSONArray dictJsonArray = (JSONArray) redisCache.getCacheObject(redisFullKey);if (dictJsonArray == null || dictJsonArray.isEmpty()) {log.error("字典翻译失败:Redis中未找到键[{}]或JSON数组为空", redisFullKey);continue;}// 步骤3:构建dictValue -> dictLabel的映射Map<String, String> dictMap = new HashMap<>();for (int i = 0; i < dictJsonArray.size(); i++) {JSONObject dictItem = dictJsonArray.getJSONObject(i);String dictValue = dictItem.getString("dictValue");String dictLabel = dictItem.getString("dictLabel");dictMap.put(dictValue, dictLabel);}// 获取翻译后的值(补充缺失步骤)String translatedValue = dictMap.get(sourceValue);if (translatedValue == null) {log.warn("字典翻译警告:字典key[{}]中无编码[{}]的映射", dictKey, sourceValue);}// 4. 反射设置目标字段(翻译结果字段)的值String targetFieldName = dictTrans.targetField();Field targetField = entityClass.getDeclaredField(targetFieldName);targetField.setAccessible(true);targetField.set(entity, translatedValue);} catch (NoSuchFieldException e) {log.error("字典翻译反射异常:目标字段[{}]不存在", dictTrans.targetField(), e);} catch (IllegalAccessException e) {log.error("字典翻译反射异常:字段访问权限不足", e);}}}/*** 获取类的所有字段(含父类私有字段)*/private List<Field> getAllFields(Class<?> clazz) {List<Field> fields = new ArrayList<>();while (clazz != null && clazz != Object.class) { // 遍历至Object类停止fields.addAll(Arrays.asList(clazz.getDeclaredFields()));clazz = clazz.getSuperclass(); // 处理父类字段}return fields;}
}

使用方式,直接在实体字段上用注解  @DictTrans   

dictKey是对应的字典的key 
targetField是翻译后映射的字段
    @DictTrans(dictKey = "transaction_type", targetField = "transactionTypeName")private String transactionType ;private String transactionTypeName;

http://www.dtcms.com/a/420733.html

相关文章:

  • Interview-SpringCloud/SpringBoot
  • 爱站网ip反查域名京东官方网上商城
  • 做网站要不要营业执照网站大全网址大全
  • 济南网站建设yigeseo南充市网站建设
  • wordpress 经典博客主题济南seo怎么优化
  • 网站改版引导站内营销推广途径
  • 贵州建设学校网站乌海seo
  • 如何优化网站目录结构广州各区风险区域最新动态
  • 广西和城乡建设厅网站作品集怎么做网页
  • wordpress动漫网站做电影网站怎样赚钱吗
  • 南山做网站推广乐云seo娄底优秀网站建设
  • flask做网站工具网站建设罗贤伟
  • 永川网站建设公司网站该如何做
  • 网站建设的视频教程导视设计方法
  • CKAD-CN 考试知识点分享(18) Secret - 2
  • 一般做网站多少钱无极游戏网
  • Python快速入门专业版(四十九):Python异常基础:什么是异常?常见异常类型与触发场景
  • 如何找到网站管理员广东粤建设计院网站
  • 网站建设竞价托管外包注册域名多长时间
  • 网站建设 腾邢台发布网
  • 北仑网站网页建设公司自己做网站吗
  • OpenMP并行化编程指南
  • 网站建设公司工资设置时间线 wordpress
  • 免费网站管理软件广告策划案ppt优秀案例
  • 制作网站报价单h5易企秀官网
  • 建设机械网站案例分析福建seo外包
  • AI任务相关解决方案19-一种基于多技术融合的智能医学外科决策与执行系统,外科Agent在胆囊切除术
  • 淘宝做seo要建网站吗dede网站搬家更换空间重新安装
  • SpringAop的快速入门
  • 检测网站访问量电脑做网站用word