• 两个类文件,实现根据返回的id显示对应的人员信息增强返回


    后台与前台交互时,由于后台存放的原始信息可能就是一些id或code,要经过相应的转换才能很好地在前台展示。

    比如: select id, user_id from user

    直接返回给前台时,前台可能要根据你这个user_id作为参数,再请求一次后台,获取对应的人员信息实体,以作人员信息展示。

    这样多了一次IO,同时还要根据不同的场景写很多的重复代码。比如第一次IO时就连接查出对应的返回实体,或者本来不需要后续又需要这些实体就又要补上代码。

    这些重复性的工作抽像出通用的代码解决,我的做法是这样:

    1、首先我的人员信息是有缓存的

    2、自定义一个注解@BaseId(第一个类文件)

    3、写一个AOP(第二个类文件)

    这个AOP在@Controller方法返回前,校验返回的实体是固定的泛型且泛型参数对应的实体类中存在被@BaseId注解的变量,就基于这个变量生成一个人员信息实体,加进这个返回实体中返回给前台。下面且看代码:

    一、注解类

    1. @Target(ElementType.FIELD)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. public @interface BaseId {
    5. }

    二、AOP类

    1. /**
    2. * 对GetMapping接口的返回做条件性增强,
    3. * 1、返回的类型为TableDataInfo的。里面的rows对应的实体类如果有@BaseId的,增加对应的StaffMain字段返回
    4. *
    5. * @author wack
    6. * @version 1.0
    7. * @since 2023/8/3
    8. */
    9. @Aspect
    10. @Slf4j
    11. @Component
    12. public class GetResponseAspect {
    13. private static final String STAFF_MAIN = "xxx.xxx.basis.model.staff.StaffMain";
    14. @Autowired
    15. private IStaffService staffService;
    16. @AfterReturning(pointcut = "@annotation(getMapping)", returning = "jsonResult")
    17. public void beforeReturnIng(JoinPoint joinPoint, Object jsonResult, GetMapping getMapping) throws ClassNotFoundException {
    18. if (jsonResult instanceof TableDataInfo) {
    19. List rows = ((TableDataInfo) jsonResult).getRows();
    20. List newRows = new ArrayList();
    21. if (CollectionUtils.isNotEmpty(rows) && rows.get(0) != null) {
    22. Class returnModel = rows.get(0).getClass();
    23. Field[] declaredFields = returnModel.getDeclaredFields();
    24. if (Arrays.stream(declaredFields).filter(obj -> obj.getAnnotation(BaseId.class) != null).findAny().isPresent()) {
    25. for (Object row : rows) {
    26. // 找到注解为baseId的字段,生成一个新的StaffMain 字段来承载对应的人员信息
    27. DynamicObject dynamicBean = new DynamicObject();
    28. Map allPropertyType = dynamicBean.getAllPropertyType(row);
    29. Map allPropertyValue = dynamicBean.getAllPropertyValue(row);
    30. for (Field declaredField : declaredFields) {
    31. if (declaredField.getAnnotation(BaseId.class) != null) {
    32. String fieldValue = ReflectUtils.getFieldValue(row, declaredField.getName());
    33. allPropertyType.put(declaredField.getName() + "Staff", Class.forName(STAFF_MAIN));
    34. allPropertyValue.put(declaredField.getName() + "Staff", staffService.getStaffCacheInfo(fieldValue));
    35. }
    36. }
    37. dynamicBean.addProperty(allPropertyType, allPropertyValue);
    38. row = dynamicBean.getObject();
    39. newRows.add(row);
    40. }
    41. if (CollectionUtils.isNotEmpty(newRows)) ((TableDataInfo) jsonResult).setRows(newRows);
    42. }
    43. }
    44. }
    45. }
    46. class DynamicObject {
    47. private Object object; //对象
    48. private BeanMap beanMap; //对象的属性
    49. private BeanGenerator beanGenerator; //对象生成器
    50. private Map allProperty; //对象的<属性名, 属性名对应的类型>
    51. /**
    52. * 给对象属性赋值
    53. *
    54. * @param property
    55. * @param value
    56. */
    57. public void setValue(String property, Object value) {
    58. beanMap.put(property, value);
    59. }
    60. private void setValue(Object object, Map property) {
    61. for (String propertyName : property.keySet()) {
    62. if (allProperty.containsKey(propertyName)) {
    63. Object propertyValue = ReflectUtils.getFieldValue(object, propertyName);
    64. this.setValue(propertyName, propertyValue);
    65. }
    66. }
    67. }
    68. private void setValue(Map propertyValue) {
    69. for (Map.Entry entry : propertyValue.entrySet()) {
    70. this.setValue(entry.getKey(), entry.getValue());
    71. }
    72. }
    73. /**
    74. * 通过属性名获取属性值
    75. *
    76. * @param property
    77. * @return
    78. */
    79. public Object getValue(String property) {
    80. return beanMap.get(property);
    81. }
    82. /**
    83. * 获取该bean的实体
    84. *
    85. * @return
    86. */
    87. public Object getObject() {
    88. return this.object;
    89. }
    90. private Object generateObject(Map propertyMap) {
    91. if (null == beanGenerator) {
    92. beanGenerator = new BeanGenerator();
    93. }
    94. Set keySet = propertyMap.keySet();
    95. for (Iterator i = keySet.iterator(); i.hasNext(); ) {
    96. String key = (String) i.next();
    97. beanGenerator.addProperty(key, (Class) propertyMap.get(key));
    98. }
    99. return beanGenerator.create();
    100. }
    101. /**
    102. * 添加属性名与属性值
    103. *
    104. * @param propertyType
    105. * @param propertyValue
    106. */
    107. public void addProperty(Map propertyType, Map propertyValue) {
    108. if (null == propertyType) {
    109. throw new RuntimeException("动态添加属性失败!");
    110. }
    111. Object oldObject = object;
    112. object = generateObject(propertyType);
    113. beanMap = BeanMap.create(object);
    114. if (null != oldObject) {
    115. setValue(oldObject, allProperty);
    116. }
    117. setValue(propertyValue);
    118. if (null == allProperty) {
    119. allProperty = propertyType;
    120. } else {
    121. allProperty.putAll(propertyType);
    122. }
    123. }
    124. /**
    125. * 获取对象中的所有属性名与属性值
    126. *
    127. * @param object
    128. * @return
    129. * @throws ClassNotFoundException
    130. */
    131. public Map getAllPropertyType(Object object) throws ClassNotFoundException {
    132. Map map = new HashMap<>();
    133. Field[] fields = object.getClass().getDeclaredFields();
    134. for (int index = 0; index < fields.length; index++) {
    135. Field field = fields[index];
    136. String propertyName = field.getName();
    137. String typeName = field.getGenericType().getTypeName();
    138. if ("long".equals(typeName)) {
    139. typeName = "java.lang.Long";
    140. }
    141. if ("int".equals(typeName)) {
    142. typeName = "java.lang.Integer";
    143. }
    144. if ("float".equals(typeName)) {
    145. typeName = "java.lang.Float";
    146. }
    147. if ("double".equals(typeName)) {
    148. typeName = "java.lang.Double";
    149. }
    150. if ("boolean".equals(typeName)) {
    151. typeName = "java.lang.Boolean";
    152. }
    153. if ("char".equals(typeName)) {
    154. typeName = "java.lang.Character";
    155. }
    156. if (typeName.indexOf("List") > -1) {
    157. typeName = "java.util.List";
    158. }
    159. Class propertyType = Class.forName(typeName);
    160. map.put(propertyName, propertyType);
    161. }
    162. defaultEndType(map);
    163. return map;
    164. }
    165. private void defaultEndType(Map map) {
    166. map.put("createId", String.class);
    167. map.put("modifyId", String.class);
    168. map.put("createDate", Date.class);
    169. map.put("modifyDate", Date.class);
    170. }
    171. /**
    172. * 获取对象中的所有属性名与属性值
    173. *
    174. * @param object
    175. * @return
    176. */
    177. public Map getAllPropertyValue(Object object) {
    178. Map map = new HashMap<>();
    179. Field[] fields = object.getClass().getDeclaredFields();
    180. for (int index = 0; index < fields.length; index++) {
    181. Field field = fields[index];
    182. String propertyName = field.getName();
    183. Object propertyValue = ReflectUtils.getFieldValue(object, propertyName);
    184. map.put(propertyName, propertyValue);
    185. }
    186. defaultEndValue(object,map);
    187. return map;
    188. }
    189. private void defaultEndValue(Object object,Map map) {
    190. map.put("createId", ReflectUtils.getFieldValue(object, "createId"));
    191. map.put("modifyId", ReflectUtils.getFieldValue(object, "modifyId"));
    192. map.put("createDate", ReflectUtils.getFieldValue(object, "createDate"));
    193. map.put("modifyDate", ReflectUtils.getFieldValue(object, "modifyDate"));
    194. }
    195. }
    196. }

    在实体类中加注解

  • 相关阅读:
    【0day】复现海康威视综合安防管理平台信息泄露(内网集权账户密码)漏洞
    《国际服务贸易》期末复习题 及答案参考
    你知道电子招标最突出的5大好处有哪些吗?
    python中的运算符
    柯桥成人英语培训机构哪家好,新陈代谢到底是什么?
    曲线艺术编程 coding curves 第六章 平托图 (Pintographs)
    StarRocks实战——云览科技存算分离实践
    一文搞懂PKI/CA
    2. 计算WPL
    Basis运维日常检查清单- Checklist
  • 原文地址:https://blog.csdn.net/h15915793385/article/details/132694264