(快速參考)

8 特質

版本 6.2.0

8 特質

概觀

Grails 提供許多特質,可存取各種 Grails 工件以及屬於 Grails 專案的任意 Groovy 類別的屬性和行為。這些特質中的許多會自動新增至 Grails 工件類別(例如控制器和標籤庫),而且很容易新增至其他類別。

8.1 Grails 提供的特質

Grails 工件會在編譯時自動擴充某些特質。

攔截器特質

標籤庫特質

以下是框架提供的其他特質清單。javadoc 提供了與每個特質相關的方法和屬性的詳細資訊。

特質 簡要說明

grails.web.api.WebAttributes

常見 Web 屬性

grails.web.api.ServletAttributes

Servlet API 屬性

grails.web.databinding.DataBinder

資料繫結 API

grails.artefact.controller.support.RequestForwarder

要求轉發 API

grails.artefact.controller.support.ResponseRedirector

回應重新導向 API

grails.artefact.controller.support.ResponseRenderer

回應渲染 API

grails.validation.Validateable

驗證 API

8.1.1 WebAttributes 特質範例

WebAttributes 是架構提供的特質之一。任何 Groovy 類別都可以實作此特質,以繼承特質提供的所有屬性和行為。

src/main/groovy/demo/Helper.groovy
package demo

import grails.web.api.WebAttributes

class Helper implements WebAttributes {

    List<String> getControllerNames() {
        // There is no need to pass grailsApplication as an argument
        // or otherwise inject the grailsApplication property.  The
        // WebAttributes trait provides access to grailsApplication.
        grailsApplication.getArtefacts('Controller')*.name
    }
}

特質與靜態編譯相容…​

src/main/groovy/demo/Helper.groovy
package demo

import grails.web.api.WebAttributes
import groovy.transform.CompileStatic

@CompileStatic
class Helper implements WebAttributes {

    List<String> getControllerNames() {
        // There is no need to pass grailsApplication as an argument
        // or otherwise inject the grailsApplication property.  The
        // WebAttributes trait provides access to grailsApplication.
        grailsApplication.getArtefacts('Controller')*.name
    }
}