It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now, but since what configuration there is typically a one off, it is best to get it out the way.
With Grails' default settings you can actually develop and application without doing any configuration whatsoever. Grails ships with an embedded container and in-memory HSQLDB meaning there isn't even a database to set-up.
However, typically you want to set-up a real database at some point and the way you do that is described in the following section.
For general configuration Grails provides a file called
grails-app/conf/Config.groovy
. This file uses Groovy's
ConfigSlurper which is very similar to Java properties files except it is pure Groovy hence you can re-use variables and use proper Java types!
You can add your own configuration in here, for example:
Then later in your application you can access these settings in one of two ways. The most common is via the
GrailsApplication object, which is available as a variable in controllers and tag libraries:
assert "world" == grailsApplication.config.foo.bar.hello
The other way involves getting a reference to the
ConfigurationHolder class that holds a reference to the configuration object:
import org.codehaus.groovy.grails.commons.*
…
def config = ConfigurationHolder.config
assert "world" == config.foo.bar.hello
Grails also provides the following configuration options:
grails.config.locations
- The location of properties files or addition Grails Config files that should be merged with main configuration
grails.enable.native2ascii
- Set this to false if you do not require native2ascii conversion of Grails i18n properties files
grails.views.default.codec
- Sets the default encoding regime for GSPs - can be one of 'none', 'html', or 'base64' (default: 'none'). To reduce risk of XSS attacks, set this to 'html'.
grails.views.gsp.encoding
- The file encoding used for GSP source files (default is 'utf-8')
grails.mime.file.extensions
- Whether to use the file extension to dictate the mime type in Content Negotiation
grails.mime.types
- A map of supported mime types used for Content Negotiation
grails.serverURL
- A string specifying the server URL portion of absolute links, including server name e.g. grails.serverURL="http://my.yourportal.com". See createLink.
War generation
grails.war.destFile
- Sets the location where the war command should place the generated WAR file
grails.war.dependencies
- A closure containing Ant builder syntax or a list of JAR filenames. Allows you to customise what libaries are included in the WAR file.
grails.war.java5.dependencies
- A list of the JARs that should be included in the WAR file for JDK 1.5 and above.
grails.war.copyToWebApp
- A closure containing Ant builder syntax that is legal inside an Ant copy, for example "fileset()". Allows you to control what gets included in the WAR file from the "web-app" directory.
grails.war.resources
- A closure containing Ant builder syntax. Allows the application to do any other pre-warring stuff it needs to.
For more information on using these options, see the section on
deployment
Logging Basics
Grails uses its common configuration mechanism to configure the underlying
Log4j log system. To configure logging you must modify the file
Config.groovy
located in the
grails-app/conf
directory.
This single
Config.groovy
file allows you to specify separate logging configurations for
development
,
test
, and
production
environments. Grails processes the
Config.groovy
and configures Log4j appropriately.
Since 1.1 Grails provides a Log4j DSL, that you can use to configure Log4j an example of which can be seen below:
log4j = {
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages' // GSP warn 'org.mortbay.log'
}
Essentially, each method translates into a log level and you can pass the names of the packages you want to log at that level as arguments to the method.
Some useful loggers include:
org.codehaus.groovy.grails.commons
- Core artefact information such as class loading etc.
org.codehaus.groovy.grails.web
- Grails web request processing
org.codehaus.groovy.grails.web.mapping
- URL mapping debugging
org.codehaus.groovy.grails.plugins
- Log plugin activity
org.springframework
- See what Spring is doing
org.hibernate
- See what Hibernate is doing
The Root Logger
The Root logger is the logger that all other loggers inherit from. You can configure the Root logger using the root method:
root {
error()
additivity = true
}
The above example configures the root logger to log messages at the error level and above to the default standard out appender. You can also configure the root logger to log to one or more named appenders:
appenders {
file name:'file', file:'/var/logs/mylog.log'
}
root {
debug 'stdout', 'file'
additivity = true
}
Here the root logger will log to two appenders - the default 'stdout' appender and a 'file' appender.
You can also configure the root logger from the argument passed into the Log4J closure:
log4j = { root ->
root.level = org.apache.log4j.Level.DEBUG
…
}
The closure argument "root" is an instance of
org.apache.log4j.Logger
, so refer to the API documentation for Log4J to find out what properties and methods are available to you.
Custom Appenders
Using the Log4j you can define custom appenders. The following appenders are available by default:
jdbc
- An appender that logs to a JDBC connection
console
- An appender that logs to standard out
file
- An appender that logs to a file
rollingFile
- An appender that logs to rolling set of files
For example to configure a rolling file appender you can do:
log4j = {
appenders {
rollingFile name:"myAppender", maxFileSize:1024, file:"/tmp/logs/myApp.log"
}
}
Each argument passed to the appender maps to a property of underlying
Appender class. The example above sets the
name
,
maxFileSize
and
file
properties of the
RollingFileAppender class.
If you prefer to simply create the appender programmatically yourself, or you have your own appender implementation then you can simply call the
appender
method and appender instance:
import org.apache.log4j.*log4j = {
appenders {
appender new RollingFileAppender(name:"myAppender", maxFileSize:1024, file:"/tmp/logs/myApp.log")
}
}
You can then log to a particular appender by passing the name as a key to one of the log level methods from the previous section:
error myAppender:"org.codehaus.groovy.grails.commons"
Custom Layouts
By default the Log4j DSL assumes that you want to use a
PatternLayout. However, there are other layouts available including:
xml
- Create an XML log file
html
- Creates an HTML log file
simple
- A simple textual log
pattern
- A Pattern layout
You can specify custom patterns to an appender using the
layout
setting:
log4j = {
appenders {
console name:'customAppender', layout:pattern(conversionPattern: '%c{2} %m%n')
}
}
This also works for the built-in appender "stdout", which logs to the console:
log4j = {
appenders {
console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')
}
}
Full stacktraces
When exceptions occur, there can be an awful lot of noise in the stacktrace from Java and Groovy internals. Grails filters these typically irrelevant details and restricts traces to non-core Grails/Groovy class packages.
When this happens, the full trace is always written to the
StackTrace
logger. This logs to a file called
stacktrace.log
- but you can change this in your
Config.groovy
to do anything you like. For example if you prefer full stack traces to go to standard out you can add this line:
error stdout:"StackTrace"
You can completely disable stacktrace filtering by setting the
grails.full.stacktrace
VM property to
true
:
grails -Dgrails.full.stacktrace=true run-app
Logging by Convention
All application artefacts have a dynamically added
log
property. This includes
domain classes,
controllers, tag libraries and so on. Below is an example of its usage:
def foo = "bar"
log.debug "The value of foo is $foo"
Logs are named using the convention
grails.app.<artefactType>.ClassName
. Below is an example of how to configure logs for different Grails artefacts:
log4j = {
// Set level for all application artefacts
info "grails.app"
// Set for a specific controller
debug "grails.app.controller.YourController"
// Set for a specific domain class
debug "grails.app.domain.Book"
// Set for all taglibs
info "grails.app.tagLib"}
The artefacts names are dictated by convention, some of the common ones are listed below:
bootstrap
- For bootstrap classes
dataSource
- For data sources
tagLib
- For tag libraries
service
- For service classes
controller
- For controllers
domain
- For domain entities
Grails provides the following GORM configuration options:
grails.gorm.failOnError
- If set to true
, causes the save() method on domain classes to throw a grails.validation.ValidationException
if validation fails during a save. This option may also be assigned a list of Strings representing package names. If the value is a list of Strings then the failOnError behavior will only be applied to domain classes in those packages (including sub-packages). See the save method docs for more information.
Enable failOnError for all domain classes…
grails.gorm.failOnError=true
Enable failOnError for domain classes by package…
grails.gorm.failOnError = ['com.companyname.somepackage', 'com.companyname.someotherpackage']
grails.gorm.autoFlush
= If set to true
, causes the merge, save and delete methods to flush the session, replacing the need to do something like save(flush: true)
.
Per Environment Configuration
Grails supports the concept of per environment configuration. Both the
Config.groovy
file and the
DataSource.groovy
file within the
grails-app/conf
directory can take advantage of per environment configuration using the syntax provided by
ConfigSlurper As an example consider the following default
DataSource
definition provided by Grails:
dataSource {
pooled = false
driverClassName = "org.hsqldb.jdbcDriver"
username = "sa"
password = ""
}
environments {
development {
dataSource {
dbCreate = "create-drop" // one of 'create', 'createeate-drop','update'
url = "jdbc:hsqldb:mem:devDB"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:hsqldb:mem:testDb"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:hsqldb:file:prodDb;shutdown=true"
}
}
}
Notice how the common configuration is provided at the top level and then an
environments
block specifies per environment settings for the
dbCreate
and
url
properties of the
DataSource
. This syntax can also be used within
Config.groovy
.
Packaging and Running for Different Environments
Grails'
command line has built in capabilities to execute any command within the context of a specific environment. The format is:
grails [environment] [command name]
In addition, there are 3 preset environments known to Grails:
dev
,
prod
, and
test
for
development
,
production
and
test
. For example to create a WAR for the
test
environment you could do:
If you have other environments that you need to target you can pass a
grails.env
variable to any command:
grails -Dgrails.env=UAT run-app
Programmatic Environment Detection
Within your code, such as in a Gant script or a bootstrap class you can detect the environment using the
Environment class:
import grails.util.Environment...switch(Environment.current) {
case Environment.DEVELOPMENT:
configureForDevelopment()
break
case Environment.PRODUCTION:
configureForProduction()
break
}
Per Environment Bootstrapping
Its often desirable to run code when your application starts up on a per-environment basis. To do so you can use the
grails-app/conf/BootStrap.groovy
file's support for per-environment execution:
def init = { ServletContext ctx ->
environments {
production {
ctx.setAttribute("env", "prod")
}
development {
ctx.setAttribute("env", "dev")
}
}
ctx.setAttribute("foo", "bar")
}
Generic Per Environment Execution
The previous
BootStrap
example uses the
grails.util.Environment
class internally to execute. You can also use this class yourself to execute your own environment specific logic:
Environment.executeForCurrentEnvironment {
production {
// do something in production
}
development {
// do something only in development
}
}
Since Grails is built on Java technology to set-up a data source requires some knowledge of JDBC (the technology that doesn't stand for Java Database Connectivity).
Essentially, if you are using another database other than HSQLDB you need to have a JDBC driver. For example for MySQL you would need
Connector/JDrivers typically come in the form of a JAR archive. Drop the JAR into your projects
lib
directory.
Once you have the JAR in place you need to get familiar Grails' DataSource descriptor file located at
grails-app/conf/DataSource.groovy
. This file contains the dataSource definition which includes the following settings:
driverClassName
- The class name of the JDBC driver
username
- The username used to establish a JDBC connection
password
- The password used to establish a JDBC connection
url
- The JDBC URL of the database
dbCreate
- Whether to auto-generate the database from the domain model or not
pooled
- Whether to use a pool of connections (defaults to true)
logSql
- Enable SQL logging
dialect
- A String or Class that represents the Hibernate dialect used to communicate with the database. See the org.hibernate.dialect package for available dialects.
properties
- Extra properties to set on the DataSource bean. See the Commons DBCP BasicDataSource documentation.
A typical configuration for MySQL may be something like:
dataSource {
pooled = true
dbCreate = "update"
url = "jdbc:mysql://localhost/yourDB"
driverClassName = "com.mysql.jdbc.Driver"
username = "yourUser"
password = "yourPassword"
}
When configuring the DataSource do not include the type or the def keyword before any of the configuration settings as Groovy will treat these as local variable definitions and they will not be processed. For example the following is invalid:
dataSource {
boolean pooled = true // type declaration results in local variable
…
}
Example of advanced configuration using extra properties:
dataSource {
pooled = true
dbCreate = "update"
url = "jdbc:mysql://localhost/yourDB"
driverClassName = "com.mysql.jdbc.Driver"
username = "yourUser"
password = "yourPassword"
properties {
maxActive = 50
maxIdle = 25
minIdle = 5
initialSize = 5
minEvictableIdleTimeMillis = 60000
timeBetweenEvictionRunsMillis = 60000
maxWait = 10000
}
}
The previous example configuration assumes you want the same config for all environments: production, test, development etc.
Grails' DataSource definition is "environment aware", however, so you can do:
dataSource {
// common settings here
}
environments {
production {
dataSource {
url = "jdbc:mysql://liveip.com/liveDb"
}
}
}
Since many Java EE containers typically supply
DataSource
instances via the
Java Naming and Directory Interface (JNDI). Sometimes you are required to look-up a
DataSource
via JNDI.
Grails supports the definition of JNDI data sources as follows:
dataSource {
jndiName = "java:comp/env/myDataSource"
}
The format on the JNDI name may vary from container to container, but the way you define the
DataSource
remains the same.
The
dbCreate
property of the
DataSource
definition is important as it dictates what Grails should do at runtime with regards to automatically generating the database tables from
GORM classes. The options are:
create-drop
- Drop and re-create the database when Grails is run
create
- Create the database if it doesn't exist, but don't modify it if it does. Deletes existing data.
update
- Create the database if it doesn't exist, and modify it if it does exist
Both create-drop
and create
will destroy all existing data hence use with caution!
In
development mode
dbCreate
is by default set to "create-drop":
dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop','update'
}
What this does is automatically drop and re-create the database tables on each restart of the application. Obviously this may not be what you want in production.
Although Grails does not currently support Rails-style Migrations out of the box, there are currently three plugins that provide similar capabilities to Grails: Autobase (http://wiki.github.com/RobertFischer/autobase), The LiquiBase plugin and the DbMigrate plugin both of which are available via the grails list-plugins
command
The default configuration file
Config.groovy
in
grails-app/conf
is fine in the majority of cases, but there may be circumstances where you want to maintain the configuration in a file
outside the main application structure. For example if you are deploying to a WAR some administrators prefer the configuration of the application to be externalized to avoid having to re-package the WAR due to a change of configuration.
In order to support deployment scenarios such as these the configuration can be externalized. To do so you need to point Grails at the locations of the configuration files Grails should be using by adding a
grails.config.locations
setting in
Config.groovy
:
grails.config.locations = [ "classpath:${appName}-config.properties",
"classpath:${appName}-config.groovy",
"file:${userHome}/.grails/${appName}-config.properties",
"file:${userHome}/.grails/${appName}-config.groovy"]
In the above example we're loading configuration files (both Java properties files and
ConfigSlurper configurations) from different places on the classpath and files located in
USER_HOME
.
Ultimately all configuration files get merged into the
config
property of the
GrailsApplication object and are hence obtainable from there.
Grails also supports the concept of property place holders and property override configurers as defined in Spring For more information on these see the section on Grails and Spring
Versioning Basics
Grails has built in support for application versioning. When you first create an application with the
create-app command the version of the application is set to
0.1
. The version is stored in the application meta data file called
application.properties
in the root of the project.
To change the version of your application you can run the
set-version command:
The version is used in various commands including the
war command which will append the application version to the end of the created WAR file.
Detecting Versions at Runtime
You can detect the application version using Grails' support for application metadata using the
GrailsApplication class. For example within
controllers there is an implicit
grailsApplication variable that can be used:
def version = grailsApplication.metadata['app.version']
If it is the version of Grails you need you can use:
def grailsVersion = grailsApplication.metadata['app.grails.version']
or the
GrailsUtil
class:
import grails.util.*
def grailsVersion = GrailsUtil.grailsVersion
Since Grails 1.2, the documentation engine that powers the creation of this documentation is available to your Grails projects.
The documentation engine uses a variation on the Textile syntax to automatically create project documentation with smart linking, formatting etc.
Creating project documentation
To use the engine you need to follow a few conventions. Firstly you need to create a
src/docs/guide
directory and then have numbered text files using the
gdoc
format. For example:
+ src/docs/guide/1. Introduction.gdoc
+ src/docs/guide/2. Getting Started.gdoc
The title of each chapter is taken from the file name. The order is dictated by the numerical value at the beginning of the file name.
Creating reference items
Reference items appear in the left menu on the documentation and are useful for quick reference documentation. Each reference item belongs to a category and a category is a directory located in the
src/docs/ref
directory. For example say you defined a new method called
renderPDF
, that belongs to a category called
Controllers
this can be done by creating a gdoc text file at the following location:
+ src/ref/Controllers/renderPDF.gdoc
Configuring Output Properties
There are various properties you can set within your
grails-app/conf/Config.groovy
file that customize the output of the documentation such as:
- grails.doc.authors - The authors of the documentation
- grails.doc.license - The license of the software
- grails.doc.copyright - The copyright message to display
- grails.doc.footer - The footer to use
Other properties such as the name of the documentation and the version are pulled from your project itself.
Generating Documentation
Once you have created some documentation (refer to the syntax guide in the next chapter) you can generate an HTML version of the documentation using the command:
This command will output an
docs/manual/index.html
which can be opened to view your documentation.
Documentation Syntax
As mentioned the syntax is largely similar to Textile or Confluence style wiki markup. The following sections walk you through the syntax basics.
Basic Formatting
Monospace:
monospace
Italic:
italic Bold:
bold
Image:
!http://grails.org/images/new/grailslogo_topNav.png!
Linking
There are several ways to create links with the documentation generator. A basic external link can either be defined using confluence or textile style markup:
[SpringSource|http://www.springsource.com/] or "SpringSource":http://www.springsource.com/
For links to other sections inside the user guide you can use the
guide:
prefix:
[Intro|guide:1. Introduction]
The documentation engine will warn you if any links to sections in your guide break. Sometimes though it is preferable not to hard code the actual names of guide sections since you may move them around. To get around this you can create an alias inside
grails-app/conf/Config.groovy
:
grails.doc.alias.intro="1. Introduction"
And then the link becomes:
This is useful since if you linked the to "1. Introduction" chapter many times you would have to change all of those links.
To link to reference items you can use a special syntax:
In this case the category of the reference item is on the left hand side of the | and the name of the reference item on the right.
Finally, to link to external APIs you can use the
api:
prefix. For example:
[String|api:java.lang.String]
The documentation engine will automatically create the appropriate javadoc link in this case. If you want to add additional APIs to the engine you can configure them in
grails-app/conf/Config.groovy
. For example:
grails.doc.api.org.hibernate="http://docs.jboss.org/hibernate/stable/core/api"
The above example configures classes within the
org.hibernate
package to link to the Hibernate website's API docs.
Lists and Headings
Headings can be created by specifying the letter 'h' followed by a number and then a dot:
h3.<space>Heading3
h4.<space>Heading4
Unordered lists are defined with the use of the * character:
* item 1
** subitem 1
** subitem 2
* item 2
Numbered lists can be defined with the # character:
Tables can be created using the
table
macro:
Name | Number |
---|
Albert | 46 |
Wilma | 1348 |
James | 12 |
{table}
*Name* | *Number*
Albert | 46
Wilma | 1348
James | 12
{table}
Code and Notes
You can define code blocks with the
code
macro:
class Book {
String title
}
{code}
class Book {
String title
}
{code}
The example above provides syntax highlighting for Java and Groovy code, but you can also highlight XML markup:
{code:xml}
<hello>world</hello>
{code}
There are also a couple of macros for displaying notes and warnings:
Note:
This is a note!
{note}
This is a note!
{note}
Warning:
This is a warning!
{warning}
This is a warning!
{warning}
In order to control how JAR dependencies are resolved Grails features (since version 1.2) a dependency resolution DSL that allows you to control how dependencies for applications and plugins are resolved.
Inside the
grails-app/conf/BuildConfig.groovy
file you can specify a
grails.project.dependency.resolution
property that configures how dependencies are resolved:
grails.project.dependency.resolution = {
// config here
}
The default configuration looks like the following:
grails.project.dependency.resolution = {
inherits "global" // inherit Grails' default dependencies
log "warn" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
repositories {
grailsHome() // uncomment the below to enable remote dependency resolution
// from public Maven repositories
//mavenCentral()
//mavenRepo "http://snapshots.repository.codehaus.org"
//mavenRepo "http://repository.codehaus.org"
//mavenRepo "http://download.java.net/maven/2/"
//mavenRepo "http://repository.jboss.com/maven2/
}
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
// runtime 'com.mysql:mysql-connector-java:5.1.5'
}}
The details of the above will be explained in the next few sections.
Grails features 5 dependency resolution configurations (or 'scopes') which you can take advantage of:
-
build
: Dependencies for the build system only
-
compile
: Dependencies for the compile step
-
runtime
: Dependencies needed at runtime but not for compilation (see above)
-
test
: Dependencies needed for testing but not at runtime (see above)
-
provided
: Dependencies needed at development time, but not during WAR deployment
Within the
dependencies
block you can specify a dependency that falls into one of these configurations by calling the equivalent method. For example if your application requires the MySQL driver to function at
runtime
you can specify as such:
runtime 'com.mysql:mysql-connector-java:5.1.5'
The above uses the string syntax which is
group:name:version
. You can also use a map-based syntax:
runtime group:'com.mysql', name:'mysql-connector-java', version:'5.1.5'
Multiple dependencies can be specified by passing multiple arguments:
runtime 'com.mysql:mysql-connector-java:5.1.5',
'net.sf.ehcache:ehcache:1.6.1'// Orruntime(
[group:'com.mysql', name:'mysql-connector-java', version:'5.1.5'],
[group:'net.sf.ehcache', name:'ehcache', version:'1.6.1']
)
Remote Repositories
Grails, when installed, does not use any remote public repositories. There is a default
grailsHome()
repository that will locate the JAR files Grails needs from your Grails installation. If you want to take advantage of a public repository you need to specify as such inside the
repositories
block:
repositories {
mavenCentral()
}
In this case the default public Maven repository is specified. To use the SpringSource Enterprise Bundle Repository you can use the
ebr()
method:
You can also specify a specific Maven repository to use by URL:
repositories {
mavenRepo "http://repository.codehaus.org"
}
Local Resolvers
If you do not wish to use a public Maven repository you can specify a flat file repository:
repositories {
flatDir name:'myRepo', dirs:'/path/to/repo'
}
Custom Resolvers
If all else fails since Grails builds on Apache Ivy you can specify an Ivy resolver:
repositories {
resolver new URLResolver(...)
}
Authentication
If your repository requires some form of authentication you can specify as such using a
credentials
block:
credentials {
realm = ".."
host = "localhost"
username = "myuser"
password = "mypass"
}
The above can also be placed in your
USER_HOME/.grails/settings.groovy
file using the
grails.project.ivy.authentication
setting:
grails.project.ivy.authentication = {
credentials {
realm = ".."
host = "localhost"
username = "myuser"
password = "mypass"
}
}
If you are having trouble getting a dependency to resolve you can enable more verbose debugging from the underlying engine using the
log
method:
// log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
log "warn"
By default every Grails application inherits a bunch of framework dependencies. This is done through the line:
Inside the
BuildConfig.groovy
file. If you wish exclude certain inherited dependencies then you can do so using the
excludes
method:
inherits("global") {
excludes "oscache", "ehcache"
}
Most Grails applications will have runtime dependencies on a lot of jar files that are provided by the Grails framework. These
include libraries like Spring, Sitemesh, Hibernate etc. When a war file is created, all of these dependencies will be included
in it. But, an application may choose to exclude these jar files from the war. This is useful when the jar files will
be provided by the container, as would normally be the case if multiple Grails applications are deployed to the same container.
The dependency resolution DSL provides a mechanism to express that all of the default dependencies will be provided by the container.
This is done by invoking the
defaultDependenciesProvided
method and passing
true
as an argument:
grails.project.dependency.resolution = { defaultDependenciesProvided true // all of the default dependencies will be "provided" by the container inherits "global" // inherit Grails' default dependencies repositories {
grailsHome()
// …
}
dependencies {
// …
}
}
Note that
defaultDependenciesProvided
must come before
inherits
, otherwise the Grails dependencies will be included in the war.
As mentioned in the previous section a Grails application consists of dependencies inherited from the framework, the plugins installed and the application dependencies itself.
To obtain a report of an application's dependencies you can run the
dependency-report command:
This will output a report to the
target/dependency-report
directory by default. You can specify which configuration (scope) you want a report for by passing an argument containing the configuration name:
grails dependency-report runtime
Specifying Plugin JAR dependencies
The way in which you specify dependencies for a
plugin is identical to how you specify dependencies in an application. When a plugin is installed into an application the application automatically inherits the dependencies of the plugin.
If you want to define a dependency that is resolved for use with the plugin but not
exported to the application then you can set the
exported
property of the dependency:
compile( 'org.hibernate:hibernate-core:3.3.1.GA') {
exported = false
}
In this can the
hibernate-core
dependency will be available only to the plugin and not resolved as an application dependency.
Overriding Plugin JAR Dependencies in Your Application
If a plugin is using a JAR which conflicts with another plugin, or an application dependency then you can override how a plugin resolves its dependencies inside an application using the
plugin
method:
plugin("hibernate") {
compile( 'org.hibernate:hibernate-core:3.3.1.GA') {
excludes 'ehcache', 'xml-apis', 'commons-logging'
}
compile 'org.hibernate:hibernate-annotations:3.4.0.GA',
'org.hibernate:hibernate-commons-annotations:3.3.0.ga' runtime 'javassist:javassist:3.4.GA'
}
In this case the application is controlling how the
hibernate
plugin resolves dependencies and not the
hibernate
plugin. If you wish to simply exclude a single dependency resolved by a plugin then you can do so:
plugin("hibernate") {
runtime "cglib:cglib-nodep:2.1_3"
excludes 'javassist:javassist:3.4.GA'
}
When using the Grails Maven plugin, Grails' dependency resolution mechanics are disabled as it is assumed that you will manage dependencies via Maven's
pom.xml
file.
However, if you would like to continue using Grails regular commands like run-app, test-app and so on then you can tell Grails' command line to load dependencies from the Maven
pom.xml
file instead.
To do so simply add the following line to your
BuildConfig.groovy
:
grails.project.dependency.resolution = {
pom true
..
}
The line
pom true
tells Grails to parse Maven's
pom.xml
and load dependencies from there.