I want to mask personal information when a 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 the 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.
When creating a DTO, I want to intercept the constructor and generate it as masked data. Finally, when providing it as API using dto, I want to provide it as masked data Even if there is unmasked data in the DB.
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 (@Component
s), 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.