簡體   English   中英

如何在Grails 3.3.2中為領域類保存方法創建方面?

[英]How to create aspect in Grails 3.3.2 for domain class save method?

我想在grails 3.3.2中創建一個方面,該方面在每次調用我的域類的對象的save()方法時執行。

我該怎么做?

/ ************ /

編輯:@pavger

我嘗試了以下代碼,盡管調用了ProyectoService的任何方法,但我的Aspect從未運行

服務域類別

import grails.gorm.services.Service

@Service(Proyecto)
interface ProyectoService {

    Proyecto get(Serializable id)

    List<Proyecto> list(Map args)

    Long count()

    void delete(Serializable id)

    Proyecto save(Proyecto proyecto)

}

方面!

@Aspect
class MeAspect {
    @PostConstruct
    public void init() {
        println "Inicializado"
    }

    @Pointcut("within(com.sample.ProyectoService.*())")
    void isDomainClass() {}


    @Around("isDomainClass()")
    Object aroundSaveConnector(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object[] args = proceedingJoinPoint.getArgs()
        println "Aspecto before"
        Object object = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs())
        println "Aspecto after"
        return object
    }
}

您可以在Domain類上創建一個選項。 這是GORM上的一個選項

事件和自動時間戳記GORM支持將事件注冊為在發生某些事件(例如刪除,插入和更新)時會觸發的方法。 以下是受支持的事件的列表:

beforeInsert-在對象最初持久保存到數據庫之前執行。 如果返回false,則插入將被取消。

beforeUpdate-在更新對象之前執行。 如果返回false,則更新將被取消。

beforeDelete-在刪除對象之前執行。 如果返回false,則刪除將被取消。

beforeValidate-在驗證對象之前執行

afterInsert-將對象持久保存到數據庫后執行

afterUpdate-在對象更新后執行

afterDelete-刪除對象后執行

onLoad-從數據庫加載對象時執行

http://gorm.grails.org/6.0.x/hibernate/manual/

class Person {
   private static final Date NULL_DATE = new Date(0)

   String firstName
   String lastName
   Date signupDate = NULL_DATE

   def beforeInsert() {
      if (signupDate == NULL_DATE) {
         signupDate = new Date()
      }
   }
}



class Person {

   def securityService

   String firstName
   String lastName
   String lastUpdatedBy

   static constraints = {
      lastUpdatedBy nullable: true
   }

   def beforeUpdate() {
      lastUpdatedBy = securityService.currentAuthenticatedUsername()
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM