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

亲爱的所有人,我目前正在将Spring AOP(v4)和AspectJ与Load-Time-Weaver一起使用.

我目前正在寻找一种将脏标志机制添加到我的bean中的方法.因此,尽管我在使用bean的setter之前使用AOP来调用方法.我已经实现了,但是如何在修改之前访问旧的字段值?还是有一种获取字段名称的方法,以便我可以在调用setter之前先调用getter?

有人可以在这里为我提供一些示例,如何使切入点/建议看起来像参数一样传递?

@Aspect
public class MyAspect {

  @Before("execution(* foo.*.set*(..))") 
  public void beforeSetterCalled(JoinPoint joinPoint){
    System.out.println("beforeSetter");
  }
}

不幸的是,Spring AOP似乎不支持“ set()”字段切入点构造,这是正确的吗?还是存在某种使用方式?

感谢您的任何帮助.

解决方法:

我建议将完整的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;

@Aspect
public 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 -> 8
LastName: Camus -> Einstein
Id: 2 -> 9
LastName: Hepburn -> Tautou

Person [8, Albert Einstein]
Person [9, Audrey Tautou]
上一篇:Spring Aop(二)——基于Aspectj注解的Spring Aop简单实现


下一篇:JavaScript设计模式-19.代理模式