(Quick Reference)

4.6 Ant y Maven - Reference Documentation

Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith

Version: null

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 Ant build.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 Ant build.xml pero puede generar una con el comando integrate-with:


grails integrate-with --ant

This creates a build.xml file containing the following targets:

  • clean - Cleans the Grails application
  • compile - Compiles your application's source code
  • test - Runs the unit tests
  • run - Equivalent to "grails run-app"
  • war - Creates a WAR file
  • deploy - Empty by default, but can be used to implement automatic deployment

Each of these can be run by Ant, for example:

ant war

Esto crea un archivo build.xml que contiene los siguientes targets:

  • clean - Limpia la aplicación Grails
  • compile - Compila el código fuente de su aplicación
  • test - Ejecuta las pruebas unitarias
  • run - Equivalente a "ejecutar grails-app"
  • war - Crea un archivo WAR
  • deploy - Vacio por defecto, pero puede ser usado para implementar el despliegue automático

Cada uno de ellos se puede ejecutar con Ant, por ejemplo:

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:

<taskdef name="grailsTask"
         classname="grails.ant.GrailsTask"
         classpathref="grails.classpath"/>

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"/>

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:
AttributeDescriptionRequired
homeThe location of the Grails installation directory to use for the build.Yes, unless classpath is specified.
classpathrefClasspath 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.
scriptThe name of the Grails script to run, e.g. "TestApp".Yes.
argsThe arguments to pass to the script, e.g. "-unit -xml".No. Defaults to "".
environmentThe Grails environment to run the script in.No. Defaults to the script default.
includeRuntimeClasspathAdvanced setting: adds the application's runtime classpath to the build classpath if true.No. Defaults to true.

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:

AtributoDescripciónRequerido
homeLa ubicación del directorio de instalación de Grails que se utilizará para la construcción.Sí, a menos que se especifique un classpath.
classpathrefClasspath 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.
scriptEl nombre del script Grails para ejecutar, por ejemplo, "TestApp".Sí.
argsLos argumentos que se pasan al script, por ejemplo, "-unit -xml".No, por defecto "".
environmentEl entorno de Grails para ejecutar el script inNo, por defecto los valores del script.
includeRuntimeClasspathConfiguració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:
  • 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 in runtimeClasspath.

How you populate these paths is up to you. If you use the 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.

La tarea también es compatible con los siguientes elementos anidados, todos los cuales son estructuras estándar de Ant:

  • 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.

Como crear esas rutas depende de usted. Si utiliza el atributo 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

Choose whichever grails version, group ID and artifact ID you want for your application, but everything else must be as written. This will create a new Maven project with a POM and a couple of other files. What you won't see is anything that looks like a Grails application. So, the next step is to create the project structure that you're used to. But first, to set target JDK to Java 6, do that now. Open my-app/pom.xml and change

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <source>1.5</source>
    <target>1.5</target>
  </configuration>
</plugin>
to
<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

Elija la versión de Grails que desee, el identificador de grupo y la identificación de artefactos que desee para su aplicación, pero todo lo demás debe ser escrito como está. Esto creará un nuevo proyecto de Maven con un POM y un otro par de ficheros. Lo que no verá es nada que se parezca a una aplicación Grails. Por lo tanto, el siguiente paso es crear la estructura del proyecto que estamos acostumbrados. Pero primero, para establecer objetivos JDK de Java 6, hagalo ahora. Abra el fichero my-app/pom.xml y modifiquelo:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <source>1.5</source>
    <target>1.5</target>
  </configuration>
</plugin>
to
<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:

cd my-app
mvn initialize

if you see a message similar to this:

Resolving plugin JAR dependencies …
:: problems summary ::
:::: WARNINGS
        module not found: org.hibernate#hibernate-core;3.3.1.GA

you need to add the plugins manually to application.properties:

plugins.hibernate=2.0.0
plugins.tomcat=2.0.0

then run

mvn compile

and the hibernate and tomcat plugins will be installed.

Entonces estás listo para crear la estructura del proyecto:

cd mi-app
mvn initialize

null
si usted ve un mensaje similar a este:

Resolving plugin JAR dependencies …
:: problems summary ::
:::: WARNINGS
        module not found: org.hibernate#hibernate-core;3.3.1.GA

es necesario agregar manualmente los plugins al application.properties:

plugins.hibernate = 2.0.0
plugins.tomcat = 2.0.0

a continuación, ejecute

mvn compile

y el plugin de hibernate y de tomcat se instalarán. {nota}

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: 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:

For a complete, up to date list, run mvn grails:help

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 .

También puede utilizar algunos de los comandos de Grails que se han creado como goals de Maven:

Para una lista completa y actualizada, ejecute mvn grails:help

Mavenizing 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
When this command has finished, you can immediately start using the standard phases, such as 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

Cuando este comando ha terminado, puede comenzar inmediatamente con las fases estándar, tales como 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 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

Esto también muestra el goal 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

The process will be suspended on startup and listening for a debugger on port 8000.

If you need more control of the debugger, this can be specified using the MAVEN_OPTS environment variable, and launch Maven with the default "mvn" command:

MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
mvn grails:run-app

La 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

El proceso será suspendido en el arranque y escucha buscando un depurador en el puerto 8000.

Si necesita más control del depurador, se puede especificar usando la variable de entorno MAVEN_OPTS, y lanzando Maven con el comando por defecto "mvn":

MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
mvn grails:run-app

Raising issues

If you come across any problems with the Maven integration, please raise a JIRA issue as a sub-task of GRAILS-3547.

Notificando problemas

Si te encuentras con algún problema con la integración Maven, por favor, da de alta un asunto en JIRA como una sub-tarea de Grails-3547.