grails中面向方面的编程问题。切点方法没有执行

时间:2015-02-05 07:23:32

标签: java spring spring-mvc grails groovy

我正在使用Grails 2.4.3。在resource.groovy中,我添加了组件扫描

xmlns aop:"http://www.springframework.org/schema/aop"
context.'component-scan'('base-package': 'com')

然后在src / groovy中我创建了groovy类

package com.demo.aspects.mongo.history;

import grails.transaction.Transactional
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.aspectj.lang.annotation.After
import org.springframework.stereotype.Component

@Aspect
@Component
@Transactional
public class MongoAspectAdvice {
    @After("execution(* com.demo.global.BaseOptionService.save(..))")
    def afterMethod(){
        println "after method execution"
    }

    @Before("execution(* com.demo.global.BaseOptionService.save(..))")
    def beforeMethod(){
        println "before method execution"
    }
}

在com.demo.global.BaseOptionService中保存功能定义为

def save(def entity){
        if(entity.id == null){
            entity.createdDate = new Date()
        }
        entity.lastUpdatedDate = new Date()
        log.debug(entity)
        neo4jTemplate.save(entity)
    }

BaseOptionService由UserService扩展,其中调用了BaseOptionService方法。

UserService.groovy

         class UserService extends BaseOptionService{

    def addUser(username,email,role,phonenumber){
        log.debug "user ===== "+username
        UserCommand userCommand = new UserCommand()

        userCommand.username = username
        userCommand.email = email
        userCommand.phonenumber = phonenumber
        userCommand.role = role
        if(userCommand.labels?.empty == true || userCommand.labels == null){
            if(role == null){
                userCommand.addLabel(null)
            }else{
            userCommand.addLabel("_USER")
            userCommand.addLabel(role)
            }
        }
        userCommand.isActive = true
        userCommand.token = null

        UserDomain user = userCommand.getUser()
        log.debug "user == "+user
        save(user)
        return user
    }

    def removeLabels(id,label){
        UserDomain user = findOne(id,UserDomain)
        if(user.labels?.contains(label)){
            user.labels.remove(label)
        }
        save(user)
        return user
    }

    def serviceMethod() {

    }
}

当执行保存功能时,我还没有在控制台中看到afterMethod和beforeMethod的println语句,并且没有错误。我不确定我在做什么错。请帮忙。

1 个答案:

答案 0 :(得分:1)

当您的应用程序启动时,组件扫描将扫描所有包以检查存在的bean。 无论如何,如果bean没有被任何其他类引用,那么这个进程不会实例化它。换句话说,你告诉我是的,我有一个使用@Component注释的MongoAspectAdvice类,所以它也是一个单例但你在哪里使用它? 尝试在UserService中导入它。 然后,如果stil不工作(检查你可以在该类中放置一个断点),请将以下代码添加到resources.groovy:

// Place your Spring DSL code here
beans = {
mongoAspectAdvice(MongoAspectAdvice) { bean ->
bean.autowire = "byName"
}

然后导入您的服务:

def mongoAspectAdvice

但是,您可以通过使用一些grails ad-hc闭包来复制此行为:

def beforeInterceptor = {
    println "Tracing action ${actionUri}"
} 

def afterInterceptor = {
    println "Tracing action ${actionUri}"
}

将它们放入BaseOptionService