1、类注解
/**
* 需要动态查询CodeTable数据字典时,在类上配置该注解
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CodeAnnotation {
}
2、字段注解
/**
* 需要动态查询CodeTable数据字典时,在对应str属性上配置该注解
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CodeAnnotationProperties {
String codeKeyProperties();
String codeType();
}
3、Aspectj
@Aspect
@Component
public class CodeAspect {
@Autowired
private CodeTableService codeTableService;
/**
* 自动属性值注入
*/
@AfterReturning(value = "execution(* com.lujie.source.mode..service.*.*(..)) || execution(* com.lujie.common.service.BaseService.*(..))", returning = "res")
public void serviceReturn(JoinPoint joinPoint, Object res) throws Exception {
if (ObjectUtil.isEmpty(res)) {
return;
}
//是否为集合
Boolean isList = res instanceof List ? true : false;
Object obj = isList ? ((List<?>) res).get(0) : res;
Class objClass = obj.getClass();
Annotation[] allAnnos = objClass.getAnnotations();
//若类标注了 @CodeAnnotation
if (Arrays.stream(allAnnos).anyMatch(i -> i.annotationType() == CodeAnnotation.class)) {
Field[] fields = objClass.getDeclaredFields();
//遍历所有字段
for (Field field : fields) {
//若字段标注了 @CodeAnnotationProperties
if (Arrays.stream(field.getAnnotations()).anyMatch(i -> i.annotationType() == CodeAnnotationProperties.class)) {
//获取标注类型
CodeAnnotationProperties codeAnnotationProperties = field.getAnnotation(CodeAnnotationProperties.class);
String codeType = codeAnnotationProperties.codeType();
List<CodeTable> codeTableList = codeTableService.findByType(codeType);
if (isList) {
for (Object sub : (List) res) {
setValue(fields, field, sub, codeTableList);
}
} else {
setValue(fields, field, res, codeTableList);
}
}
}
}
}
/**
* @param fields 字段集合
* @param field 字段str
* @param sub 对象
* @throws Exception
*/
public void setValue(Field[] fields, Field field, Object sub, List<CodeTable> codeTableList) throws Exception {
CodeAnnotationProperties codeAnnotationProperties = field.getAnnotation(CodeAnnotationProperties.class);
String codeKeyProperties = codeAnnotationProperties.codeKeyProperties();
//寻找key
for (Field field2 : fields) {
if (field2.getName().equals(codeKeyProperties)) {
field2.setAccessible(true);
Object obj2 = field2.get(sub);
CodeTable codeTable = codeTableList.stream().filter(i -> i.getCodeKey().equals(String.valueOf(obj2))).findFirst().orElse(null);
//将值设置到str字段中
field.setAccessible(true);
field.set(sub, (ObjectUtil.isNotEmpty(codeTable) ? codeTable.getCodeName() : null));
}
}
}
}
标签:codeTableList,fields,自定义,res,field,CodeAnnotationProperties,注解,sub
From: https://www.cnblogs.com/yifanSJ/p/17824479.html