使用aspectJ在AOP中使用Joinpoint VS ProceedingJoinPoint?

Hum*_*ing 18 java spring aspectj spring-aop

谁能告诉我Joinpoint和 之间有什么区别 Proceedingjoinpoint

何时使用JoinpointProceedingjoinpoint方面类的方法?

我用过JoinPointAspectJ class喜欢的,

@Pointcut("execution(* com.pointel.aop.test1.AopTest.beforeAspect(..))")  
public void adviceChild(){}  

@Before("adviceChild()")  
public void beforeAdvicing(JoinPoint joinPoint /*,ProceedingJoinPoint pjp - used refer book marks of AOP*/){ 

    //Used to get the parameters of the method !
    Object[] arguments = joinPoint.getArgs();
    for (Object object : arguments) {
        System.out.println("List of parameters : " + object);
    }

    System.out.println("Method name : " + joinPoint.getSignature().getName());
    log.info("beforeAdvicing...........****************...........");
    log.info("Method name : " + joinPoint.getSignature().getName());
    System.out.println("************************"); 
}
Run Code Online (Sandbox Code Playgroud)

但我在其他资源中看到的一些是,

@Around("execution(* com.mumz.test.spring.aop.BookShelf.addBook(..))")
public void aroundAddAdvice(ProceedingJoinPoint pjp){
    Object[] arguments = pjp.getArgs();
    for (Object object : arguments) {
        System.out.println("Book being added is : " + object);
    }
    try {
        pjp.proceed();
    } catch (Throwable e) {
        e.printStackTrace();
    }
} 
Run Code Online (Sandbox Code Playgroud)

ProceedingJoinPoint与'JointPoint`相比,这里有什么特别之处?

pjp.proceed()还能为我们做些什么?

Sea*_*oyd 26

around advice是一个特殊的建议,可以控制何时以及是否执行方法(或其他连接点).这仅适用于周围的建议,因此它们需要类型的参数ProceedingJoinPoint,而其他建议只使用普通JoinPoint.示例用例是缓存返回值:

private SomeCache cache;

@Around("some.signature.pattern.*(*)")
public Object cacheMethodReturn(ProceedingJoinPoint pjp){
    Object cached = cache.get(pjp.getArgs());
    if(cached != null) return cached; // method is never executed at all
    else{
        Object result = pjp.proceed();
        cache.put(pjp.getArgs(), result);
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

在此代码中(使用不存在的缓存技术来说明一点),仅在缓存未返回结果时才调用实际方法.例如,这是Spring EHCache Annotations项目的确切工作方式.

围绕建议的另一个特点是它们必须具有返回值,而其他建议类型则不能具有返回值.


abi*_*rai 11

@Around("execution(* com.mumz.test.spring.aop.BookShelf.addBook(..))")
Run Code Online (Sandbox Code Playgroud)

这意味着在调用com.mumz.test.spring.aop.BookShelf.addBook方法 aroundAddAdvice 方法之前调用.后 System.out.println("Book being added is : " + object);操作完成.它会调用你的实际方法addBook().pjp.proceed()将调用addBook()方法.

  • 如果你使用之前,投掷后,返回后和使用后的Jointpoint.如果你使用的话使用Proceedingjoinpoint.它们只是接口.Proceedingjoinpoint正在扩展Joinpoint.所以,看到它的功能你可以根据你的要求选择使用哪个. (9认同)