字典注解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Dict {
String dictType();
String dictLabel() default "";
}
定义切面拦截controller接口
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.daimler.cg.common.lib.base.util.common.ResponseBean;
import com.daimler.cg.imp.client.currency.Dict;
import com.daimler.cg.imp.sysdict.service.SysDictService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Aspect
@Component
@Slf4j
public class DictAspect {
//表对应字段加上DictLabel即可显示出文本
private static String DICT_TEXT_SUFFIX = "_DictLabel";
@Resource
private SysDictService dictService;
/**
* 定义切点Pointcut拦截所有对服务器的请求
*/
// @Pointcut("execution(* com.daimler..controller..*(..))")
// public void excudeService() {
// }
/**
* 这是触发DictionariesService的时候会执行的,在环绕通知中目标对象方法被调用后的结果进行再处理
* @Around("excudeService()")
*/
@Around("@annotation(InterceptInterface)")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
log.error("{}",pjp);
//这是定义开始事件
long time1 = System.currentTimeMillis();
//这是方法并获取返回结果
Object result = pjp.proceed();
//这是获取到结束时间
long time2 = System.currentTimeMillis();
log.info("获取JSON数据耗时:" + (time2 - time1) + "ms");
//解析开始时间
long start = System.currentTimeMillis();
//开始解析(翻译字段内部的值凡是打了@Dict这玩意的都会被翻译)
this.parsedictLabel(result);
//解析结束时间
long end = System.currentTimeMillis();
log.info("解析注入JSON数据耗时:" + (end - start) + "ms");
return result;
}
private void parsedictLabel(Object result) {
if (result instanceof ResponseBean) {
List<JSONObject> items = new ArrayList<>();
Map<String, List<JSONObject>> objects = new HashMap<>();
Map<String, JSONObject> jsonObject = new HashMap<>();
ResponseBean responseBean = (ResponseBean) result;
// 获取实际数据 ResponseBean.getData
Object data = responseBean.getData();
// 处理data没有json数据问题
if (Objects.isNull(data)) {
return;
}
// 处理data是个集合
if (data instanceof List) {
for (Object object : (List<?>) data) {
String json = convertJson(object);
items.add(getDictAnnotation(json, object));
}
responseBean.setData(items);
// 处理是map集合问题
} else if (data instanceof Map) {
//Object转Map
Map<String, Object> map = JSONObject.parseObject(JSON.toJSONString(data));
map.keySet().forEach(key -> {
// 处理map value是集合问题
if (map.get(key) instanceof List) {
for (Object object : (List<?>) data) {
String json = convertJson(object);
objects.put(key, Collections.singletonList(getDictAnnotation(json, object)));
}
responseBean.setData(objects);
// 处理map value是对象问题
} else {
Object object = map.get(key);
String json = convertJson(object);
jsonObject.put(key, getDictAnnotation(json, object));
}
responseBean.setData(jsonObject);
});
// 处理是对象问题
} else {
String json = convertJson(data);
JSONObject item = getDictAnnotation(json, data);
items.add(item);
responseBean.setData(item);
}
}
}
/**
* 翻译字典文本
*/
private String translateDictValue(String dictType, String key) {
//如果key为空直接返回就好了
if (isEmpty(key)) {
return "";
}
StringBuffer textValue = new StringBuffer();
//分割key值
String[] keys = key.split(",");
//循环keys中的所有值
for (String k : keys) {
String tmpValue = null;
log.debug("字典key:" + k);
if (k.trim().length() == 0) {
continue; //跳过循环
}
tmpValue = dictService.getDictNameByCodeAndType(dictType, key);
if (tmpValue != null) {
if (!"".equals(textValue.toString())) {
textValue.append(",");
}
textValue.append(tmpValue);
}
}
//返回翻译的值
return textValue.toString();
}
public static Field[] getAllFields(Object object) {
Class<?> clazz = object.getClass();
List<Field> fieldList = new ArrayList<>();
while (clazz != null) {
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();
}
Field[] fields = new Field[fieldList.size()];
fieldList.toArray(fields);
return fields;
}
public static boolean isEmpty(Object object) {
return object == null || "".equals(object) || "null".equals(object);
}
public JSONObject getDictAnnotation(String json, Object object) {
JSONObject item = JSONObject.parseObject(json);
//解决继承实体字段无法翻译问题
for (Field field : getAllFields(object)) {
//解决继承实体字段无法翻译问题
//如果该属性上面有@Dict注解,则进行翻译
if (field.getAnnotation(Dict.class) != null) {
//拿到注解的dictType属性的值
String dictType = field.getAnnotation(Dict.class).dictType();
//拿到注解的dictLabel属性的值
String text = field.getAnnotation(Dict.class).dictLabel();
//获取当前待翻译的值
String key = String.valueOf(item.get(field.getName()));
//翻译字典值对应的text值
String textValue = translateDictValue(dictType, key);
//DICT_TEXT_SUFFIX的值为,是默认值:
//public static final String DICT_TEXT_SUFFIX = "_dictLabel";
log.debug("字典Val: " + textValue);
log.debug("翻译字典字段:" + field.getName() + DICT_TEXT_SUFFIX + ": " + textValue);
//如果给了文本名
if (!StringUtils.isBlank(text)) {
item.put(text, textValue);
} else {
//走默认策略
item.put(field.getName() + DICT_TEXT_SUFFIX, textValue);
}
}
}
return item;
}
public String convertJson(Object object) {
ObjectMapper mapper = new ObjectMapper();
String json = "{}";
try {
//解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
json = mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
log.error("Json解析失败:" + e);
}
return json;
}
解决拦截所有的请求耗时过长问题
@Pointcut("execution(* com.daimler..controller..*(..))") public void excudeService() {}
自定义切面注解来拦截莫一个controller接口
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 拦截controller接口数据进行翻译
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InterceptInterface {
}