1

我正在编写 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
   }
}

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

4

1 回答 1

0

已编辑

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

1- 遍历entity.

  • 检查字段类型(必须等于BaseDto.class

2-将选中字段的可访问性设置为true

3-设置new BaseDto()为字段

@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 ...
}
于 2020-01-17T20:25:14.730 回答