Example: field userId, want to display userName in the page list

Custom annotations

  • Introduction to Java annotations Retention, Documented, and Target

  • The code shown

    • @Target(ElementType.FIELD)
      @Retention(RetentionPolicy.RUNTIME)
      public @interface UserName {
      	
      }
      Copy the code
  • Place the annotation on the class field

    • pubilc class User {
          
          @UserName
      	private Integer userId;
      }
      Copy the code

AOP

  • If you don’t know AOP, search other blogs, and familiarize yourself with AOP, as well as reflection, before eating

  • Define section annotations

    • /** ** on the controller method that needs to be replaced@author MLK
       */
      @Target({ElementType.PARAMETER, ElementType.METHOD})
      @Retention(RetentionPolicy.RUNTIME)
      @Documented
      public @interface Conversion {
      }
      Copy the code
  • Define the aspect class

    • The code shown

      @Aspect
      @Component
      @Slf4j
      public class ConversionAspect {
      
          // Define Pointcut Pointcut
          @Pointcut("@annotation(com... Conversion)")
          public void excudeService(a) {}@Around("excudeService()")
          public Object doAroundConversion(ProceedingJoinPoint pjp) {
              // Get the data to return
              Object res = pjp.proceed();
              try {
                  parseText(res);
              }catch (Exception e){
                  e.printStackTrace();
              }
              returnres; }}Copy the code
    • parseText(res); This method handles the data returned by the controller layer to the front-end page. According to the return format of the project, the list data is fetched.

    • The code shown

      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();
                    	
                      // Check paging, my paging data is in rows
                      if ("rows".equals(key)){
                          / / paging
                          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); }}Copy the code
    • jsonValue(o); To get the specific list value, reflect -> get the annotation

    • The code shown

      public JSONObject jsonValue(Object record) {
              ObjectMapper mapper = new ObjectMapper();
              String json = "{}";
              try {
                  json = mapper.writeValueAsString(record);
              } catch (JsonProcessingException e) {
                  log.error("Json parsing failed" + e.getMessage(), e);
              }
          	// The data to be returned
              JSONObject item = JSONObject.parseObject(json);
          	// convert. getAllFields: Gets all attributes of the class, including the parent class
          	for (Field field : Convert.getAllFields(record)) {
                  // Check if there is a UserName annotation
                  if(field.getAnnotation(UserName.class) ! =null) {
                      // Get the field
                      String fieldName = field.getName();
                      // Get the field value
                      String fileValue = String.valueOf(item.get(fieldName));
                      // The value is not empty. Get userName according to userId
                      String userName = queryUserNameByUserId(userId);
                      item.put("userName", userName); }}return item;
      }
      Copy the code