gpt4 book ai didi

Grails 和 AspectJ : advice for private methods is not working

转载 作者:行者123 更新时间:2023-12-01 15:37:37 25 4
gpt4 key购买 nike

我需要拦截对 Grails 服务中私有(private)方法的调用。以下方面适用于任何带注释的公共(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)方法会被拦截。

最佳答案

与 AspectJ 相比,Spring 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” 中所述。 .

关于Grails 和 AspectJ : advice for private methods is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28100016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com