Spring AOP-在调用setter之前获取旧的字段值

Spring AOP-在调用setter之前获取旧的字段值,第1张

Spring AOP-在调用setter之前获取旧的字段值

我建议将完整的AspectJ与

set()
切入点结合使用,以获得有效的解决方案。但是,如果您不介意使用缓慢而丑陋的解决方案来进行反射,那么您也可以执行以下 *** 作:

package de.scrum_master.app;public class Person {    private int id;    private String firstName;    private String lastName;    public Person(int id, String firstName, String lastName) {        this.id = id;        this.firstName = firstName;        this.lastName = lastName;    }    public int getId() { return id; }    public String getFirstName() { return firstName; }    public String getLastName() { return lastName; }    public void setId(int id) { this.id = id; }    public void setFirstName(String firstName) { this.firstName = firstName; }    public void setLastName(String lastName) { this.lastName = lastName; }    @Override    public String toString() { return "Person [" + id + ", " + firstName + " " + lastName + "]"; }    public static void main(String[] args) {        Person albert = new Person(1, "Albert", "Camus");        Person audrey = new Person(2, "Audrey", "Hepburn");        System.out.println(albert);        System.out.println(audrey);        System.out.println();        albert.setId(8);        albert.setLastName("Einstein");        audrey.setId(9);        audrey.setLastName("Tautou");        System.out.println();        System.out.println(albert);        System.out.println(audrey);    }}package de.scrum_master.aspect;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.SoftException;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;@Aspectpublic class SetterInterceptor {    @Before("execution(* set*(*)) && target(instance) && args(newValue)")    public void beforeSetterCalled(JoinPoint thisJoinPoint, Object instance, Object newValue) {        String methodName = thisJoinPoint.getSignature().getName();        try { System.out.println(     methodName.substring(3) + ": " +     instance         .getClass()         .getMethod(methodName.replaceFirst("set", "get"))         .invoke(instance) +     " -> " + newValue );        } catch (Exception e) { throw new SoftException(e);        }    }}

控制台日志:

Person [1, Albert Camus]Person [2, Audrey Hepburn]Id: 1 -> 8LastName: Camus -> EinsteinId: 2 -> 9LastName: Hepburn -> TautouPerson [8, Albert Einstein]Person [9, Audrey Tautou]


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5439200.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存