Grails & AspectJ:对私有方法的建议不起作用

Grails & AspectJ: advice for private methods is not working

我需要拦截对 Grails 服务中私有方法的调用。以下方面适用于任何带注释的 public 方法,但是当注释位于 PRIVATE 方法时没有任何反应。

import exceptions.DwcpExeption
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component

@Aspect
@Component
public class LoggerInterceptor {
    private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class);
    @Around("@annotation(newAnnotation)")
    public Object aroundEvents(ProceedingJoinPoint proceedingJoinPoint, NewAnnotation newAnnotation) {
        log.info newAnnotation.value()
        String logMessage = String.format("%s.%s(%s)",
                proceedingJoinPoint.getTarget().getClass().getName(),
                proceedingJoinPoint.getSignature().getName(),
                Arrays.toString(proceedingJoinPoint.getArgs()));
        log.info "*Entering $logMessage"
        def result
        try {
            result = proceedingJoinPoint.proceed()
        catch (ex) {
            log.error '', ex
        }
        log.info "*Exiting $logMessage. Result: $result"
        return result
    }
}

可能问题出在配置上?我试过 applicationContext.xml <aop:aspectj-autoproxy proxy-target-class="true"/> 在 resources.groovy aop.config("proxy-target-class": true)

然而,只有 public 个方法被拦截。

如果您不指定范围,则默认为 public。为私有方法添加切入点:

@Around("@annotation(newAnnotation) && execution(private * *(..))")

Spring 与 AspectJ 相比,AOP 是一种基于代理的 "AOP lite" 方法。它仅适用于 Spring 个组件,并且仅适用于 public 个非静态方法。这在Spring AOP documentation中也解释如下:

Due to the proxy-based nature of Spring’s AOP framework, protected methods are by definition not intercepted, neither for JDK proxies (where this isn’t applicable) nor for CGLIB proxies (where this is technically possible but not recommendable for AOP purposes). As a consequence, any given pointcut will be matched against public methods only!

If your interception needs include protected/private methods or even constructors, consider the use of Spring-driven native AspectJ weaving instead of Spring’s proxy-based AOP framework. This constitutes a different mode of AOP usage with different characteristics, so be sure to make yourself familiar with weaving first before making a decision.

底线:请切换到 AspectJ,它可以通过 LTW(加载时编织)轻松集成到 Spring 应用程序中,如 Section 9.8, “Using AspectJ with Spring applications” 中所述。