I Want to get the value of the modified objects using spring AOP (@Before). I have the below class:
package com.mypack;
public class Person {
private String id;
private String firstName;
private String lastName;
public String getId() { return id; }
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public void setId(String id) { this.id = id; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String toString() { return "Person[" + id + ",
+ firstName + ", " + lastName+ "]"; }
}
Details class:
package com.mypack;
public class Details extends Person{
private String address;
private String contactNum;
//getters and setters
public String toString() { return "Details[" + address + ",
" + contactNum+ "]"; }
}
AspectSetterInterceptor class:
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class AspectSetterInterceptor {
@Before("execution(* com.mypack.Details.set*(*))")
public void before(JoinPoint joinPoint) throws Throwable {
Object[] signatureArgs = joinPoint.getArgs();
for (Object signatureArg : signatureArgs) {
Person obj = (Person) signatureArg;
System.out.println("Before : " + obj.getFirstName() + " ---- "
+ obj.getId());
}
}
}
Test class:
public class ChangeTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AspectConfig.class);
ctx.refresh();
//Details userService = ctx.getBean(Details.class);
Details obj1 = new Details();
obj1.setAddress("xx 202");
obj1.setContactNum("2124551234");
obj1.setId("242");
obj1.setFirstName("John");
obj1.setLastName("John");
Details obj2 = new Details();
obj2.setAddress("ASDf 202");
obj2.setContactNum("234544565656");
obj2.setId("23689");
obj2.setFirstName("Sam");
obj2.setLastName("S");
System.out.println("obj1 : " + obj1);
System.out.println("obj2 : " + obj2);
obj2.setFirstName("Samuel");
}
}
Tried as mentioned here too Spring AOP - get old field value before calling the setter
--EDITED--- When ChangeTest class is executed, it is printing the values of obj1 and obj2 (toString() method overridden in the class). It is not hitting the method before(..) mentioned in the AspectSetterInterceptor . Please advice.
PS: My scenario is to hit the @Before aspect when ever some one is using set*(..) methods. Here in the above example i gave one simple class Details which extend Person class, so anytime the set*(..) method is invoked in those classes the aspect @before should be called, similarly i want in my application any set**(..) method is invoked i want to call the @Before. Is there any better approach to follow.TIA.