如何使用AOP在JPA实体中建议/切入点设置器?

时间:2014-07-16 16:49:51

标签: java jpa aspectj

我需要记录对实体中字段的任何更改 - 无论是字符串更改,还是添加/删除集合/映射。

给定一个带有一堆原始字段的JPA实体,编写一个切入点来截断字段上的任何set(..)方法都是相当简单的。

但是,我遇到的问题是如何编写切入点来处理Collections / Sets / Embedded /等。

鉴于以下实体:

@Entity
public class Provider implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;


    private String name;

    @Column(name="type", nullable=false)
    @Enumerated(EnumType.STRING)
    private ProviderType providerType;


    @ManyToMany
    private List<Contact> contacts;

    @Embedded
    private Validity validity;

   // setters and getters omitted for brevity

}

其中Contact是一个带有一堆原始字段的简单实体,Validity是一个带有一些原始字段的非实体对象。

以下切入点将拦截类中的所有set()方法:

pointcut fieldSetter() : set(!static !final !transient * *.Provider) && args(val) && target(o);

我可以写一个之前/之后/周围的建议。

before( Object val, Object o) : fieldSetter{
  String fieldName = thisJoinPointStaticPart.getSignature().getName();
  System.out.println( "Object being changed: " + o.toString() );
  System.out.println( "New Value for: " + fieldname + " is: " + v.toString() );
}

但是我如何处理嵌入式对象或集合的情况呢?对于Embedded对象,如果我只是在对象中设置setter方法的建议,我怎么知道哪个是实际被修改/持久化的父对象?

在集合/集合/地图/等的情况下,我如何建议反对添加/删除方法?我最终需要做的是建议getCollection()。add()方法以及getCollection.remove()方法。但我似乎无法找到一个好方法。

1 个答案:

答案 0 :(得分:1)

这不能直接完成,只能通过手动记账,因为集合或映射不会更改其标识,只有当您调用方法时才会更改其内部状态,即没有set()个连接点被截获,只有方法调用。因此,您需要维护分配给您感兴趣的对象成员的集合/映射之间的映射并跟踪它们的更改,这非常繁琐。以下是一些示例代码,其中包含适用于Collection.add()Map.put()的概念证明。你必须为所有改变内部状态的方法扩展它,例如remove()clear()等。基本上它的工作原理如下:

驱动程序类:

这是一个示例Person类,包含两个原始成员,两个集合和一个映射。它

  • 为所有Person成员分配默认值
  • 更改它们,
  • 取消分配现有的集合/地图Person成员,将其保存在本地变量中
  • 再次更改集合/地图对象(不应该产生任何日志记录输出,因为这些对象当前未分配给Person成员),
  • 将集合/地图对象重新分配给Person成员
  • 再次更改它们(现在应该再次生成日志输出)。
package de.scrum_master.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Person {
    int id;
    String name;
    List<Object> objects = new ArrayList<>();
    Set<Integer> numbers = new HashSet<>();
    Map<String, Object> properties = new HashMap<>();

    public Person(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person[id=" + id + ", name=" + name + "]";
    }

    public static void main(String[] args) {
        System.out.println("Creating Person object");
        Person person = new Person(2, "Werner Heisenberg");

        System.out.println("\nChanging member object states");
        person.id = 1;
        person.name = "Albert Einstein";
        person.objects.add("foo");
        person.objects.add(11);
        person.objects.add(new Object());
        person.numbers.add(11);
        person.numbers.add(22);
        person.numbers.add(33);
        person.properties.put("year of birth", 1879);
        person.properties.put("year of death", 1955);
        person.properties.put("well known for", new String[] { "Photoelectric Effect", "Special Relativity", "General Relativity" });

        System.out.println("\nUnassigning member objects");
        List<Object> objects = person.objects;
        person.objects = null;
        Set<Integer> numbers = person.numbers;
        person.numbers = null;
        Map<String, Object> properties = person.properties;
        person.properties = null;

        System.out.println("\nChanging non-member object states");
        objects.add("bar");
        objects.add(22);
        objects.add(new Object());
        numbers.add(44);
        numbers.add(55);
        numbers.add(66);
        properties.put("Nobel Prize year", 1921);

        System.out.println("\nReassigning member objects");
        person.objects = objects;
        person.numbers = numbers;
        person.properties = properties;

        System.out.println("\nChanging member object states again");
        person.objects.add("zot");
        person.objects.add(33);
        person.objects.add(new Object());
        person.numbers.add(77);
        person.numbers.add(88);
        person.numbers.add(99);
        person.properties.put("Time Person of the Century year", 1999);
    }
}

直接/间接成员更改的记录方面:

这方面拦截

  • 直接成员更改(set()切入点定位Person个对象),
  • 致电Collection+.add()
  • 致电Map+.put()

方面还在其members属性中保留了相当复杂的数据结构:Map<Object, Set<Entry<Person, String>>>使用集合/映射作为键和PersonString对(字段名称) )元素作为价值观。为什么这么复杂的数据结构?因为可以将同一个集合/映射分配给多个Person成员,甚至可以分配给同一Person个对象的多个成员,具体取决于您使用的集合/映射的类型。所以数据结构非常通用。随意扩展驱动程序类以使用多个Person对象和/或在Person类中具有相同类型的多个成员。我没有测试过,但它应该可以工作。

<强> 更新

  • 丑陋的getOldFieldValue()辅助方法是必要的,因为AspectJ不会在set()切入点中公开旧值,只会显示新值。因此,需要通过反思来确定。
  • 因为JDK没有通用的对/元组类,并且我不想使用列表/向量来保持值对,所以我使用AbstractMap.SimpleEntry。此外,它的equals()方法保证将具有相等键和值的对视为相等,因此我可以创建一个新实例并在我的Map.remove()调用中使用它 - 无需通过以下方式搜索现有值迭代。万一你想知道。
package de.scrum_master.aspect;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;

import org.aspectj.lang.Signature;
import org.aspectj.lang.SoftException;

import de.scrum_master.app.Person;

public aspect MemberChangeLogger {
    private Map<Object, Set<Entry<Person, String>>> members =
        Collections.synchronizedMap(
            new IdentityHashMap<Object, Set<Entry<Person, String>>>()
        );

    private Object getOldFieldValue(Signature signature, Person person) {
        Field field;
        try {
            field = signature.getDeclaringType().getDeclaredField(signature.getName());
        }
        catch (Exception e) { throw new SoftException(e); }
        field.setAccessible(true);
        try {
            return field.get(person); 
        }
        catch (Exception e) { throw new SoftException(e); }
    }

    pointcut directMemberChange(Person person, Object newValue) :
        set(* Person.*) &&
        args(newValue) &&
        target(person);

    pointcut collectionChange(Collection collection, Object newElement) :
        !cflow(adviceexecution()) &&
        call(* Collection+.add(*)) &&
        args(newElement) &&
        target(collection);

    pointcut mapChange(Map map, Object key, Object value) :
        !cflow(adviceexecution()) &&
        call(* Map+.put(*, *)) &&
        args(key, value) &&
        target(map);

    before(Person person, Object newValue) : directMemberChange(person, newValue) {
        String fieldName = thisJoinPointStaticPart.getSignature().getName();
        System.out.println(
            "Direct field change: " +
            person + " -> " + fieldName + " = " + newValue
        );
        Object oldValue = getOldFieldValue(thisJoinPoint.getSignature(), person);
        if (!(
            newValue instanceof Collection || newValue instanceof Map ||
            oldValue instanceof Collection || oldValue instanceof Map
        ))
            return;
        if (oldValue != null && members.get(oldValue) != null) {
            members.get(oldValue).remove(new SimpleEntry<Person, String>(person, fieldName));
            if (members.get(oldValue).size() == 0)
                members.remove(oldValue);
        }
        if (newValue == null)
            return;
        if (members.get(newValue) == null)
            members.put(newValue, new HashSet<Map.Entry<Person, String>>());
        members.get(newValue).add(new SimpleEntry<Person, String>(person, fieldName));
    }

    before(Collection collection, Object newElement) : collectionChange(collection, newElement) {
        if (members.get(collection) == null)
            return;
        for (Entry<Person, String> entry : members.get(collection)) {
            System.out.println(
                "Indirect field change: " +
                entry.getKey() + " -> " + entry.getValue() +
                " -> adding element " + newElement + " to " + collection
            );
        }
    }

    before(Map map, Object key, Object value) : mapChange(map, key, value) {
        if (members.get(map) == null)
            return;
        for (Entry<Person, String> entry : members.get(map)) {
            System.out.println(
                "Indirect field change: " +
                entry.getKey() + " -> " + entry.getValue() +
                " -> putting entry (" + key + "=" + value + ") into " + map
            );
        }
    }
}

控制台输出:

如果您在编织方面的情况下运行Person.main(),则输出应如下所示:

Creating Person object
Direct field change: Person[id=0, name=null] -> objects = []
Direct field change: Person[id=0, name=null] -> numbers = []
Direct field change: Person[id=0, name=null] -> properties = {}
Direct field change: Person[id=0, name=null] -> id = 2
Direct field change: Person[id=2, name=null] -> name = Werner Heisenberg

Changing member object states
Direct field change: Person[id=2, name=Werner Heisenberg] -> id = 1
Direct field change: Person[id=1, name=Werner Heisenberg] -> name = Albert Einstein
Indirect field change: Person[id=1, name=Albert Einstein] -> objects -> adding element foo to []
Indirect field change: Person[id=1, name=Albert Einstein] -> objects -> adding element 11 to [foo]
Indirect field change: Person[id=1, name=Albert Einstein] -> objects -> adding element java.lang.Object@69d30fe7 to [foo, 11]
Indirect field change: Person[id=1, name=Albert Einstein] -> numbers -> adding element 11 to []
Indirect field change: Person[id=1, name=Albert Einstein] -> numbers -> adding element 22 to [11]
Indirect field change: Person[id=1, name=Albert Einstein] -> numbers -> adding element 33 to [22, 11]
Indirect field change: Person[id=1, name=Albert Einstein] -> properties -> putting entry (year of birth=1879) into {}
Indirect field change: Person[id=1, name=Albert Einstein] -> properties -> putting entry (year of death=1955) into {year of birth=1879}
Indirect field change: Person[id=1, name=Albert Einstein] -> properties -> putting entry (well known for=[Ljava.lang.String;@1fb93cf8) into {year of birth=1879, year of death=1955}

Unassigning member objects
Direct field change: Person[id=1, name=Albert Einstein] -> objects = null
Direct field change: Person[id=1, name=Albert Einstein] -> numbers = null
Direct field change: Person[id=1, name=Albert Einstein] -> properties = null

Changing non-member object states

Reassigning member objects
Direct field change: Person[id=1, name=Albert Einstein] -> objects = [foo, 11, java.lang.Object@69d30fe7, bar, 22, java.lang.Object@3a51ce0d]
Direct field change: Person[id=1, name=Albert Einstein] -> numbers = [33, 55, 66, 22, 11, 44]
Direct field change: Person[id=1, name=Albert Einstein] -> properties = {year of birth=1879, Nobel Prize year=1921, year of death=1955, well known for=[Ljava.lang.String;@1fb93cf8}

Changing member object states again
Indirect field change: Person[id=1, name=Albert Einstein] -> objects -> adding element zot to [foo, 11, java.lang.Object@69d30fe7, bar, 22, java.lang.Object@3a51ce0d]
Indirect field change: Person[id=1, name=Albert Einstein] -> objects -> adding element 33 to [foo, 11, java.lang.Object@69d30fe7, bar, 22, java.lang.Object@3a51ce0d, zot]
Indirect field change: Person[id=1, name=Albert Einstein] -> objects -> adding element java.lang.Object@50aed564 to [foo, 11, java.lang.Object@69d30fe7, bar, 22, java.lang.Object@3a51ce0d, zot, 33]
Indirect field change: Person[id=1, name=Albert Einstein] -> numbers -> adding element 77 to [33, 55, 66, 22, 11, 44]
Indirect field change: Person[id=1, name=Albert Einstein] -> numbers -> adding element 88 to [33, 55, 66, 22, 77, 11, 44]
Indirect field change: Person[id=1, name=Albert Einstein] -> numbers -> adding element 99 to [33, 55, 66, 22, 77, 11, 88, 44]
Indirect field change: Person[id=1, name=Albert Einstein] -> properties -> putting entry (Time Person of the Century year=1999) into {year of birth=1879, Nobel Prize year=1921, year of death=1955, well known for=[Ljava.lang.String;@1fb93cf8}

正如您所看到的,部分&#34;更改非成员对象状态&#34;中没有输出,正如预期的那样。但add() / put()分段调用&#34;更改成员对象状态&#34;和&#34;再次更改成员对象状态&#34;记录为&#34;间接字段更改:人员[...&#34;。基本上这就是你想要达到的目标,但我个人认为,除了做一个很好的练习外,它可能有点慢和维护噩梦,但可行。