Spring AOP target() vs this()

笑着哭i 提交于 2019-12-20 10:39:10

问题


From Spring Documentation:

  • any join point (method execution only in Spring AOP) where the proxy implements the AccountService interface:

    this(com.xyz.service.AccountService)
    
  • any join point (method execution only in Spring AOP) where the target object implements the AccountService interface:

    target(com.xyz.service.AccountService)
    

I don't understand what "target object" and the expression target(...) mean.

How is target different from this?


回答1:


this(AType) means all join points where this instanceof AType is true. So this means that in your case once the call reaches any method of AccountService this instanceof AccountService will be true.

target(AType) means all join points where anObject instanceof AType . If you are calling a method on an object and that object is an instanceof AccountService, that will be a valid joinpoint.

To summarize a different way - this(AType) is from a receivers perspective, and target(AType) is from a callers perspective.




回答2:


I know this is an old post but I just came across an important difference between this and target while not using AspectJ.

Consider the following introduction aspect:

@Aspect
public class IntroductionsAspect {

    @DeclareParents(value="a.b.c.D", defaultImpl=XImpl.class)
    public static X x;

    @After("execution(* a.b.c.D.*(..)) && this(traceable)")
    public void x(Traceable traceable) {
        traceable.increment();
    }

}

Simply put, this aspect is doing two things:

  1. Making the a.b.c.D class implement the X interface.
  2. Adding a call to traceable.increment() to be executed before each method of a.b.c.D.

The important part is "execution(* a.b.c.D.*(..)) && this(traceable)". Notice that I used this, not target.

If you use target instead, you are trying to match the original class a.b.c.D, not the introduced interface X. So Spring AOP will not find any join point in a.b.c.D.

In summary:

this - Checks the proxy type, or introduced type. target - Checks the declared type.




回答3:


From official documentation:

Spring AOP is a proxy-based system and differentiates between the proxy object itself (bound to 'this') and the target object behind the proxy (bound to 'target').

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-pointcuts-designators



来源:https://stackoverflow.com/questions/11924685/spring-aop-target-vs-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!