3

My exact requirement is to log the values of old object and new object together. for example if previously the name of the user was "AAA" and somebody changes the name to "CCC" than in service layer I need to log like this "user name changes from AAA to CCC dated 10-09-2013". Please provide some solution in spring framework.

Aditya
  • 31
  • 1
  • 6

1 Answers1

0

You can use Spring AOP, intercept bean's setters and log property change, basic idea is here

class B1 {
    String name = "xxx";
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

@Aspect
class A1 {
    @Before("execution(void test.B1.set*(*))")
    public void before(JoinPoint jp) throws Exception {
        String prop = jp.getSignature().getName().substring(3);
        Object target = jp.getTarget();
        Object before = target.getClass().getMethod("get" + prop).invoke(target);
        Object now = jp.getArgs()[0];
        System.out.println(prop + " changed from " + before + " to " + now);
    }
}

public class Test1 {

    public static void main(String[] args) throws Exception {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("test1.xml");
        B1 b1 = ctx.getBean(B1.class);
        b1.setName("yyy");
    }
}

this prints

Name changed from xxx to yyy

test1.xml

...
    <context:annotation-config />
    <aop:aspectj-autoproxy />
    <bean class="test.B1" />
    <bean class="test.A1" />
...
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275