grails
5 命令列
版本 6.2.0
5 命令列
Grails 新命令列介面 (CLI) 與舊版本相比,經歷了重大變更,主要集中在程式碼產生上。一個顯著的變更,是移除了用於呼叫 Gradle 執行與使用 Gradle Tooling API 進行建置相關任務的 API。此責任轉移符合架構的演進,以及它與 Gradle 建置系統的整合。
存取 Grails CLI
Grails CLI (命令列介面) 可以透過在終端機或命令提示字元中輸入下列指令,快速且輕鬆地存取
此指令讓開發人員可以快速啟動 Grails CLI,並開始使用架構,讓想要開始 Grails 專案的人員有一個簡單的入門點。
新的 Grails CLI!是啟動新 Grails 專案的首選方法。此命令列介面提供各種建立專案的選項,讓您可以選擇偏好的建置工具、測試架構、GORM 實作等等。此外,CLI 提供指令來產生必要的元件,例如控制器和網域類別。
Grails Forge 網站
您也可以透過瀏覽 Grails Forge 網站 來啟動 Grails 應用程式,而不需要安裝 Grails CLI。這個網路平台讓您可以輕鬆地啟動 Grails 專案,而不需要安裝 CLI。
瞭解新的 Grails 命令列介面 (CLI)
成功安裝 Grails CLI 後,您可以使用「grails」指令來啟動它。例如
grails create-app myapp
Grails 架構 CLI 專案的特徵是存在「grails-cli.yml」檔案,如果專案是使用 CLI 建立的,這個檔案會自動產生在專案的根目錄。這個檔案包含專案的設定檔、預設套件和其它變數的資訊。
以下是預設 Grails 網路應用程式的「grails-cli.yml」組態範例
applicationType: web
defaultPackage: com.example
testFramework: spock
sourceLanguage: groovy
buildTool: gradle
gormImpl: gorm-hibernate5
servletImpl: spring-boot-starter-tomcat
features:
- app-name
- asset-pipeline-grails
- base
- geb
- gorm-hibernate5
- gradle
- grails-application
- grails-console
- grails-dependencies
- grails-gorm-testing-support
- grails-gradle-plugin
- grails-gsp
- grails-url-mappings
- grails-web
- grails-web-testing-support
- h2
- logback
- micronaut-inject-groovy
- readme
- scaffolding
- spock
- spring-boot-autoconfigure
- spring-boot-starter
- spring-boot-starter-tomcat
- yaml
這個「grails-cli.yml」組態設定了 Grails 網路應用程式各個層面的預設值,包括應用程式類型、預設套件、測試架構、原始程式語言、建置工具、GORM 實作、servlet 實作和已啟用功能的清單。
Grails 預設套件組態
專案的預設套件會根據專案名稱來決定。例如,執行下列指令
grails create-app myapp
會將預設套件設定為 myapp
。
如果您希望在建立應用程式時指定自己的預設套件,您可以使用套件為應用程式名稱加上前綴,如下所示
grails create-app com.example.myapp
在此情況下,「com.example」會成為您專案的預設套件。
Gradle 建置工具
Grails 現在使用 Gradle 建置系統來進行專案管理。專案的建置組態會指定在 build.gradle
檔案中,您可以在其中定義專案的重要層面,例如版本、必要的相依性和相依性來源的存放庫。以下是如何執行此動作的範例
plugins {
id 'org.grails.grails-web' version 'x.y.z' // Grails plugin
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.grails:grails-core'
// Add more dependencies as needed...
}
grails {
pathingJar = true
}
使用 Gradle 建置工具
若要與您的 Grails 專案互動並執行與建置和執行相關的各種任務,您應該使用 Gradle 指令。以下是一些範例
-
建置 Grails 應用程式
gradle build
-
執行 Grails 應用程式
gradle bootRun
-
列出可用的 Gradle 任務
gradle tasks
透過呼叫這些 Gradle 指令,您可以有效地管理 Grails 應用程式的生命週期。
重要的是要記住,Grails 利用 Gradle 的功能來簡化專案管理,包括建置自動化和相依性解析。這種方法讓您可以更靈活地控制您的 Grails 專案。
5.1 互動模式
當您在沒有任何參數的情況下執行 grails
命令時,Grails 命令列介面 (CLI) 會進入互動模式。在此模式中,它會像 shell 一樣運作,讓您可以在不需要重新初始化 CLI 執行時間的情況下執行多個 CLI 命令。此模式在使用程式碼產生命令(例如 create-controller
)、建立多個專案或探索各種 CLI 功能時特別有用。
互動模式的其中一個優點是具有 tab 補完功能。您只需按下 TAB 鍵,即可查看特定命令或標記的可用選項。以下是互動模式中可用選項的範例
grails>
--help --verbose -V -v create-app create-domain-class create-restapi create-webapp
--stacktrace --version -h -x create-controller create-plugin create-web-plugin
說明和資訊
您可以使用與特定命令相關聯的說明標記來存取 Grails 命令的一般使用資訊。
grails> create-app -h
Usage: grails create-app [-hivVx] [--list-features] [-g=GORM Implementation] [--jdk=<javaVersion>]
[-s=Servlet Implementation] [-t=TEST] [-f=FEATURE[,FEATURE...]]... [NAME]
Creates an application
[NAME] The name of the application to create.
-f, --features=FEATURE[,FEATURE...]
The features to use. Possible values: h2, scaffolding, gorm-hibernate5,
spring-boot-starter-jetty, springloaded, spring-boot-starter-tomcat,
micronaut-http-client, cache-ehcache, hibernate-validator, postgres,
mysql, cache, database-migration, grails-gsp, hamcrest, gorm-mongodb,
assertj, mockito, spring-boot-starter-undertow, micronaut-inject-groovy,
github-workflow-java-ci, jrebel, testcontainers, sqlserver,
grails-console, views-markup, asset-pipeline-grails, views-json,
gorm-neo4j, asciidoctor, embedded-mongodb, grails-web-console,
logbackGroovy, mongo-sync, shade, geb, properties
-g, --gorm=GORM Implementation
Which GORM Implementation to configure. Possible values: hibernate,
mongodb, neo4j.
-h, --help Show this help message and exit.
-i, --inplace Create a service using the current directory
--jdk, --java-version=<javaVersion>
The JDK version the project should target
--list-features Output the available features and their descriptions
-s, --servlet=Servlet Implementation
Which Servlet Implementation to configure. Possible values: none, tomcat,
jetty, undertow.
-t, --test=TEST Which test framework to use. Possible values: junit, spock.
-v, --verbose Create verbose output.
-V, --version Print version information and exit.
-x, --stacktrace Show full stack trace when exceptions occur.
您也可以使用任何建立命令中的 --list-features 標記來取得可用功能的清單。
grails> create-app --list-features
Available Features
(+) denotes the feature is included by default
Name Description
---------------------------------- ---------------
CI/CD
github-workflow-java-ci [PREVIEW] Adds a Github Actions Workflow to Build and Test Grails Application
Cache
cache The Grails Cache plugin provides powerful and easy to use caching functionality to Grails applications and plugins.
cache-ehcache The Grails Cache Ehcache plugin extends the Cache plugin and uses Ehcache as the storage provider for cached content.
Client
micronaut-http-client Adds support for the Micronaut HTTP client
Configuration
properties Creates a properties configuration file
Database
database-migration Adds support for Liquibase database migrations. The Database Migration plugin helps you manage database changes while developing Grails applications.
embedded-mongodb Executes an embedded mongo database for integration or functional testing
gorm-hibernate5 (+) Adds support for Hibernate5 using GORM
gorm-mongodb Configures GORM for MongoDB for Groovy applications
gorm-neo4j Configures GORM for Neo4j for Groovy applications
h2 (+) Adds the H2 driver and default config
mongo-sync Adds support for the MongoDB Synchronous Driver
mysql Adds the MySQL driver and default config
postgres Adds the PostgresSQL driver and default config
sqlserver Adds the SQL Server driver and default config
testcontainers Use Testcontainers to run a database or other software in a Docker container for tests
Development Tools
assertj AssertJ fluent assertions framework
hamcrest Hamcrest matchers for JUnit
jrebel Adds support for class reloading with JRebel (requires separate JRebel installation)
springloaded Adds support for class reloading with Spring Loaded
Documentation
asciidoctor Adds support for creating Asciidoctor documentation
Logging
logbackGroovy Gives you the ability to use groovy to configure logback instead of XML.
Management
grails-web-console A web-based Groovy console for interactive runtime application management and debugging
Other
geb (+) This plugins configure Geb for Grails framework to write automation tests.
grails-console (+) Starts the Grails console, which is an extended version of the regular Groovy console.
micronaut-inject-groovy (+) micronaut-inject-groovy
scaffolding (+) The Grails® framework Scaffolding plugin replicates much of the functionality from Grails 2, but uses the fields plugin instead.
Packaging
shade Adds the ability to build a Fat/Shaded JAR
Server
spring-boot-starter-jetty spring-boot-starter-jetty
spring-boot-starter-tomcat (+) spring-boot-starter-tomcat
spring-boot-starter-undertow spring-boot-starter-undertow
Validation
hibernate-validator Adds support for the Hibernate Validator
mockito Mockito test mocking framework for JUnit
View Rendering
asset-pipeline-grails (+) The Asset-Pipeline is a plugin used for managing and processing static assets in JVM applications primarily via Gradle (however not mandatory). Read more at https://github.com/bertramdev/asset-pipeline
grails-gsp (+) grails-gsp
views-json JSON views are written in Groovy, end with the file extension gson and reside in the grails-app/views directory. They provide a DSL for producing output in the JSON format.
views-markup Markup views are written in Groovy, end with the file extension gml and reside in the grails-app/views directory. They provide a DSL for producing output in the XML.
5.2 建立自訂命令
在 Grails 中,自訂命令是您可以新增到 Grails 應用程式並透過命令列介面 (CLI) 執行的功能。這些命令不是核心 Grails 架構的一部分,而是您可以建立的擴充功能,用於執行特定任務或作業,這些任務或作業是您的應用程式需求所獨有的。自訂命令是自動化各種任務、與您的應用程式互動以及從命令列執行管理功能的強大方式。當您執行自訂命令時,它們會導致 Grails 環境啟動,讓您可以完全存取應用程式內容和執行時間,讓您可以在自訂命令中視需要使用應用程式的資源、服務和設定。
您可能想為您的 Grails 應用程式撰寫自訂命令的原因有以下幾個
-
自動化任務:自訂命令讓您可以自動化常規任務,例如資料遷移、資料庫更新或批次處理,方法是將邏輯封裝在一個可依需求執行的命令中。
-
管理作業:您可以使用自訂命令執行管理任務,例如使用者管理、系統維護和設定管理,讓您更容易在不同的環境中管理您的應用程式。
-
整合:自訂命令可用於將您的 Grails 應用程式與其他系統或服務整合。例如,您可以建立一個命令來與外部 API 同步資料。
-
自訂工作流程:如果您的應用程式有獨特的工作流程或程序,自訂命令提供一種從命令列執行這些工作流程的方法。
在 Grails 中,您可以透過實作 GrailsApplicationCommand 特質來建立自訂命令。預設情況下,此特質需要您的命令實作 handle() 方法,如下所示
boolean handle()
以這種方式定義的命令仍可透過稱為「executionContext」的變數存取執行內容。 |
以下是如何使用 GrailsApplicationCommand 特質建立自訂命令的逐步指南,其中包含範例,以及如何執行這些命令。
在 Grails 中,您可以透過實作 GrailsApplicationCommand
特質來建立自訂命令。自訂命令讓您可以新增功能到您的 Grails 應用程式,這些功能可透過命令列介面 (CLI) 執行。以下是如何使用 GrailsApplicationCommand
特質建立自訂命令的逐步指南,其中包含範例,以及如何執行這些命令。
步驟 1:建立自訂指令
若要建立自訂指令,您需要建立一個實作 GrailsApplicationCommand
特質的 Groovy 類別。此特質提供指令執行方法。我們來建立一個簡單的範例指令,向使用者問候
// grails-app/commands/com/example/GreetCommand.groovy
package com.example
import grails.cli.GrailsApplicationCommand
class GreetCommand implements GrailsApplicationCommand {
String getName() {
return "greet"
}
String getDescription() {
return "Greet the user"
}
boolean handle() {
println("Hello, user!")
return true // Return true to indicate successful execution
}
}
在此範例中,我們建立一個實作 GrailsApplicationCommand
特質的 GreetCommand
類別。它提供一個 getName()
方法來定義指令名稱、一個 getDescription()
方法提供簡要說明,以及一個 run()
方法來指定指令執行時要執行的程式碼。
步驟 2:建置您的 Grails 應用程式
在使用 runCommand 任務之前,請確定您已使用下列指令建置您的 Grails 應用程式
./gradlew assemble
此指令會編譯您的應用程式,並讓它準備好執行自訂指令。
步驟 3:執行自訂指令
若要執行自訂指令,請使用 Gradle 的 runCommand 任務。開啟您的終端機並導覽至 Grails 應用程式的根目錄。然後,使用下列 Gradle 指令執行自訂指令
./gradlew runCommand -Pargs="greet"
在上述指令中,將「greet」替換為您的自訂指令名稱。這會執行 GreetCommand,您將會看到輸出。
以下是執行 greet 指令時預期的最終輸出
Hello, user!
其他功能:指令參數和選項
Grails 也支援自訂指令的命令列參數和選項。您可以透過實作 GrailsApplicationCommand
介面在您的指令類別中定義這些內容。以下是將名稱作為參數,並提供一個選用 --loud
選項讓問候語更響亮的指令範例
// grails-app/commands/com/example/GreetCommand.groovy
package com.example
import grails.cli.GrailsApplicationCommand
class GreetCommand implements GrailsApplicationCommand {
String getName() {
return "greet"
}
String getDescription() {
return "Greet the user with options"
}
boolean handle() {
def args = commandLine.args
String name = args.size() > 0 ? args[0] : "user"
boolean loud = args.contains("--loud")
if (loud) {
println("HELLO, $name! (LOUD)")
} else {
println("Hello, $name!")
}
return true
}
}
現在您可以使用參數和選項執行 greet
指令
# Greet the user with the default message
./gradlew runCommand -Pargs="greet"
# Greet a specific user
./gradlew runCommand -Pargs="greet Alice"
# Greet loudly
./gradlew runCommand -Pargs="greet --loud"
# Greet a specific user loudly
./gradlew runCommand -Pargs="greet Alice --loud"
這讓您可以為您的 Grails 應用程式建立更多元且互動的自訂指令。
總之,使用 GrailsApplicationCommand
特質在 Grails 中建立自訂指令是擴充您的應用程式功能超越網頁介面的強大方式。您可以定義指令的名稱、說明和邏輯,然後從命令列執行它,並視需要傳遞參數和選項。
在 Grails 自訂指令中使用 executionContext
在 Grails 中,executionContext 是執行時期的內容物件,提供關於 Grails 應用程式目前執行環境的寶貴資訊。它包含應用程式的環境(例如開發、製作、測試)等詳細資訊,並允許開發人員在自訂指令中存取此內容。
Grails 中的自訂指令可以使用 executionContext 根據目前的執行時期環境做出明智的決策,並執行特定任務。例如,開發人員可以在自訂指令中撰寫條件式邏輯,讓指令在製作、開發或測試環境中執行時有不同的行為。這種彈性讓自訂指令可以根據執行它們的內容而調整並表現出不同的行為,讓它們成為管理和擴充 Grails 應用程式的多功能工具。
假設您有一個管理客戶資料的 Grails 應用程式,而且您想要建立一個自訂指令來執行資料備份。在這個情況下,您可能希望備份程序根據您是在開發、測試或生產環境中執行而有不同的行為。
以下是使用 executionContext 來決定備份行為的自訂指令建立範例
// grails-app/commands/com/example/BackupCommand.groovy
package com.example
import grails.cli.GrailsApplicationCommand
class BackupCommand implements GrailsApplicationCommand {
String getName() {
return "backup"
}
String getDescription() {
return "Backup customer data"
}
boolean handle() {
// Access the executionContext to determine the environment
def environment = executionContext.environment
if (environment == "production") {
// Perform a full backup in the production environment
println("Performing a full backup of customer data (Production)")
// Add production-specific backup logic here
} else {
// Perform a partial backup in other environments
println("Performing a partial backup of customer data (Non-production)")
// Add non-production backup logic here
}
return true // Return true to indicate successful execution
}
}
在此範例中
-
名為
BackupCommand
的自訂指令是用來備份客戶資料。 -
它會檢查
executionContext
來決定目前的環境。 -
如果環境是「生產」,它會執行具有生產特定邏輯的完整備份。
-
在所有其他環境中,它會執行具有非生產邏輯的部份備份。
當您使用 ./gradlew runCommand -Pargs="backup"
執行這個自訂指令時,它會根據您是在生產或非生產環境中調整其行為,展示 executionContext
如何用於在實際情況中做出特定於環境的決策。
如何從 Grails 外掛建立自訂指令
您不僅可以在 Grails 應用程式中建立自訂指令,也可以從 Grails 外掛建立。以下是方法
-
建立 Grails 外掛:如果您還沒有 Grails 外掛,您可以使用 Grails 的外掛產生指令來建立一個。例如
grails create-plugin my-plugin
-
定義指令:在您的 Grails 外掛中,透過建立實作
GrailsApplicationCommand
特質或介面的 Groovy 類別來定義自訂指令,提供必要的 method,例如getName()
、getDescription()
和handle()
。 -
建置並封裝外掛:若要發佈外掛,您應該使用 Gradle maven-publish 外掛。更新您的外掛的 build.gradle 檔案,以包含下列設定
publishing { publications { mavenJava(MavenPublication) { from components.java } } repositories { maven { url "file://path/to/your/local/repo" // Adjust the path accordingly } } }
然後,您可以將外掛發佈到您的本機儲存庫
./gradlew publishToMavenLocal
-
將外掛新增為相依性:您應該在 Grails 應用程式的 build.gradle 檔案中將外掛新增為相依性,而不是使用 grails install-plugin 指令。包含下列相依性
dependencies { // ... implementation 'com.example:my-plugin:1.0.0' // Replace with your plugin's group and version // ... }
務必將「com.example:my-plugin:1.0.0」替換為外掛適當的群組和版本
-
執行自訂指令:現在,您可以使用 Gradle
runCommand
工作,從您的 Grails 應用程式的根目錄執行自訂指令,如前所述./gradlew runCommand -Pargs="your-command-name"
將
"your-command-name"
替換為您在外掛程式中定義的客製化指令名稱。
遵循下列步驟,您可以建立並執行 Grails 外掛程式的客製化指令,視需要擴充 Grails 應用程式的功能。此方法讓您可以將客製化功能模組化,並在必要時於多個 Grails 專案中分享。
5.3 建立 Grails 專案
建立專案是 CLI 的主要用途。建立新專案的主要指令為 create-app,它會建立透過 HTTP 通訊的標準 Grails 網路應用程式。對於其他類型的應用程式,請參閱下列文件。
指令 | 說明 | 選項 | 範例 |
---|---|---|---|
create-app / create-webapp |
建立 Grails 網路應用程式 |
|
|
create-restapi |
建立 Grails REST API 應用程式 |
|
|
create-plugin |
建立 Grails 外掛程式應用程式 |
|
|
create-web-plugin |
建立 Grails 網路外掛程式應用程式 |
|
|
| 旗標 | 說明 | 範例
create-
指令旗標
"create-*" 指令用於產生基本的 Grails 專案,允許包含選用旗標來選擇額外功能,以自訂 GORM 設定、內嵌 servlet、測試架構,以及 Java 版本。
旗標 | 說明 | 範例 |
---|---|---|
-jdk, --java-version |
專案應鎖定的 JDK 版本 |
|
-s, --servlet |
要設定的 Servlet 實作。可能的數值:none、tomcat、jetty、undertow。 |
|
-g, --gorm |
要設定的 GORM 實作。可能的數值:hibernate、mongodb、neo4j。 |
|
-t, --test |
要使用的測試架構。可能的數值:junit、spock。 |
|
-f, --features |
要使用的功能。可能的數值:h2、gorm-hibernate5、spring-boot-starter-jetty、springloaded、micronaut-http-client、cache-ehcache、hibernate-validator、postgres、mysql、cache、database-migration、grails-gsp、hamcrest、gorm-mongodb、assertj、mockito、spring-boot-starter-undertow、micronaut-inject-groovy、github-workflow-java-ci、jrebel、testcontainers、sqlserver、grails-console、views-markup、views-json、gorm-neo4j、asciidoctor、embedded-mongodb、grails-web-console、logbackGroovy、mongo-sync、shade、properties |
|
-i, --inplace |
使用目前目錄建立專案 |
|