5.3 Creating Custom Commands

You can create your own commands by running the create-command command from the root of your project. For example the following command will create a command called grails-app/commands/HelloWorldCommand:

  1. grails create-command HelloWorld
Unlike scripts, commands cause the Grails environment to start and you have full access to the application context and the runtime.

Since Grails 3.2.0, commands have similar abilities as scripts in regards to retrieving arguments, template generation, file access, and model building.

If you created a command in a previous version of grails, you can update your command to have those abilities by changing which trait you are implementing.

Commands created in Grails 3.1.x or lower implement the ApplicationCommand trait by default which requires your command to implement the following method:

  1. boolean handle(ExecutionContext executionContext)

Commands created in Grails 3.2.0 or higher implement the GrailsApplicationCommand trait by default which requires your command to implement the following method:

  1. boolean handle()
Commands defined this way still have access to the execution context via a variable called "executionContext".

Custom commands can be executed using grails run-command:

  1. grails run-command my-example

Commands can also be executed using the runCommand gradle task. Note that the gradle task uses camelCase:

  1. gradle runCommand -Pargs="my-example"

If the grails server is a subproject (e.g., in a project created with the angular profile), the subproject command can still be invoked from the gradle wrapper in the parent project:

  1. ./gradlew server:runCommand -Pargs="my-example"