我想在我的 Grails 项目中创建自定义日志记录注释。
我的代码:
class MyService{
@AuditLog
def method1() {
println "method1 called"
method2()
}
@AuditLog
def method2() {
println "method2 called"
}
}
拦截器:
class AuditLogInterceptor implements MethodInterceptor {
@Override
Object invoke(MethodInvocation methodInvocation) throws Throwable {
println "${methodInvocation.method}"
return methodInvocation.proceed();
}
}
Spring 配置:
aop {
config("proxy-target-class": true) {
pointcut(id: "auditLogInterceptorPointcut", expression: "@annotation(xxx.log.AuditLog)")
advisor('pointcut-ref': "auditLogInterceptorPointcut", 'advice-ref': "auditLogInterceptor")
}
}
auditLogInterceptor(AuditLogInterceptor) {}
结果:
public java.lang.Object xxx.MyService.method1()
method1 called
method2 called
我也希望看到方法 2 的注释触发。我错过了什么?
最佳答案
发生这种情况是因为服务类中对自身的内部方法调用未在 service
的代理实例上完成类(class)。如果您从应用程序上下文中获取服务 bean 并尝试调用 method2()
你应该看到 aspect
听advice
.
class MyService{
static transactional = false
def grailsApplication
@AuditLog
def method1() {
println "method1 called"
grailsApplication.mainContext.myService.method2()
//method2()
}
@AuditLog
def method2() {
println "method2 called"
}
}
关于java - Grails 的 AOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17410018/