4 La línea de comando - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: null
Table of Contents
4 La línea de comando
Grails' command line system is built on Gant - a simple Groovy wrapper around Apache Ant.However, Grails takes it further through the use of convention and the
El sistema de comandos de Grails está construido sobre Gant, un envoltorio simple de Apache Ant.Sin embargo, Grails lleva un paso más alla el uso de la convención y del comando grails command. When you type:
grails. Cuando introduces:grails [command name]
Grails searches in the following directories for Gant scripts to execute:
Grails busca en los siguientes directorios scripts de Gant para ejecutar:
USER_HOME/.grails/scriptsPROJECT_HOME/scriptsPROJECT_HOME/plugins/*/scriptsGRAILS_HOME/scripts
Grails will also convert command names that are in lower case form such as run-app into camel case. So typing
Grails convertirá también los nombres de los comandos que están en minúsculas tales como run-app en "camel case", así que introducir:grails run-app
Results in a search for the following files:
Produce una busqueda de los siguientes ficheros:
USER_HOME/.grails/scripts/RunApp.groovyPROJECT_HOME/scripts/RunApp.groovyPLUGINS_HOME/*/scripts/RunApp.groovyGLOBAL_PLUGINS_HOME/*/scripts/RunApp.groovyGRAILS_HOME/scripts/RunApp.groovy
If multiple matches are found Grails will give you a choice of which one to execute.When Grails executes a Gant script, it invokes the "default" target defined in that script. If there is no default, Grails will quit with an error.To get a list of all commands and some help about the available commands type:
Si coincide con varios Grails le dejará elegir cúal se ejecuta.Cuando Grails ejecuta un script de Gant, invoca el target por defecto en es script. Si no hay target por defecto, Grails dejará de ejecutarse y dará un error.grails help
which outputs usage instructions and the list of commands Grails is aware of:
devuelve como salida instrucciones de uso y una lista de los comandos de Grails:Usage (optionals marked with *):
grails [environment]* [target] [arguments]*Examples:
grails dev run-app
grails create-app booksAvailable Targets (type grails help 'target-name' for more info):
grails bootstrap
grails bug-report
grails clean
grails compile
...Refer to the Command Line reference in the Quick Reference menu of the reference guide for more information about individual commands
Consulte la referencia de línea de comandos en el menú de referencia rápida de la guía de referencia para obtener más información sobre cada uno de los comandos.
It's often useful to provide custom arguments to the JVM when running Grails commands, in particular with
A menudo es útil proporcionar argumentos a la JVM cuando se ejecutan comandos de Grails, en particular con run-app where you may for example want to set a higher maximum heap size. The Grails command will use any JVM options provided in the general JAVA_OPTS environment variable, but you can also specify a Grails-specific environment variable too:
run-app donde se puede, por ejemplo, establecer un tamaño máximo más alto al "heap". El comando Grails utilizará todas las opciones JVM proporcionadas en la variable de entorno JAVA_OPTS, pero también se puede especificar una variable de entorno específica de Grails también:export GRAILS_OPTS="-Xmx1G -Xms256m -XX:MaxPermSize=256m"
grails run-appnon-interactive mode
When you run a script manually and it prompts you for information, you can answer the questions and continue running the script. But when you run a script as part of an automated process, for example a continuous integration build server, there's no way to "answer" the questions. So you can pass the--non-interactive switch to the script command to tell Grails to accept the default answer for any questions, for example whether to install a missing plugin.For example:
Modo no interactivo
Cuando se ejecuta un script manualmente, y se solicita información, se puede responder a las preguntas y continuar la ejecución del script. Pero cuando se ejecuta un script como parte de un proceso automatizado, por ejemplo, un servidor de integración continua, no hay manera de responder a las preguntas. Por lo que puede pasar el parámetro--non-interactive al script para decirle a Grails que acepte la respuesta por defecto para cualquier pregunta, por ejemplo, si se instala un plugin que falta.Por ejemplo:grails war --non-interactive
4.1 Modo interactivo
Interactive mode is the a feature of the Grails command line which keeps the JVM running and allows for quicker execution of commands. To activate interactive mode type 'grails' at the command line and then use TAB completion to get a list of commands:
If you need to open a file whilst within interactive mode you can use the
TAB completion also works for class names after the
If you need to run an external process whilst interactive mode is running you can do so by starting the command with a !:
El modo interactivo es una característica de la línea de comandos Grails que mantiene la JVM funcionando y permite ejecutar comandos más rápidamente. Para activar el modo interactivo escriba "grails" en la línea de comandos y después use el tabulador para obtener una lista de comandos:
If you need to open a file whilst within interactive mode you can use the open command which will TAB complete file paths:
TAB completion also works for class names after the create-* commands:
If you need to run an external process whilst interactive mode is running you can do so by starting the command with a !:
Si necesita abrir un archivo cuando esté en modo interactivo se puede utilizar el comando open usando el tabulador para completar las rutas de archivos:
El tabulador también funciona para las clases después del comando create-* :
Si necesita ejecutar un proceso externo, cuando esté en el modo interactivo, puede hacerlo a partir del comando con un !
4.2 Crear Scripts de Gant
You can create your own Gant scripts by running the create-script command from the root of your project. For example the following command:Will create a script called
Puede crear sus propios scripts de Gant mediante la ejecución del comando create-script en la raíz de su proyecto. Por ejemplo, el siguiente comando:grails create-script compile-sources
scripts/CompileSources.groovy. A Gant script itself is similar to a regular Groovy script except that it supports the concept of "targets" and dependencies between them:target(default:"The default target is the one that gets executed by Grails") { depends(clean, compile) }target(clean:"Clean out things") { ant.delete(dir:"output") }target(compile:"Compile some sources") { ant.mkdir(dir:"mkdir") ant.javac(srcdir:"src/java", destdir:"output") }
grails create-script compile-sources
scripts/CompileSources.groovy. Un script de Gant es muy similar a un script normal de Groovy, excepto que soporta el concepto de "targets" y las dependencias entre ellos:target(default:"The default target is the one that gets executed by Grails") { depends(clean, compile) }target(clean:"Clean out things") { ant.delete(dir:"output") }target(compile:"Compile some sources") { ant.mkdir(dir:"mkdir") ant.javac(srcdir:"src/java", destdir:"output") }
As demonstrated in the script above, there is an implicit
Como se demuestra en la secuencia anterior, hay una variable implícita ant variable (an instance of groovy.util.AntBuilder) that allows access to the Apache Ant API.
In previous versions of Grails (1.0.3 and below), the variable was Ant, i.e. with a capital first letter.
You can also "depend" on other targets using the depends method demonstrated in the default target above.
ant (una instancia de groovy.util.AntBuilder) que permite el acceso a la Apache Ant API.
En las versiones anteriores de Grails (1.0.3 y anteriores), la variable era Ant, es decir, con una letra mayúscula en primer lugar.
También puede "depender" de otros targets utilizando el método depends mostrado en el valor default del target anterior.The default target
In the example above, we specified a target with the explicit name "default". This is one way of defining the default target for a script. An alternative approach is to use thesetDefaultTarget() method:
El target predeterminado
En el ejemplo anterior, se especifica un target con el nombre explícito "default". Esta es una manera de definir el target predeterminado para un script. Un enfoque alternativo es el uso del métodosetDefaultTarget():target("clean-compile": "Performs a clean compilation on the app source") { depends(clean, compile) }target(clean:"Clean out things") { ant.delete(dir:"output") }target(compile:"Compile some sources") { ant.mkdir(dir:"mkdir") ant.javac(srcdir:"src/java", destdir:"output") }setDefaultTarget("clean-compile")
This lets you call the default target directly from other scripts if you wish. Also, although we have put the call to
Esto permite llamar al target predeterminado directamente desde otros scripts si así lo desea. Además, aunque hemos puesto la llamada a setDefaultTarget() at the end of the script in this example, it can go anywhere as long as it comes after the target it refers to ("clean-compile" in this case).Which approach is better? To be honest, you can use whichever you prefer - there don't seem to be any major advantages in either case. One thing we would say is that if you want to allow other scripts to call your "default" target, you should move it into a shared script that doesn't have a default target at all. We'll talk some more about this in the next section.
setDefaultTarget() al final de la secuencia de comandos en este ejemplo, puede ir en cualquier lugar, siempre y cuando esté después del objetivo que se refiere ("clean-compile" en este caso).¿Qué enfoque es mejor? En realidad puede utilizar lo que prefiera, no parece haber ninguna ventaja importante en cualquier caso. Una cosa que diría es que si desea permitir que otros scripts llamen a su target por defecto, debe moverse en un script compartido que no tiene un target predeterminado. Hablaremos un poco más sobre esto en la siguiente sección.
4.3 Reusar scripts de Grails
Grails ships with a lot of command line functionality out of the box that you may find useful in your own scripts (See the command line reference in the reference guide for info on all the commands). Of particular use are the compile, package and bootstrap scripts.The bootstrap script for example lets you bootstrap a Spring ApplicationContext instance to get access to the data source and so on (the integration tests use this):
Grails tiene un montón de funcionalidades de serie mediante la línea de comandos que pueden resultar útiles en sus propios scripts (consulte la referencia de la línea de comandos en la Guía de referencia para la información sobre todos los comandos). Particularmente útiles son los scripts compile, package y bootstrap.El script bootstrap por ejemplo le permite iniciar una instancia del Contexto de aplicación de Spring para obtener acceso al origen de datos y así sucesivamente (las pruebas de integración utilizan esto):includeTargets << grailsScript("_GrailsBootstrap")target ('default': "Database stuff") { depends(configureProxy, packageApp, classpath, loadApp, configureApp) Connection c try { c = appCtx.getBean('dataSource').getConnection() // do something with connection } finally { c?.close() } }
Pulling in targets from other scripts
Gant lets you pull in all targets (except "default") from another Gant script. You can then depend upon or invoke those targets as if they had been defined in the current script. The mechanism for doing this is theincludeTargets property. Simply "append" a file or class to it using the left-shift operator:
includeTargets << new File("/path/to/my/script.groovy") includeTargets << gant.tools.Ivy
Usando targets de otros scripts
Gant permite usar todos los targets (excepto el "default") de otro script de Gant. Luego puede depender de o invocar esos targets como si se hubieran definido en el propio script. El mecanismo para hacerlo es el de la propiedadincludeTargets. Simplemente anexe un fichero o una clase a él utilizando el operador de desplazamiento a la izquierda:
includeTargets << File("/path/to/my/script.groovy") nueva
includeTargets << gant.tools.IvyCore Grails targets
As you saw in the example at the beginning of this section, you use neither the File- nor the class-based syntax forincludeTargets when including core Grails targets. Instead, you should use the special grailsScript() method that is provided by the Grails command launcher (note that this is not available in normal Gant scripts, just Grails ones).The syntax for the grailsScript() method is pretty straightforward: simply pass it the name of the Grails script to include, without any path information. Here is a list of Grails scripts that you could reuse:Principales targets de Grails
Como se ha visto en el ejemplo al principio de esta sección, no se utiliza el fichero ni la sintaxis de clases paraincludeTargets cuando se incluyen targets principales de Grails. En su lugar, debe utilizar el método especial grailsScript() proporcionado por el lanzdor del comando Grails (tenga en cuenta que esto no está disponible en scripts de Gant normales, sólo en los de Grails).La sintaxis del método grailsScript() es bastante sencilla: simplemente pas el nombre del script de Grails que se debe incluir, sin ninguna información de ruta de acceso. Aquí hay una lista de los scripts de Grails que podría volver a utilizar:| Script | Description |
|---|---|
| _GrailsSettings | You really should include this! Fortunately, it is included automatically by all other Grails scripts except _GrailsProxy, so you usually don't have to include it explicitly. |
| _GrailsEvents | Include this to fire events. Adds an event(String eventName, List args) method. Again, included by almost all other Grails scripts. |
| _GrailsClasspath | Configures compilation, test, and runtime classpaths. If you want to use or play with them, include this script. Again, included by almost all other Grails scripts. |
| _GrailsProxy | If you don't have direct access to the internet and use a proxy, include this script to configure access through your proxy. |
| _GrailsArgParsing | Provides a parseArguments target that does what it says on the tin: parses the arguments provided by the user when they run your script. Adds them to the argsMap property. |
| _GrailsTest | Contains all the shared test code. Useful if you want to add any extra tests. |
| _GrailsRun | Provides all you need to run the application in the configured servlet container, either normally (runApp/runAppHttps) or from a WAR file (runWar/runWarHttps). |
Script architecture
| Script | Descripción |
|---|---|
| _GrailsSettings | ¡Realmente debería usar esto! Afortunadamente, se usa automáticamente por todos los scripts de Grails excepto _GrailsProxy, por lo que normalmente no tiene que usarlo explícitamente. |
| _GrailsEvents | Use esto para desencadenar eventos. Agrega un método event(String eventName, List args). Una vez más, usada por casi todos los otros scripts de Grails. |
| _GrailsClasspath | Configura el classpath de la compilación, pruebas y tiempo de ejecución. Si desea usarlos o jugar con ellos, use este script. Una vez más, usado por casi todos los otros scripts de Grails. |
| _GrailsProxy | Si no tiene acceso directo a internet y utilizar a un proxy, use esta secuencia de comandos para configurar el acceso a través de proxy. |
| _GrailsArgParsing | Proporciona un target parseArguments que analiza los argumentos proporcionados por el usuario cuando ejecuta el script. Agrega a la propiedad argsMap. |
| _GrailsTest | Contiene todo el código compartido de prueba. Es útil si desea agregar cualquier prueba adicional. |
| _GrailsRun | Ofrece todo que lo necesario para ejecutar la aplicación en el contenedor de servlet configurado, ya sea normalmente (runApp/runAppHttps) o desde un fichero WAR (runWar/runWarHttps). |
Arquitectura un script
You maybe wondering what those underscores are doing in the names of the Grails scripts. That is Grails' way of determining that a script is internal , or in other words that it has not corresponding "command". So you can't run "grails _grails-settings" for example. That is also why they don't have a default target.Internal scripts are all about code sharing and reuse. In fact, we recommend you take a similar approach in your own scripts: put all your targets into an internal script that can be easily shared, and provide simple command scripts that parse any command line arguments and delegate to the targets in the internal script. For example if you have a script that runs some functional tests, you can split it like this:
Tal vez está pensando en lo que están haciendo esos caracteres de subrayado en los nombres de los scripts de Grails. Es la forma de Grails de determinar que una secuencia de comandos es interna , o en otras palabras que tiene "comando" correspondiente. Por lo que no se puede ejecutar "grails _grails-settings" por ejemplo. También es por esto qué no tienen un target predeterminado.Los scripts internos son todo para compartir código y reutilizarlo. De hecho, se recomienda adoptar un enfoque similar en sus propios scripts: poner todos sus targets en un script interno que puede ser fácilmente compartido y proporcionar script simples que analizen cualquier argumentos y deleguen en los targets de los scripts internos. Por ejemplo si tiene una secuencia de comandos que ejecuta algunas pruebas funcionales, se puede dividir así:./scripts/FunctionalTests.groovy:includeTargets << new File("${basedir}/scripts/_FunctionalTests.groovy")target(default: "Runs the functional tests for this project.") { depends(runFunctionalTests) }./scripts/_FunctionalTests.groovy:includeTargets << grailsScript("_GrailsTest")target(runFunctionalTests: "Run functional tests.") { depends(...) … }
Here are a few general guidelines on writing scripts:
Aquí hay unas directrices generales sobre cómo escribir scripts:
- Split scripts into a "command" script and an internal one.
- Put the bulk of the implementation in the internal script.
- Put argument parsing into the "command" script.
- To pass arguments to a target, create some script variables and initialise them before calling the target.
- Avoid name clashes by using closures assigned to script variables instead of targets. You can then pass arguments direct to the closures.
- Dividir los scripts un script de "comando" y uno interno.
- Poner la mayor parte de la implementación en la secuencia de comandos interno.
- Poner el análisis de los parámetros en el script de "comando".
- Para pasar argumentos a un target, crear algunas variables de script e inicializarlas antes de llamar al target.
- Evitar colisiones de nombres utilizando closures asignadas a las variables del script en lugar de targets. Así puede pasar argumentos directamente a las closures.
4.4 Interceptando Eventos
Grails provides the ability to hook into scripting events. These are events triggered during execution of Grails target and plugin scripts.The mechanism is deliberately simple and loosely specified. The list of possible events is not fixed in any way, so it is possible to hook into events triggered by plugin scripts, for which there is no equivalent event in the core target scripts.
Grails proporciona la capacidad de interceptar eventos de scripts. Estos eventos son activados durante la ejecución de scripts de Grails y plugins.El mecanismo es deliberadamente simple y vagamente especificado. La lista de posibles eventos no es fija en modo alguno, por lo que es posible enlazar eventos activados por los scripts de plugin, para los que no hay evento equivalente en los scripts del núcleo.Defining event handlers
Event handlers are defined in scripts called_Events.groovy. Grails searches for these scripts in the following locations:
USER_HOME/.grails/scripts- user-specific event handlersPROJECT_HOME/scripts- applicaton-specific event handlersPLUGINS_HOME/*/scripts- plugin-specific event handlersGLOBAL_PLUGINS_HOME/*/scripts- event handlers provided by global plugins
Definición de manejadores de eventos
Los controladores de eventos se definen en un scripts llamado_Events.groovy. Grails busca estos scripts en las siguientes ubicaciones:
USER_HOME/.grails/scripts- manejadores de eventos específicos del usuario.PROJECT_HOME/scripts- manejadores de eventos específicos de la aplicación.PLUGINS_HOME / * / scripts- manejadores de eventos específicos de plugin.GLOBAL_PLUGINS_HOME / * / scripts- manejadores de eventos proporcionados por plugins globales.
Whenever an event is fired, all the registered handlers for that event are executed. Note that the registration of handlers is performed automatically by Grails, so you just need to declare them in the relevant
Cuando se desencadena un evento, se ejecutan todos los manejadores registrados para ese evento. Tenga en cuenta que el registro de controladores se realiza automáticamente por Grails, por lo que sólo es necesario declararlos en el archivo _Events.groovy file.Event handlers are blocks defined in _Events.groovy, with a name beginning with "event". The following example can be put in your /scripts directory to demonstrate the feature:eventCreatedArtefact = { type, name ->
println "Created $type $name"
}eventStatusUpdate = { msg ->
println msg
}eventStatusFinal = { msg ->
println msg
}_Events.groovy pertinente.Los manejadores de eventos son bloques definidos en _Events.groovy, con un nombre que empieza con "event". En el ejemplo siguiente se puede colocar en el directorio/scripts para demostrar esta característica:eventCreatedArtefact = { type, name ->
println "Created $type $name"
}eventStatusUpdate = { msg ->
println msg
}eventStatusFinal = { msg ->
println msg
}You can see here the three handlers
Aquí puede ver tres controladores eventCreatedArtefact, eventStatusUpdate, eventStatusFinal. Grails provides some standard events, which are documented in the command line reference guide. For example the compile command fires the following events:
CompileStart- Called when compilation starts, passing the kind of compile - source or testsCompileEnd- Called when compilation is finished, passing the kind of compile - source or tests
Triggering events
To trigger an event simply include the Init.groovy script and call the event() closure:eventCreatedArtefact, eventStatusUpdate, eventStatusFinal. Grails proporciona algunos eventos estándar, que se describen en la Guía de referencia de línea de comandos. Por ejemplo, el comando compile dispara los siguientes eventos:
CompileStart- llamado cuando se inicia la compilación, pasando el tipo de compilación - código fuente o pruebasCompileEnd- llamada una vez finalizada la compilación, pasando el tipo de compilación - código fuente o pruebas
Activación de eventos
Para desencadenar un evento simplemente debe incluir la secuencia de comandos Init.groovy y llamar a la closure event():includeTargets << grailsScript("_GrailsEvents")event("StatusFinal", ["Super duper plugin action complete!"])
Common Events
Below is a table of some of the common events that can be leveraged:includeTargets << grailsScript("_GrailsEvents")event("StatusFinal", ["Super duper plugin action complete!"])
Eventos habituales
A continuación es una tabla de algunos de los eventos habituales que se pueden utilizar:| Event | Parameters | Description |
|---|---|---|
| StatusUpdate | message | Passed a string indicating current script status/progress |
| StatusError | message | Passed a string indicating an error message from the current script |
| StatusFinal | message | Passed a string indicating the final script status message, i.e. when completing a target, even if the target does not exit the scripting environment |
| CreatedArtefact | artefactType,artefactName | Called when a create-xxxx script has completed and created an artefact |
| CreatedFile | fileName | Called whenever a project source filed is created, not including files constantly managed by Grails |
| Exiting | returnCode | Called when the scripting environment is about to exit cleanly |
| PluginInstalled | pluginName | Called after a plugin has been installed |
| CompileStart | kind | Called when compilation starts, passing the kind of compile - source or tests |
| CompileEnd | kind | Called when compilation is finished, passing the kind of compile - source or tests |
| DocStart | kind | Called when documentation generation is about to start - javadoc or groovydoc |
| DocEnd | kind | Called when documentation generation has ended - javadoc or groovydoc |
| SetClasspath | rootLoader | Called during classpath initialization so plugins can augment the classpath with rootLoader.addURL(...). Note that this augments the classpath after event scripts are loaded so you cannot use this to load a class that your event script needs to import, although you can do this if you load the class by name. |
| PackagingEnd | none | Called at the end of packaging (which is called prior to the Tomcat server being started and after web.xml is generated) |
| Evento | Parámetros | Descripción |
|---|---|---|
| StatusUpdate | mensaje | Pasa una cadena que indica el Estado y progreso de script actual. |
| StatusError | mensaje | Pasa una cadena que indica un mensaje de error en el script actual. |
| StatusFinal | mensaje | Pasa una cadena que indica el mensaje de estado final del script, es decir, al completar un target, incluso no cierra el entorno de script. |
| CreatedArtefact | artefactType, artefactName | Se llama cuando un script create-xxxx ha terminado y ha creado un artefacto |
| CreatedFile | nombre de archivo | Llamada siempre que se crea un fichero en el proyecto, sin incluir los archivos administrado por Grails. |
| Exiting | returnCode | Se llama cuando el entorno de script está a punto de cerrarse. |
| PluginInstalled | Nombre de Plugin | Se llama después de que se ha instalado un plugin. |
| CompileStart | tipo | Se llama cuando comienza la compilación, pasando el tipo de compilación - código fuente o pruebas |
| CompileEnd | tipo | Se llama cuando finaliza la compilación, pasando el tipo de compilación - código fuente o pruebas |
| DocStart | tipo | Se llama cuando la generación de documentación está a punto de empezar - javadoc o groovydoc |
| DocEnd | tipo | Se llama cuando se ha finalizado la generación de documentación - javadoc o groovydoc |
| SetClasspath | rootLoader | Llamado durante la inicialización del classpath para que los plugins pueda insertar entradas en el classpath con rootLoader.addURL(...). Dese cuenta de que esto inserta nuevas rutas después de que los scripts se cargen por lo que no se puede utilizar esto para cargar una clase su script de eventos necesita, aunque se puede hacer esto si carga la clase por su nombre. |
| PackagingEnd | ninguno | Llamado al final del empaquetamiento (que se llama antes de arrancar el servidor Tomcat y después de generar el web.xml) |
4.5 Personalizar la construcción
Grails is most definitely an opinionated framework and it prefers convention to configuration, but this doesn't mean you can't configure it. In this section, we look at how you can influence and modify the standard Grails build.
Grails es definitivamente un framework opinionado y prefiere la convención sobre la configuración, pero esto no significa que no se pueda configurar. En esta sección, veremos cómo puede influir y modificar el la construcción estándar de Grails.The defaults
The core of the Grails build configuration is thegrails.util.BuildSettings class, which contains quite a bit of useful information. It controls where classes are compiled to, what dependencies the application has, and other such settings.Here is a selection of the configuration options and their default values:
| Property | Config option | Default value |
|---|---|---|
| grailsWorkDir | grails.work.dir | $USER_HOME/.grails/<grailsVersion> |
| projectWorkDir | grails.project.work.dir | <grailsWorkDir>/projects/<baseDirName> |
| classesDir | grails.project.class.dir | <projectWorkDir>/classes |
| testClassesDir | grails.project.test.class.dir | <projectWorkDir>/test-classes |
| testReportsDir | grails.project.test.reports.dir | <projectWorkDir>/test/reports |
| resourcesDir | grails.project.resource.dir | <projectWorkDir>/resources |
| projectPluginsDir | grails.project.plugins.dir | <projectWorkDir>/plugins |
| globalPluginsDir | grails.global.plugins.dir | <grailsWorkDir>/global-plugins |
| verboseCompile | grails.project.compile.verbose | false |
Los valores predeterminados
El núcleo de la configuración de la construcción de Grails es la clasegrails.util.BuildSettings, que contiene bastante información útil. Controla donde se guardan las clases se compiladas, que dependencias tiene la aplicación, y otros ajustes como estos.He aquí una selección de las opciones de configuración y sus valores predeterminados:
| Propiedad | Opción de configuración | Valor por defecto |
|---|---|---|
| grailsWorkDir | grails.work.dir | $USER_HOME/.grails/<grailsVersion> |
| projectWorkDir | grails.project.work.dir | <grailsWorkDir>/projects/<baseDirName> |
| classesDir | grails.project.class.dir | <projectWorkDir>/classes |
| testClassesDir | grails.project.test.class.dir | <projectWorkDir>/test-classes |
| testReportsDir | grails.project.test.reports.dir | <projectWorkDir>/test/reports |
| resourcesDir | grails.project.resource.dir | <projectWorkDir>/resources |
| projectPluginsDir | grails.project.plugins.dir | <projectWorkDir>/plugins |
| globalPluginsDir | grails.global.plugins.dir | <grailsWorkDir>/global-plugins |
| verboseCompile | grails.project.compile.verbose | false |
The
La clase BuildSettings class has some other properties too, but they should be treated as read-only:
| Property | Description |
|---|---|
| baseDir | The location of the project. |
| userHome | The user's home directory. |
| grailsHome | The location of the Grails installation in use (may be null). |
| grailsVersion | The version of Grails being used by the project. |
| grailsEnv | The current Grails environment. |
| compileDependencies | A list of compile-time project dependencies as File instances. |
| testDependencies | A list of test-time project dependencies as File instances. |
| runtimeDependencies | A list of runtime-time project dependencies as File instances. |
BuildSettings también tiene algunas otras propiedades, pero deben ser tratados como de sólo lectura:
| Propiedad | Descripción |
|---|---|
| baseDir | La ubicación del proyecto. |
| userHome | Directorio principal del usuario. |
| grailsHome | La ubicación de la instalación de Grails en uso (puede ser null). |
| grailsVersion | La versión de Grails utilizada por el proyecto. |
| grailsEnv | El entorno actual de Grails. |
| compileDependencies | Una lista de dependencias del proyecto en tiempo de compilación como instancias de File. |
| testDependencies | Una lista de dependencias del proyecto en tiempo de pruebas como instancias de File. |
| runtimeDependencies | Una lista de dependencias del proyecto en tiempo de ejecución como instancias de File. |
Of course, these properties aren't much good if you can't get hold of them. Fortunately that's easy to do: an instance of
Por supuesto, estas propiedades no sirven para nada si no se puede conseguir accceso a ellas. Afortunadamente eso es fácil de hacer: una instancia de BuildSettings is available to your scripts as the grailsSettings script variable. You can also access it from your code by using the grails.util.BuildSettingsHolder class, but this isn't recommended.Overriding the defaults
All of the properties in the first table can be overridden by a system property or a configuration option - simply use the "config option" name. For example, to change the project working directory, you could either run this command:grails -Dgrails.project.work.dir=work compile
BuildSettings está disponible para tus scripts como la variable grailsSettings. También se puede acceder desde el código mediante el uso de la clase grails.util.BuildSettingsHolder, pero esto no es recomendable.Sobreescribiendo los valores predeterminados
Todas las propiedades de la primera tabla se pueden sobreescribir por una propiedad del sistema o una opción de configuración, simplemente usar el nombre de "opción de configuración". Por ejemplo, para cambiar el directorio de trabajo del proyecto, podría ejecutar este comando:grails -Dgrails.project.work.dir=work compile
or add this option to your
Note that the default values take account of the property values they depend on, so setting the project working directory like this would also relocate the compiled classes, test classes, resources, and plugins.What happens if you use both a system property and a configuration option? Then the system property wins because it takes precedence over the
o añadir esta opción al archivo grails-app/conf/BuildConfig.groovy file:
grails.project.work.dir = "work"BuildConfig.groovy file, which in turn takes precedence over the default values.The BuildConfig.groovy file is a sibling of grails-app/conf/Config.groovy - the former contains options that only affect the build, whereas the latter contains those that affect the application at runtime. It's not limited to the options in the first table either: you will find build configuration options dotted around the documentation, such as ones for specifying the port that the embedded servlet container runs on or for determining what files get packaged in the WAR file.grails-app/conf/BuildConfig.groovy:
grails.project.work.dir = "work"BuildConfig.groovy, que a su vez tiene prioridad sobre los valores predeterminados.El archivo BuildConfig.groovy es un hermano de grails-app/conf/Config.groovy: la primera contiene opciones que sólo afectan a la construcción, mientras que el segundo contiene opciones que afectan a la aplicación en tiempo de ejecución. No se limita sólo a las opciones de la primera tabla: encontrará las opciones de configuración de generación en esta documentación, como las necesarias para especificar el puerto que se ejecuta el contenedor de servlet embebido o para determinar qué archivos se empaquetan en el archivo WAR.Available build settings
| Name | Description |
|---|---|
| grails.server.port.http | Port to run the embedded servlet container on ("run-app" and "run-war"). Integer. |
| grails.server.port.https | Port to run the embedded servlet container on for HTTPS ("run-app --https" and "run-war --https"). Integer. |
| grails.config.base.webXml | Path to a custom web.xml file to use for the application (alternative to using the web.xml template). |
| grails.compiler.dependencies | Legacy approach to adding extra dependencies to the compiler classpath. Set it to a closure containing "fileset()" entries. These entries will be processed by an AntBuilder so the syntax is the Groovy form of the corresponding XML elements in an Ant build file, e.g. fileset(dir: "$basedir/lib", include: "**/*.class). |
| grails.testing.patterns | A list of Ant path patterns that let you control which files are included in the tests. The patterns should not include the test case suffix, which is set by the next property. |
| grails.testing.nameSuffix | By default, tests are assumed to have a suffix of "Tests". You can change it to anything you like but setting this option. For example, another common suffix is "Test". |
| grails.project.war.file | A string containing the file path of the generated WAR file, along with its full name (include extension). For example, "target/my-app.war". |
| grails.war.dependencies | A closure containing "fileset()" entries that allows you complete control over what goes in the WAR's "WEB-INF/lib" directory. |
| grails.war.copyToWebApp | A closure containing "fileset()" entries that allows you complete control over what goes in the root of the WAR. It overrides the default behaviour of including everything under "web-app". |
| grails.war.resources | A closure that takes the location of the staging directory as its first argument. You can use any Ant tasks to do anything you like. It is typically used to remove files from the staging directory before that directory is jar'd up into a WAR. |
| grails.project.web.xml | The location to generate Grails' web.xml to |
Configuración de construcción disponible
| Nombre | Descripción |
|---|---|
| grails.Server.Port.http | Puerto para ejecutar el contenedor de servlet embebido ("run-app" y "run-war"). Entero. |
| grails.Server.Port.https | Puerto para ejecutar el contenedor de servlet embebido bajo HTTPS ("run-app --https" y "run war --https"). Entero. |
| grails.config.base.webXml | Ruta del archivo web.xml personalizada para utilizar para la aplicación (alternativa al uso de la plantilla de web.xml). |
| grails.compiler.dependencies | Enfoque heredado para agregar dependencias adicionales a los classpath del compilador. Establézcalo en una closure que contenga las entradas "fileset()". Estas entradas serán procesadas por un AntBuilder por lo que la sintaxis es la forma Groovy de los correspondientes elementos XML en un fichero de construcción Ant, por ejemplo, fileset(dir: "$basedir/lib", include: "**/*.class). |
| grails.testing.Patterns | Una lista de patrones de rutas Ant que le permiten controlar qué archivos se incluyen en las pruebas. Los patrones no deben incluir el sufijo de caso de prueba, se establece mediante la propiedad siguiente. |
| grails.testing.nameSuffix | Por defecto, las pruebas se supone que tienen un sufijo de "Tests". Puede cambiarlo a cualquier cosa que le guste asignando esta opción. Por ejemplo, otro sufijo común es "Test". |
| grails.project.war.File | Una cadena que contiene la ruta del archivo WAR generado, junto con su nombre completo (incluye extensión). Por ejemplo, "target/my-app.war". |
| grails.war.dependencies | Una closure que contiene las entradas "fileset()" que permite un control total sobre lo que pasa en el directorio de "WEB-INF/lib" del WAR. |
| grails.war.copyToWebApp | Una closure que contiene las entradas "fileset()" que permite un control total sobre lo que pasa en la raíz del WAR. Reemplaza el comportamiento predeterminado de incluir todo bajo "web-app". |
| grails.war.resources | Una closure que toma la ubicación del directorio provisional (staging) como primer argumento. Puede utilizar cualquier tarea de Ant para hacer cualquier cosa que le guste. Normalmente se utiliza para eliminar archivos del directorio provisional antes de ese directorio jar se incluya en un WAR. |
| grails.project.web.xML | La ubicación en la que se generará el fichero web.xml. |
4.6 Ant y Maven
If all the other projects in your team or company are built using a standard build tool such as Ant or Maven, you become the black sheep of the family when you use the Grails command line to build your application. Fortunately, you can easily integrate the Grails build system into the main build tools in use today (well, the ones in use in Java projects at least).
Si todos los proyectos en su equipo o empresa se construyen utilizando una herramienta de construcción como Ant o Maven, se convierte en la oveja negra de la familia cuando utiliza la línea de comandos de Grails para construir su aplicación. Afortunadamente, puede integrar fácilmente el sistema de construcción de Grails en las principales herramientas de construcción en uso hoy en día (bueno, las que están en uso en proyectos de Java por lo menos).Ant Integration
When you create a Grails application with the create-app command, Grails doesn't automatically create an Antbuild.xml file but you can generate one with the integrate-with command:Integración con Ant
Cuando se crea una aplicación Grails con la create-app, Grails no crea automáticamente un archivo Antbuild.xml pero puede generar una con el comando integrate-with:
grails integrate-with --antThis creates a
Esto crea un archivo build.xml file containing the following targets:
clean- Cleans the Grails applicationcompile- Compiles your application's source codetest- Runs the unit testsrun- Equivalent to "grails run-app"war- Creates a WAR filedeploy- Empty by default, but can be used to implement automatic deployment
ant war
build.xml que contiene los siguientes targets:
clean- Limpia la aplicación Grailscompile- Compila el código fuente de su aplicacióntest- Ejecuta las pruebas unitariasrun- Equivalente a "ejecutar grails-app"war- Crea un archivo WARdeploy- Vacio por defecto, pero puede ser usado para implementar el despliegue automático
ant war
The build file is configured to use Apache Ivy for dependency management, which means that it will automatically download all the requisite Grails JAR files and other dependencies on demand. You don't even have to install Grails locally to use it! That makes it particularly useful for continuous integration systems such as CruiseControl or Jenkins.It uses the Grails Ant task to hook into the existing Grails build system. The task lets you run any Grails script that's available, not just the ones used by the generated build file. To use the task, you must first declare it:
El fichero de construcción está configurado para utilizar Apache Ivy para la gestión de la dependencias, lo que significa que se descargará automáticamente todos los archivos JAR necesarios y otras dependencias bajo demanda. ¡Ni siquiera tiene que instalar Grails localmente para usarlo! Esto lo hace especialmente útil para los sistemas de integración continua, tales como CruiseControl o Jenkins.Use la tarea Ant de Grails para enlazar con el actual sistema de construcción de Grails. La tarea le permite ejecutar cualquier script Grails que esté disponible, no sólo los utilizados por el fichero de construcción generado. Para utilizar la tarea, primero se debe declarar:<taskdef name="grailsTask" classname="grails.ant.GrailsTask" classpathref="grails.classpath"/>
<taskdef name="grailsTask" classname="grails.ant.GrailsTask" classpathref="grails.classpath"/>
This raises the question: what should be in "grails.classpath"? The task itself is in the "grails-bootstrap" JAR artifact, so that needs to be on the classpath at least. You should also include the "groovy-all" JAR. With the task defined, you just need to use it! The following table shows you what attributes are available:
Esto plantea la pregunta: ¿qué debe estar en "grails.classpath"? La tarea en sí misma está en el artefacto JAR "grails-bootstrap", por lo que tiene que estar en el classpath por lo menos. También debe incluir el "groovy-all" JAR. Con la tarea definida, ¡sólo tiene que usarla! La siguiente tabla muestra los atributos que están disponibles:
| Attribute | Description | Required |
|---|---|---|
| home | The location of the Grails installation directory to use for the build. | Yes, unless classpath is specified. |
| classpathref | Classpath to load Grails from. Must include the "grails-bootstrap" artifact and should include "grails-scripts". | Yes, unless home is set or you use a classpath element. |
| script | The name of the Grails script to run, e.g. "TestApp". | Yes. |
| args | The arguments to pass to the script, e.g. "-unit -xml". | No. Defaults to "". |
| environment | The Grails environment to run the script in. | No. Defaults to the script default. |
| includeRuntimeClasspath | Advanced setting: adds the application's runtime classpath to the build classpath if true. | No. Defaults to true. |
| Atributo | Descripción | Requerido |
|---|---|---|
| home | La ubicación del directorio de instalación de Grails que se utilizará para la construcción. | Sí, a menos que se especifique un classpath. |
| classpathref | Classpath para la carga de Grails. Debe incluir el artefacto "grails-bootstrap" y debe incluir "grails-scripts". | Sí, a menos que home se establezca o se utilice un elemento classpath. |
| script | El nombre del script Grails para ejecutar, por ejemplo, "TestApp". | Sí. |
| args | Los argumentos que se pasan al script, por ejemplo, "-unit -xml". | No, por defecto "". |
| environment | El entorno de Grails para ejecutar el script in | No, por defecto los valores del script. |
| includeRuntimeClasspath | Configuración avanzada: añade el classpath de la aplicación al classpath de la construcción si es verdadero. | No, por defecto true. |
The task also supports the following nested elements, all of which are standard Ant path structures:
La tarea también es compatible con los siguientes elementos anidados, todos los cuales son estructuras estándar de Ant:
classpath- The build classpath (used to load Gant and the Grails scripts).compileClasspath- Classpath used to compile the application's classes.runtimeClasspath- Classpath used to run the application and package the WAR. Typically includes everything in @compileClasspath.testClasspath- Classpath used to compile and run the tests. Typically includes everything inruntimeClasspath.
home attribute and put your own dependencies in the lib directory, then you don't even need to use any of them. For an example of their use, take a look at the generated Ant build file for new apps.
classpath- El classpath de construcción (se utiliza para cargar los scripts de Gant y Grails).compileClasspath- Classpath utilizados para compilar las clases de la aplicación.runtimeClasspath- Classpath que se utiliza para ejecutar la aplicación y empaquetar el WAR. Por lo general incluye todo lo de @compileClasspath .testClasspath- Classpath utilizado para compilar y ejecutar las pruebas. Por lo general incluye todo lo de @runtimeClasspath.
home y coloca su propias dependencias en el directorio lib, entonces ni siquiera tiene necesidad de utilizar ninguna de ellas. Para un ejemplo de su uso, eche un vistazo al fichero de construcción generado por Ant para nuevas aplicaciones.
Maven Integration
Grails provides integration with Maven 2 with a Maven plugin. The current Maven plugin is based on but supersedes the version created by Octo, who did a great job with the original.Preparation
In order to use the new plugin, all you need is Maven 2 installed and set up. This is because you no longer need to install Grails separately to use it with Maven!The Maven 2 integration for Grails has been designed and tested for Maven 2.0.9 and above. It will not work with earlier versions.
The default mvn setup DOES NOT supply sufficient memory to run the Grails environment. We recommend that you add the following environment variable setting to prevent poor performance:export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256"
Integración con Maven
Grails ofrece una integración con Maven 2 con un plugin de Maven. El actual plugin de Maven reemplaza y se basa en la versión creada por Octo, que hizo un gran trabajo con el original.Preparación
Para utilizar el nuevo plugin, todo lo que necesita es Maven 2 instalado y configurado. Esto se debe a que ¡ya no es necesario instalar Grails por separado para su uso con Maven!La integración de Maven 2 con Grails ha sido diseñado y probado para Maven 2.0.9 y superiores. No funcionará con versiones anteriores.
La configuración por defecto de Maven no proporciona suficiente memoria para ejecutar el entorno de Grails. Le recomendamos agregar la siguiente variable de entorno a su configuración para evitar que los malos rendimientos:export MAVEN_OPTS="-Xmx512m-XX: MaxPermSize = 256"
Creating a Grails Maven Project
To create a Mavenized Grails project simply run the following command:mvn archetype:generate -DarchetypeGroupId=org.grails \
-DarchetypeArtifactId=grails-maven-archetype \
-DarchetypeVersion=1.3.2 \
-DgroupId=example -DartifactId=my-app<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin><plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>Creación de un proyecto Grails con Maven
Para crear un proyecto Grails "mavenizado" sólo tiene que ejecutar el siguiente comando:mvn archetype: generate-DarchetypeGroupId org.grails =
-DarchetypeArtifactId = grails-maven-arquetipo
-DarchetypeVersion = 1.3.2
-DgroupId = ejemplo-DartifactId = my-app<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin><plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
Then you're ready to create the project structure:
Entonces estás listo para crear la estructura del proyecto:cd my-app mvn initialize
if you see a message similar to this:you need to add the plugins manually to application.properties:Resolving plugin JAR dependencies … :: problems summary :: :::: WARNINGS module not found: org.hibernate#hibernate-core;3.3.1.GAthen runplugins.hibernate=2.0.0 plugins.tomcat=2.0.0and the hibernate and tomcat plugins will be installed.mvn compile
cd mi-app mvn initialize
nullsi usted ve un mensaje similar a este:
Resolving plugin JAR dependencies …
:: problems summary ::
:::: WARNINGS
module not found: org.hibernate#hibernate-core;3.3.1.GAplugins.hibernate = 2.0.0 plugins.tomcat = 2.0.0
mvn compile
Now you have a Grails application all ready to go. The plugin integrates into the standard build cycle, so you can use the standard Maven phases to build and package your app:
Ahora tiene una aplicación Grails lista para funcionar. El plugin se integra en el ciclo estándar de construcción, así que usted puede utilizar el estándar de las fases de Maven para construir y empaquetar su aplicación: mvn clean , mvn compile , mvn test , mvn package , mvn install .You can also use some of the Grails commands that have been wrapped as Maven goals:
grails:create-controller- Calls the create-controller commandgrails:create-domain-class- Calls the create-domain-class commandgrails:create-integration-test- Calls the create-integration-test commandgrails:create-pom- Creates a new Maven POM for an existing Grails projectgrails:create-script- Calls the create-script commandgrails:create-service- Calls the create-service commandgrails:create-taglib- Calls the create-tag-lib commandgrails:create-unit-test- Calls the create-unit-test commandgrails:exec- Executes an arbitrary Grails command line scriptgrails:generate-all- Calls the generate-all commandgrails:generate-controller- Calls the generate-controller commandgrails:generate-views- Calls the generate-views commandgrails:install-plugin- Calls the install-plugin commandgrails:install-templates- Calls the install-templates commandgrails:list-plugins- Calls the list-plugins commandgrails:package- Calls the package commandgrails:run-app- Calls the run-app commandgrails:uninstall-plugin- Calls the uninstall-plugin command
mvn grails:help
mvn clean , mvn compile , mvn test , mvn package , mvn install .También puede utilizar algunos de los comandos de Grails que se han creado como goals de Maven:
grails:create-controller- Invoca el comando create-controllergrails:create-domain-class- Invoca el comando create-domain-classgrails:create-integration-test- Invoca el comando create-integration-testgrails:create-pom- Crea un nuevo POM para un proyecto Grails existente.grails:create-script- Invoca el comando create-scriptgrails:create-service- Invoca el comando create-servicegrails:create-taglib- Invoca el comando create-tag-libgrails:create-unit-test- Invoca el comando create-unit-testgrails:exec- Invoca un script de grails.grails:generate-all- ] Invoca el comando generate-allgrails:generate-controller- ] Invoca el comando generate-controllergrails:generate-views- Invoca el comando generate-viewsgrails:install-plugin- Invoca el comando install-plugingrails:install-templates- Invoca el comando install-templatesgrails:list-plugins- Invoca el comando list-pluginsgrails:package- Invoca el comando packagegrails:run-app- Invoca el comando run-appgrails:uninstall-plugin- Invoca el comando uninstall-plugin
mvn grails:helpMavenizing an existing project
Creating a new project is great way to start, but what if you already have one? You don't want to create a new project and then copy the contents of the old one over. The solution is to create a POM for the existing project using this Maven command (substitute the version number with the grails version of your existing project):mvn org.grails:grails-maven-plugin:1.3.2:create-pom -DgroupId=com.mycompany
mvn package. Note that you have to specify a group ID when creating the POM.You may also want to set target JDK to Java 6; see above.
Mavenizando un proyecto existente
Crear un nuevo proyecto es una buena forma de empezar, pero ¿qué hacer si tenemos un proyecto existente? No queremos crear un nuevo proyecto y luego copiar el contenido del proyecto existente. La solución es crear un POM para el proyecto existente con este comando Maven (sustituya el número de versión con la versión de su proyecto Grails):mvn org.grails: grails-maven-plugin: 1.3.2: create-pom-DgroupId = com.mycompany
mvn package. Tenga en cuenta que se tiene que especificar un ID de grupo al crear el POM.También es posible que desee establecer targets JDK de Java 6, ver arriba.
Adding Grails commands to phases
The standard POM created for you by Grails already attaches the appropriate core Grails commands to their corresponding build phases, so "compile" goes in the "compile" phase and "war" goes in the "package" phase. That doesn't help though when you want to attach a plugin's command to a particular phase. The classic example is functional tests. How do you make sure that your functional tests (using which ever plugin you have decided on) are run during the "integration-test" phase?Fear not: all things are possible. In this case, you can associate the command to a phase using an extra "execution" block:<plugin> <groupId>org.grails</groupId> <artifactId>grails-maven-plugin</artifactId> <version>1.3.2</version> <extensions>true</extensions> <executions> <execution> <goals> … </goals> </execution> <!-- Add the "functional-tests" command to the "integration-test" phase --> <execution> <id>functional-tests</id> <phase>integration-test</phase> <goals> <goal>exec</goal> </goals> <configuration> <command>functional-tests</command> </configuration> </execution> </executions> </plugin>
Agregando comandos Grails a las fases
El POM estándar creado por Grails ya une los comandos Grails con sus fases de construcción correspondientes, por lo que "compile" va en la fase "compile" y "war" va en la fase "package". Sin embargo, esto no ayuda cuando se desea conectar un comando de un plugin con una fase determinada. El ejemplo clásico son la pruebas funcionales. ¿Cómo asegurarse de que las pruebas funcionales (con el plugin que sea) se ejecutan durante la fase "integration-test"?No temas, todo es posible. En este caso, se puede asociar un comando a una fase con un bloque de "execution":<plugin>
<groupId>org.grails</groupId>
<artifactId>grails-maven-plugin</artifactId>
<version>1.3.2</version>
<extensions>true</extensions>
<executions>
<execution>
<goals>
…
</goals>
</execution>
<!-- Add the "functional-tests" command to the "integration-test" phase -->
<execution>
<id>functional-tests</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<command>functional-tests</command>
</configuration>
</execution>
</executions>
</plugin>
This also demonstrates the
Esto también muestra el goal grails:exec goal, which can be used to run any Grails command. Simply pass the name of the command as the command system property, and optionally specify the arguments with the args property:
mvn grails:exec -Dcommand=create-webtest -Dargs=Book
grails:exec, que se puede utilizar para ejecutar cualquier comando de Grails. Basta con pasar el nombre del comando como la propoiedad del sistema command, y, opcionalmente, especificar los argumentos con la propiedad args:mvn grails: exec-Dcommand = a crear webtest-Dargs = Libro
Debugging a Grails Maven Project
Maven can be launched in debug mode using the "mvnDebug" command. To launch your Grails application in debug, simply run:mvnDebug grails:run-app
MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
mvn grails:run-appLa depuración de un proyecto Grails Maven
Maven puede ser lanzado en modo de depuración a través del comando "mvnDebug". Para iniciar su aplicación Grails en depuración, sólo tiene que ejecutar:mvnDebug grails:run-app
MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
mvn grails:run-app
