Spring 方面如何跨多个对象更新公共字段

Spring aspect how to update a common filed across multiple objects

我正在编写 Spring 方面并寻找更新返回对象字段的方法

我的 Dto

@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class BaseDto{
   LocalDateTime testTime;
}

@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class TestDto{
  private BaseDto baseDtol
}

@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class SampleDto{
  private BaseDto baseDtol
}

我的转换器案例:

@TestAnnotation
public TestDto covert(){
  return new TestDto()
}

@TestAnnotation
public SampleDto covert(){
  return new SampleDto()
}

看点:

@Aspect
@Component
public class TestAspect {
   @AfterReturning(value = "@annotation(TestAnnotation)", returning = "entity")
   public void test(JoinPoint joinPoint, Object entity){
      //Looking for a way to set BaseDto in the TestDto and SampleDto objects
   }
}

我的方面将从转换器中调用 class 并且返回对象可以是 SampleDto 和 TestDto。我正在寻找一种在其中设置 BaseDto 对象的方法。

已编辑

您可以使用 java 反射 BaseDto 对象动态设置为 entity 字段。

1- Iterate through fields of entity.

  • Check fields type (must equal to BaseDto.class)

2- set accessibility of the checked field to true.

3- set new BaseDto() to field.

@AfterReturning(pointcut = "servicePointCut()", returning = "entity")
public void afterReturningAdvice(JoinPoint joinPoint, Object entity) throws IllegalAccessException 

{

    //Iterate through fields of entity
    for (Field field : entity.getClass().getDeclaredFields()) {

        //Check type of field (equals to BaseDto.class)
        if (field.getType().equals(BaseDto.class)) {

            //Set accessibility of field to true
            field.setAccessible(true);
            
            //Set new BaseDto to entityobject
            BaseDto baseDto = new BaseDto();
            field.set(entity, baseDto);
        }
     
    }

 //Rest of afterReturningAdvice method ...
}