Home > Back-end >  Can spring aop be applied to specific fields when creating dto?
Can spring aop be applied to specific fields when creating dto?

Time:01-19

I want to mask personal information when java dto is created. I created an PersonalInfo annotation and added it to the field I want to mask. However, I don't know how to write an advice in the PersonalInfoAspect class.

@Getter
@Builder
public class User {

    private String id;

    @PersonalInfo
    private String name; 
}
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonalInfo {
}
@Aspect
@Component
public class PersonalInfoAspect {
    
    // ...
}

When dto is created, should aop be called when the constructor is called to change the field value?

When creating User dto as shown below, I want it to be masked and stored using spring aop.

User user = User.builder()
    .id("1")
    .name("kaven")
    .build()


System.out.println(user.getName()); 
// Output : k****

CodePudding user response:

You can write aspect for getters. Remember that Lombok @Getter generates plain old getter methods for fields which can be intercepted. You will probably have to mark your DTOs that should be affected with eg some annotation (and fields as well to show which fields should be obfuscated)

FYI What you call "Spring AOP" will work only on managed beans (@Components), but using AOP in general would work. As a crosspoint you could use return statements that returns your DTOs so it would become obfuscated right before passing controll back to spring.

CodePudding user response:

You would need a @Around advice on the annotation but only for the execution pointcut designator like -

@Around("@annotation(your.package.PersonalInfo) && execution(* *.*(..))")
public Object maskValue(final ProceedingJoinPoint jp) {
    Object obj = jp.proceed();
    if (obj == null && !jp.getSignature().getName().contains("get")) {
        return jp.proceed();
    }
    String value = String.valueOf(obj);
    obj = someFunction(value); // method call for your logic
    return obj;
}

The execution(...) will scan for all packages for the said annotation. It can be directed to scan a particular package as well to limit the scan.

  • Related