springboot项目 字典/枚举翻译 终极解决方案 AOP+自定义注解+递归实体字段+实体动态三级缓存+责任链+多种转换方式
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface Dict {
String type() default "";
}
@Aspect
@Component
public class DictAspect {
@Autowired
private DictService dictService;
@Around("@annotation(dict)")
public Object around(ProceedingJoinPoint joinPoint, Dict dict) throws Throwable {
Object result = joinPoint.proceed();
if (result instanceof Collection) {
Collection<?> collection = (Collection<?>) result;
translateCollection(collection, dict);
} else if (result != null) {
translateObject(result, dict);
}
return result;
}
private void translateCollection(Collection<?> collection, Dict dict) throws IllegalAccessException {
for (Object obj : collection) {
translateObject(obj, dict);
}
}
private void translateObject(Object obj, Dict dict) throws IllegalAccessException {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Dict.class)) {
Dict fieldDict = field.getAnnotation(Dict.class);
String type = fieldDict.type();
if (!type.isEmpty()) {
field.setAccessible(true);
Object value = field.get(obj);
if (value != null) {
String translated = dictService.translate(type, value.toString());
field.set(obj, translated);
}
}
} else if (DictUtils.isComplexType(field.getType())) {
Object fieldValue = field.get(obj);
if (fieldValue != null) {
translateObject(fieldValue, dict);
}
}
}
}
}
// 使用示例
public class User {
@Dict(type = "userStatus")
private Integer status;
// getters and setters
}
// 服务调用
public interface DictService {
String translate(String type, String code);
}
// 实现类
@Service
public class DictServiceImpl implements DictService {
@Override
public String translate(String type, String code) {
// 实现字典翻译逻辑
return "翻译后的值";
}
}
这个代码示例展示了如何使用Spring AOP和自定义注解来实现字典翻译的功能。DictAspect
类中的\`a
评论已关闭