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