举例: 字段userId,想要在页面列表显示userName
自定义注解
-
代码展示
-
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface UserName { }
-
-
将注解放到类字段上
-
pubilc class User { @UserName private Integer userId; }
-
AOP
-
如果不了解AOP, 可搜索其他博客,熟悉AOP,再来食用
-
定义切面注解
-
/** * 需要置换的controller方法上 * * @author MLK */ @Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Conversion { }
-
-
定义切面类
-
代码展示
@Aspect @Component @Slf4j public class ConversionAspect { // 定义切点Pointcut @Pointcut("@annotation(com.micro.common.annotation.Conversion)") public void excudeService() { } @Around("excudeService()") public Object doAroundConversion(ProceedingJoinPoint pjp) { // 获得要返回的数据 Object res = pjp.proceed(); try { parseText(res); }catch (Exception e){ e.printStackTrace(); } return res; } }
-
parseText(res); 此方法,处理controller层返回前端页面的数据, 根据项目的返回格式,取列表data,
-
代码展示
private void parseText(Object result){ try { Iterator<Map.Entry<String, Object>> iterator = ((R) result).entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<String, Object> entry = iterator.next(); String key = entry.getKey(); Object value = entry.getValue(); // 判断分页, 我的分页数据是在rows if ("rows".equals(key)){ // 分页 List<JSONObject> items = new ArrayList<>(); ArrayList list = (ArrayList) value; for (Object o : list) { JSONObject jsonObject = jsonValue(o); items.add(jsonObject); } ((R) result).put(key,items); } }
-
jsonValue(o); 拿到具体的列表值,反射->获取注解
-
代码展示
public JSONObject jsonValue(Object record) { ObjectMapper mapper = new ObjectMapper(); String json = "{}"; try { json = mapper.writeValueAsString(record); } catch (JsonProcessingException e) { log.error("json解析失败" + e.getMessage(), e); } // 需要返回的数据 JSONObject item = JSONObject.parseObject(json); // Convert.getAllFields: 获取类的所有属性,包括父类 for (Field field : Convert.getAllFields(record)) { // 判断是否有UserName注解 if (field.getAnnotation(UserName.class) != null) { // 拿到字段 String fieldName = field.getName(); // 获取字段值 String fileValue = String.valueOf(item.get(fieldName)); // 值不为空,根据userId 获取userName String userName = queryUserNameByUserId(userId); item.put("userName", userName); } } return item; }
-