3

我使用 Grails 2.2.3 并在 grails-app/conf/spring/resources.groovy 中键入以下代码

beans = {
    xmlns aop:"http://www.springframework.org/schema/aop"
    loggerAspect(com.test.aop.aspect.LoggerAspect)
    aop{
        config("proxy-target-class": true) {
            aspect(id: "beforeService", ref: "loggerAspect") {
                before method: "beforeMethod", 
                pointcut: "execution(* com.test.DemoService.serviceMethod())"
            }
            aspect(id: "afterService", ref: "loggerAspect") {
                after method: "afterMethod", 
                pointcut: "execution(* com.test.DemoService.serviceMethod())"
            }
        }
    }
}

然后,在 src/groovy/com/test/aop/aspect 下创建一个切面类

package com.test.aop.aspect
class LoggerAspect {
    def beforeMethod(JoinPoint jp){
        println '-- Before Method.'
    }

    def afterMethod(JoinPoint jp){
        println '-- After Method.'
    }
}

并在 grails-app/services/com/test 下创建一个服务类

package com.test
class DemoService {
    def serviceMethod() {
        println 'In DemoService.serviceMethod()'
    }
}

并创建一个控制器来调用服务进行测试

package com.test
class DemoController {
    def index() {
        println 'In DemoController.index()'
        def demoService = new DemoService()
        demoService.serviceMethod()

         render 'Hello World'
    }
}

最后,我通过url测试aop:

http://myhost:8080/grails-spring-aop/demo/index

并且 aop 没有被调用。结果如下:

| Server running. Browse to http://myhost:8080/grails-spring-aop/
In DemoController.index()
In DemoService.serviceMethod()

我将以下行添加到服务类:

static transactional = false

而且,它仍然不适合我。

任何人都知道如何解决这个问题,或者这是不可能的。或者我做错了什么。

谢谢。

4

1 回答 1

11

您需要在控制器中注入服务(spring bean)而不是创建它的实例。

package com.test
class DemoController {
    def demoService //Autowired, not required to specify in resources.groovy

    def index() {
        println 'In DemoController.index()'
        demoService.serviceMethod()

        render 'Hello World'
    }
}

此外,可以根据以下方式对方面进行注释:

package com.test.aop.aspect

@Aspect
class LoggerAspect {

    //A more generic advice would be as below
    //@Before("execution(* com.test.*.*(..))")
    @Before("com.test.DemoService.serviceMethod()")
    def beforeMethod(){
        println '-- Before Method.'
    }

    //A more generic advice would be as below
    //@Around("execution(* com.test.*.*(..))")
    @After("com.test.DemoService.serviceMethod()")
    def afterMethod(){
        println '-- After Method.'
    }
}

resources.groovy 可能变成:

beans = {
    loggerAspect(com.test.aop.aspect.LoggerAspect)

    xmlns aop:"http://www.springframework.org/schema/aop"
    aop{
        config("proxy-target-class": true) {
            aspect(id: "loggerAspectService", ref: "loggerAspect") 
        }
    }
}
于 2013-07-16T03:02:05.913 回答