0

我正在寻找的是一种在类级别变量周围指定切入点的方法。就像是:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.FIELD)
@interface MyPointCut
{
}

public class Foo
{

    @MyPointCut
    BarAPI api = new BarAPI();

}

@Aspect
public class MyAspect
{
    @Around(value="execution(* *(..)) && @annotation(MyPointCut)")
    public Object doSomethingBeforeAndAfterEachMethodCall()
    {
        ...
    }
}

然后,我希望有一个方面在 api 字段的每个方法调用之前和之后执行一些工作。这是可行的吗?您能否指点我一些可以阅读如何操作的文档?

4

1 回答 1

2

It is a bit like simply putting execution advice on all the methods in type BarAPI, but your difference is that you only care about a specific instance of BarAPI and not all of them.

// Execution of any BarAPI method running in the control flow of a Foo method
Object around(): execution(* BarAPI.*(..)) && cflow(within(Foo)) {...}

cflow is a bit 'heavy' for this though, can we do something lighter:

// Call to any BarAPI method from the type Foo
Object around(): call(* BarAPI.*(..)) && within(Foo) { ... }

And what about something like that but more generally applicable:

// Assume Foo has an annotation on it so it is more general than type Foo.
@HasInterestingBarAPIField
public class Foo { ... }

Object around(): call(* BarAPI.*(..)) && @within(HasInterestingBarAPIField) { ... }
于 2016-07-22T18:40:14.697 回答