簡體   English   中英

如何在grails中調用域內部的服務方法?

[英]How to call a service method inside of the domain in grails?

我必須從域中調用控制器的一種方法。 我正在嘗試找到一些答案,但是我什么也沒找到,我不確定是否可能。 抱歉,如果我的問題是錯誤的,但是在我有要求時,我必須為此找到解決方案,因為我已經在域中的beforeInsert()方法中進行了此操作。

當我嘗試運行項目時,這是錯誤:

| 錯誤2015-12-02 10:59:29,210 [localhost-startStop-1]錯誤hibernate.AssertionFailure-發生斷言失敗(這可能表示Hibernate中的錯誤,但更可能是由於不安全地使用會話)消息: com.xxxx條目中的null id(發生異常后不要刷新Session)

控制器方式:

def calculate(Integer max){
        params.max = Math.min(max ?: 10, 100)
        def users= User.findAllByType(null)
        LicenceTypeService.calculate(users) //This call a service
        redirect(action: "list", params: params)
    }

在我的域中:

protected void callCalculateWhencreateUser(){
        def users= User.find("from User order by id desc")
        LicenceTypeService.calculate(users) //This call a service
    }

def beforeInsert() {
        encodePassword()
        callCalculateWhencreateUser()
    }

在我的服務中:

def calculate(def users){

        //logic code

    }

您的問題的主題具有誤導性:您說您需要從域中調用控制器方法,但是您的代碼說的是您正試圖從域和控制器中調用服務方法。

您不能從域中調用控制器方法,這在概念上是錯誤的,但是您還需要一個請求來調用控制器,而您在域中沒有該方法。

但是,實際上,您要嘗試的方法是:將邏輯留給服務,然后從控制器和域中調用它。 但是你做錯了。

在控制器中,您需要聲明服務,因此spring會將其注入到控制器中,如下所示:

class MyController {
    def licenceTypeService

    def calculate(Integer max){
        params.max = Math.min(max ?: 10, 100)
        def users = User.findAllByType(null)
        licenceTypeService.calculate( users )
        redirect(action: "list", params: params)
    }
}

您可以在服務屬性的聲明中使用實際類型而不是def,但重要的是,屬性名稱是服務的“邏輯名稱”:類名,但首字母小寫。 這樣,該屬性將在春季注入。

您應該將變量“ user”更改為“ users”,這使您認為這是一個單一用戶,但是使用的查找程序將返回一個用戶列表。

在域上,您只需要做更多的工作。 您需要以相同的方式注入服務,但是需要將其添加到“瞬態”列表中,因此GORM不會嘗試在數據庫中為其創建字段或從數據庫中檢索字段。

像這樣:

class MyDomain {

    def licenceTypeService

    static transients = [ "licenseTypeService" ]

    def beforeInsert() {
        encodePassword()
        licenceTypeService.calculate( this )
    }
}

您的服務將類似於:

class LicenceTypeService {

    def calculate( User user ) {
        // perform some calculation
        // do not call user.save() since this will be invoked from beforeInsert
    }

    def calculate( List<User> users ) {
        // If this is performed on several users it should be 
        // done asynchronously
        users.each {
            calculate( it )
            it.save()
        }
    }
}

希望能有所幫助。

但是,根據您在calculate方法中所做的操作(對於單個用戶),它可以是User類的方法(這是一種更OO的解決方案)。

暫無
暫無

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

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