(Quick Reference)

3 Grails下位バージョンからの更新 - Reference Documentation

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

Version: 2.3.0

Translated by: T.Yamamoto, Japanese Grails Doc Translating Team. Special thanks to NTT Software.

3 Grails下位バージョンからの更新

A number of changes need to considered when upgrading your application from Grails 2.2, including:
Grails 2.2 から更新する際にいくつか考慮する点があります。

h4. New Data Binder


There is a new data binding mechanism written from the ground up to meet Grails' needs. If you wish to continue using Spring for data binding then you must set the grails.databinding.useSpringBinder property to true in grails-app/conf/Config.groovy

h4. Dependency Resolution changes


Although dependency resolution using Ivy is still supported, the default for Grails 2.3 is to use Aether and the Ivy support will not be improved upon going forward. You may wish to consider using Aether instead for your existing applications by setting the following in grails-app/conf/BuildConfig.groovy:

grails.project.dependency.resolver = "maven" // or ivy

Dependency Metadata Changes

In addition, the POM and dependency metadata for Grails 2.3 has been re-arranged and cleaned up so that only direct dependencies are specified for an application and all other dependencies are inherited transitvely. This has implications to the upgrade since, for example, Ehcache is now a transitive dependency of the Hibernate plugin, whilst before it was a direct dependency. If get a compilation error related to Ehcache, it is most likely that you don't have the Hibernate plugin installed and need to directly declare the Ehcache dependency:

compile "net.sf.ehcache:ehcache-core:2.4.6"

In addition, excludes may no longer work and may need adjusting when upgrading due to how the metadata has changed. Run the dependency-report to see the new dependency metadata and make adjustments accordingly.

A common error that may occur when upgrading is:

| Configuring classpath
:: problems summary ::
    ::          UNRESOLVED DEPENDENCIES         ::
    :: org.springframework#spring-test;3.2.2.RELEASE: configuration 
    not found in org.springframework#spring-test;3.2.2.RELEASE: 'compile'. 
    It was required from org.grails#grails-plugin-testing;2.3.0.BUILD-SNAPSHOT compile

This is caused by a plugin that depends on an old version of spring-test (for example the Mail plugin). To correct this run grails dependency-report and search for plugins that have a transitive dependency on spring-test and exclude them. For example:

plugins {
  compile ':mail:1.0', {
    excludes 'spring-test'

However, longer term to solve problems like this we recommend that users move away from Ivy and use Aether instead for dependency resolution:


h4. No initial offline mode with Aether


Aether does not support resolving dependencies from a flat file system. This means that the jars we ship with Grails in GRAILS_HOME/lib are not used for the first resolve, but instead the jars are obtained from Maven central. After they have been obtained from Maven central then Aether operates fine offline.

If however you do not have the necessary jars in your local Maven repository, then the only way to get offline execution is to enable Ivy via BuildConfig (see above).

Scaffolding moved to a plugin and rewritten

If you have dynamically scaffolded controllers in your application then you will need to configure the 1.0 version of the Scaffolding plugin in BuildConfig:

plugins {
  compile ':scaffolding:1.0.0'

By default for new applications the 2.0 version of the scaffolding plugin is used, which is not backwards compatible with 1.0.

h4. Forked Execution for Testing


Tests are now by default executed in a forked JVM (although this can be disabled). One implication of this is that tests will be slower to execute when using:

grails test-app

The reason for this is the need to load a separate JVM to execute tests. To mitigate this Grails interactive mode has been updated to load a background JVM that can be resumed. If you do:

$ grails // load interactive mode
$ grails -> test-app
$ grails -> test-app

Test execution will be noticably faster and is the recommended way to run tests in Grails. On older hardware that does not include multiple cores (to run the separate JVMs) it is recommended you disable forked execution for tests to achieve faster test execution times:

forkConfig = [maxMemory: 1024, minMemory: 64, debug: false, maxPerm: 256]
grails.project.fork = [
   test: false, // disable forked execution for test-app
   run: forkConfig, // configure settings for the run-app JVM

h4. Forked Execution and the Reloading Agent


In Grails 2.3 the reloading agent is no longer on the build system path unless you pass the -reloading flag to the grails command:

grails -reloading run-app

The reason for this is that the default in Grails 2.3 and above is to load Grails application in a forked JVM and enable the agent for the forked JVM. If you do not wish to use forked JVMs then you must ensure that you run Grails with the -reloading flag. Alternatively, you can enable forking with the following configuration in BuildConfig:

forkConfig = [maxMemory: 1024, minMemory: 64, debug: false, maxPerm: 256]
grails.project.fork = [
   test: forkConfig, // configure settings for the test-app JVM
   run: forkConfig, // configure settings for the run-app JVM
   war: forkConfig, // configure settings for the run-war JVM
   console: forkConfig // configure settings for the Swing console JVM

h4. Forked Execution and Remote Debugging


The grails-debug command will no longer work with Grails for remote debugging sessions. The reason is the command enabled debugging for the build system JVM, but not the JVM used in forked execution. The solution to this is to use the debug-fork command line argument:

grails --debug-fork run-app

Alternatively you can set the debug setting to true in BuildConfig and use the regular grails command to execute:

forkConfig = [maxMemory: 1024, minMemory: 64, debug: true, maxPerm: 256]
grails.project.fork = [
   run: forkConfig, // configure settings for the run-app JVM

h4. Changes to Core plugin versioning schemes and the Upgrade command


Core plugins like tomcat and hibernate are no longer versioned the same as the Grails version, instead they are versioned according to the Tomcat and Hibernate version they target. If you are upgrading from Grails 2.2 you need to manually configure the correct Tomcat and Hibernate plugins in BuildConfig. The upgrade command will not do this for you!

plugins {
        // plugins for the build system only
        build ':tomcat:'

// plugins needed at runtime but not for compilation runtime ':hibernate:3.6.10.M3' }


Note that the upgrade command will be deprecated in 2.3 and replaced with a command named use-current-grails-version, which will make no attempts to automatically upgrade Grails applications.

h4. Encoding / Escaping (XSS) Changes


Grails 2.3 includes new features to help prevent XSS attacks. These are enabled by default for new applications, but older applications will require manual intervention. See the section on Cross Site Scripting (XSS) prevention for how to appropriately configure XSS prevention.




Although the Grails development team have tried to keep breakages to a minimum there are a number of items to consider when upgrading a Grails 1.0.x, 1.1.x, 1.2.x, or 1.3.x applications to Grails 2.0. The major changes are described in more detail below, but here's a brief summary of what you might encounter when upgrading from Grails 1.3.x:
Grails開発チームではできる限りの下位互換を心がけていますが、Grails 2.0へ更新する際に、下位バージョンから考慮しなくてはならない内容が幾つか存在します。大きな変更点を以下にまとめます。
  • Dependency resolution has been changed to only use data from the POMs to resolve, this can impact plugins and you may need to republish a plugin with corrected dependency data

* environment bean added by Spring 3.1, which will be auto-wired into properties of the same name.
Spring 3.1によって、同じ名称の環境が environment ビーンが自動追加されます。

* Logging by convention packages have changed, so you may not see the logging output you expect. Update your logging configuration as described below.
  • ロギングDSLのパッケージが変更されたので正常にログ出力がされない場合があります。ログの設定を変更する必要があります。

* HSQLDB has been replaced with H2 as default in-memory database. If you use the former, either change your data source to H2 or add HSQLDB as a runtime dependency.
  • デフォルトのインメモリーデータベースがHSQLDBからH2へ変更になりました。使用している場合はデータソースの設定を変更するか、HSQLDBを依存管理に追加する必要があります。

* The release-plugin command has been removed. You must now install the Release plugin and use its publish-plugin command instead.

* The redirect() method no longer commits the response, so isCommitted() will return false. If you use that method, then call request.isRedirected() instead.
  • redirect()メソッドがレスポンスを返さなくなります。これにより、isCommitted()falseを返す事になります。isCommitted()を使用している場合は、代わりにrequest.isRedirected()を使用しましょう

* The redirect() method now uses the grails.serverURL config setting to generate the redirect URL. You may need to remove the setting, particularly from the development and test environments.
  • redirect()メソッドは、設定のgrails.serverURLを使用してリダイレクトのURLを生成するようになります。developmentとtestの環境設定からgrails.serverURL設定を外す必要があります。

* withFormat() no longer takes account of the request content type. If you want to do something based on the request content type, use request.withFormat().
  • withFormat()がリクエストコンテントタイプを取得しなくなりました。リクエストコンテントタイプでの動作を実装する場合は、request.withFormat()を使用してください。

* Adaptive AJAX tags using Prototype will break. In this situation you must install the new Prototype plugin.
  • Prototypeを使用したAJAXタグは動作しません。必要であれば、Prototypeプラグインをインストールしてください。

* If you install Resources (or it is installed automatically), tags like <g:javascript> won't write anything to the page until you add the <r:layoutResources/> tags to your layout.
  • Resourcesプラグインをインストールした場合(または、自動的にインストールされた場合)、<r:layoutResources/>をレイアウトに記述するまで、<g:javascript>からは何も出力されません。

* Resources adds a '/static' URL, so you may have to update your access control rules accordingly.
  • ResourcesプラグインはURL '/static'を追加します。それに応じたアクセスコントロールを更新する必要があります。

* Some plugins may fail to install because one or more of their dependencies can not be found. If this happens, the plugin probably has a custom repository URL that you need to add to your project's BuildConfig.groovy.
  • 幾つかのプラグインは依存が見つからなかった際にインストールに失敗する場合があります。その場合は、プラグインがカスタムリポジトリURLを使用している可能性があるので、プロジェクトのBuildConfig.groovyに追加する必要があります。

* The behaviour of abstract domain classes has changed, so if you use them you will either have to move the abstract classes to 'src/groovy' or migrate your database schema and data.
  • 抽象ドメインクラスの振る舞いが変更されました。使用している場合は、抽象クラスを'src/groovy'に移動するか、データベースのスキーマとデータを変更する必要があります。

* Criteria queries default to INNER_JOIN for associations rather than OUTER_JOIN. This may affect some of your result data.
  • クライテリアクエリーのデフォルトがOUTER_JOINからINNER_JOINに変更になりました。幾つかの実装結果に影響が出る可能性があります。

* Constraints declared for non-existent properties will now throw an exception.
  • 存在しないプロパティがconstraintsに定義してある場合、例外を投げるようになりました。

* beforeValidate() may be called two or more times during a request, for example once on save() and once just before the view is rendered.
リクエスト中に beforeValidate() が複数回コールされる可能性があります。例としてsave()で1回そしてビューがレンダリングされる直前など。

* Public methods in controllers will now be treated as actions. If you don't want this, make them protected or private.
  • コントローラ内のパブリックメソッドはアクションとして扱われるようになります。アクションとして扱われたくないメソッドは、protectedまたは、privateに変更してください。

* The new unit testing framework won't work with the old GrailsUnitTestCase class hierarchy. Your old tests will continue to work, but if you wish to use the new annotations, do not extend any of the *UnitTestCase classes.
  • 新ユニットテストフレームワークにより、古いGrailsUnitTestCaseクラス階層は使用できません。新しい仕組みを使用しながら古いテスト仕様で動作させるには、*UnitTestCaseを継承しないようにしてください。

* Output from Ant tasks is now hidden by default. If your scripts are using ant.echo(), ant.input(), etc. you might want to use alternative mechanisms for output.
  • Antタスクからの出力はデフォルトで隠すようになりました。ant.echo(), ant.input()等をスクリプトで使用している場合は、出力用の代替機能を使用してください。

* Domain properties of type java.net.URL may no longer work with your existing data. The serialisation mechanism for them appears to have changed. Consider migrating your data and domain models to String.
  • ドメインプロパティでjava.net.URL型を使用している場合は、既存のデータで動作しません。シリアライゼーションの仕組みが変更になったようです。ドメインモデルとデータをStringに変更することを検討してください。

* The Ivy cache location has changed. If you want to use the old location, configure the appropriate global setting (see below) but be aware that you may run into problems running Grails 1.3.x and 2.x projects side by side.
  • Ivyのキャッシュ場所が変更になりました。古い場所を使用したい場合は、グローバル設定で変更することができます。ただし、1.3.x系と2.x系を平行利用する場合は問題が発生します。

* With new versions of various dependencies, some APIs (such as the Servlet API) may have changed. If you have code that implements any of those APIs, you will need to update it. Problems will typically manifest as compilation errors.
  • 多くのライブラリが新バージョンに変更されました。更新されたライブラリを使用している場合は変更が必要となります。

* The following deprecated classes have been removed: grails.web.JsonBuilder and grails.web.OpenRicoBuilder.
  • 次の非推奨クラスが削除されました: grails.web.JsonBuildergrails.web.OpenRicoBuilder

Upgrading to 2.2 from 2.1 or 2.0

Groovy 2.0

Grails 2.2 ships with Groovy 2.0 which has some language level changes that may require changes to your code or plugins that you use.

Dependency resolution

Grails 2.2 no longer uses the BuildConfig of the plugin for dependency resolution and only uses data provided by POMs, this may impact some plugins that had previously incorrectly specified dependency information.

If you don't want to immediately deal with the changes necessary to upgrade, then you can open BuildConfig and set the legacyResolve settings to true:

grails.project.dependency.resolution = {    
    legacyResolve false 

This is not recommended however, as it will re-enable the previous behavior of using both POM data and BuildConfig to resolve dependencies. The most commmon problem you will face is with plugins that express their dependencies in a scope that is not valid inside a POM (example: "build" scope).

Plugins like this will need to be re-publish with a corrected scope of "compile". If you then specify the plugin as "build" scope in your application, transitive compile and runtime scoped dependencies will be converted to "build" scope as well.

Grails 1.3.xからのアップグレード
Upgrading from Grails 1.3.x

Changes to web.xml template

If you have customized the web.xml provided by grails install-templates then you will need to update this customized template with the latest version provided by Grails. Failing to do so will lead to a ClassNotFoundException for the org.codehaus.groovy.grails.web.util.Log4jConfigListener class.
grails install-templatesで提供されたweb.xmlをカスタマイズしている場合は、最新のGrailsで提供される無いように更新する必要が有ります。変更を行わなかった場合は、org.codehaus.groovy.grails.web.util.Log4jConfigListenerクラスのClassNotFoundExceptionを引き起こします。

Groovy 1.8での変更点
Groovy 1.8 Changes

Groovy 1.8 is a little stricter in terms of compilation so you may be required to fix compilation errors in your application that didn't occur under Grails 1.3.x.
Groovy 1.8ではmコンパイルが少し厳しくなっています。そのため、Grails 1.3.xでは発生しなかったコンパイルエラーに対応する必要があります。

Groovy 1.8 also requires that you update many of the libraries that you may be using in your application. Libraries known to require an upgrade include:
さらに、Groovy 1.8では、アプリケーションで使用している幾つかのライブラリを更新する必要があります。解っている更新が必要なライブラリは以下になります。
  • Spock
  • Geb
  • GMock (upgrade unavailable as of this writing)

新 'environment' ビーン
New 'environment' bean

Spring 3.1 adds a new bean with the name 'environment'. It's of type Environment (in package org.springframework.core.env) and it will automatically be autowired into properties with the same name. This seems to cause particular problems with domain classes that have an environment property. In this case, adding the method: Spring 3.1から'environment'という名称の新規ビーンが追加されました。これはEnvironment型(パッケージorg.springframework.core.env)で、同じ名前のプロパティに自動ワイヤーされます。一部のドメインクラスプロパティでenvironmentの名称をもつ物に問題が起きる可能性があります。その場合次のようにメソッドを追加して回避してください:

void setEnvironment(org.springframework.core.env.Environment env) {}
works around the problem.

HSQLDB Has Been Replaced With H2

HSQLDB is still bundled with Grails but is not configured as a default runtime dependency. Upgrade options include replacing HSQLDB references in DataSource.groovy with H2 references or adding HSQLDB as a runtime dependency for the application.

If you want to run an application with different versions of Grails, it's simplest to add HSQLDB as a runtime dependency, which you can do in BuildConfig.groovy:

// Add HSQLDB as a runtime dependency
grails.project.dependency.resolution = {
    inherits("global") {
    repositories {

dependencies { // HSQLDBの依存定義 (Add HSQLDB as a runtime dependency) runtime 'hsqldb:hsqldb:' } }

A default DataSource.groovy which is compatible with H2 looks like this:

dataSource {
    driverClassName = "org.h2.Driver"
    username = "sa"
    password = ""
// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop','update'
            url = "jdbc:h2:mem:devDb"
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:mem:testDb"
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:prodDb"

Another significant difference between H2 and HSQLDB is in the handling of byte[] domain class properties. HSQLDB's default BLOB size is large and so you typically don't need to specify a maximum size. But H2 defaults to a maximum size of 255 bytes! If you store images in the database, the saves are likely to fail because of this. The easy fix is to add a maxSize constraint to the byte[] property:
他にH2とHSQLDBの重大な違いは、ドメインクラスのプロパティで定義した  byte[] の扱いです。HSQLDBでのBLOBのデフォルトサイズは、大きいので大抵最大サイズを定義する必要が無かったかと思います。H2では最大サイズの初期値が255バイトになっているので、調整する必要があります。調整するには、 制約の maxSize を byte[] のプロパティに定義するだけです。

class MyDomain {
    byte[] data

static constraints = { data maxSize: 1024 * 1024 * 2 // 2MB } }

This constraint influences schema generation, so in the above example H2 will have the data column set to BINARY(2097152) by Hibernate.
上記の制約定義でスキーマ生成を変更します。この例では、dataカラムは、 BINARY(2097152) としてHibernateがセットします。

Abstract Inheritance Changes

In previous versions of Grails abstract classes in grails-app/domain were not treated as persistent. This is no longer the case and has a significant impact on upgrading your application. For example consider the following domain model in a Grails 1.3.x application:
以前のバージョンで、 grails-app/domain に存在する抽象クラスは、永続化対象として扱われませんでした。今後は違うため、アプリケーション更新には重大な影響を与えます。例として以下のようなドメインモデルをGrails-1.3.xで持っていたとします。

abstract class Sellable {

} class Book extends Sellable {


In Grails 1.3.x you would get a BOOK table and the properties from the Sellable class would be stored within the BOOK table. However, in Grails 2.x you will get a SELLABLE table and the default table-per-hierarchy inheritance rules apply with all properties of the Book stored in the SELLABLE table.
Grails 1.3.xの場合は、 BOOK テーブルが生成され、BOOKテーブルに Sellable クラスのプロパティも含まれました。Grails 2.0からは、デフォルトのtable-per-hierarchy (クラス階層ごとのテーブル)継承ルールで、 BOOK クラスの全てのプロパティが含まれた SELLABLE テーブルが生成されます。

You have two options when upgrading in this scenario:

  1. Move the abstract Sellable class into the src/groovy package. If the Sellable class is in the src/groovy directory it will no longer be regarded as persistent.
  2. Use the database migration plugin to apply the appropriate changes to the database (typically renaming the table to the root abstract class of the inheritance tree).

  1. 抽象クラス Sellable をsrc/groovyに移動する。src/groovyに移動すれば永続化対象のクラスとしては認識しません。
  2. データベースマイグレーションプラグイン を使用して、データベースに適した変更を行う。(通常はルート抽象クラスのテーブル名称に変更すれば良いです。)

クライテリアクエリのデフォルトがINNER JOINになります
Criteria Queries Default to INNER JOIN

The previous default of LEFT JOIN for criteria queries across associations is now INNER JOIN.
今まではLEFT JOINがデフォルトでした。これからはINNER JOINになります。

Invalid Constraints Now Thrown an Exception

Previously if you defined a constraint on a property that doesn't exist no error would be thrown:
class Person {
    String name
    static constraints = {
        bad nullable:false // invalid property, no error thrown

Now the above code will result in an exception

Logging By Convention Changes

The packages that you should use for Grails artifacts have mostly changed. In particular:

  • service -> services
  • controller -> controllers
  • tagLib -> taglib (case change)
  • bootstrap -> conf
  • dataSource -> conf

  • service -> services
  • controller -> controllers
  • tagLib -> taglib (Lが小文字に)
  • bootstrap -> conf
  • dataSource -> conf

You can find out more about logging by convention in the main part of the user guide, under "Configuring loggers". This change is a side-effect of injecting the log property into artefacts at compile time.
ログの詳細については、 ユーザガイド を参考にしてください。

jQuery Replaces Prototype

The Protoype Javascript library has been removed from Grails core and now new Grails applications have the jQuery plugin configured by default. This will only impact you if you are using Prototype with the adaptive AJAX tags in your application, e.g. <g:remoteLink/> etc, because those tags will break as soon as you upgrade.

To resolve this issue, simply install the Prototype plugin in your application. You can also remove the prototype files from your web-app/js/prototype directory if you want.
この問題は Prototypeプラグイン をインストールすることで解決できます。Prototypeはプラグイン内から参照するようになるので、不用になるweb-app/js/prototypeディレクトリは削除できます。

The Resources Plugin

The Resources plugin is a great new feature of Grails that allows you to manage static web resources better than before, but you do need to be aware that it adds an extra URL at /static. If you have access control in your application, this may mean that the static resources require an authenticated user to load them! Make sure your access rules take account of the /static URL.

Controller Public Methods

As of Grails 2.0, public methods of controllers are now treated as actions in addition to actions defined as traditional Closures. If you were relying on the use of methods for privacy controls or as helper methods then this could result in unexpected behavior. To resolve this issue you should mark all methods of your application that are not to be exposed as actions as private methods.
Grails 2.0からは、今までのクロージャに加えて、コントローラのパブリックメソッドもアクションとして扱われるようになりました。もし補助機能や内部機能としてメソッドを使用している場合は必ずメソッドを private にしてください。

Command Object Constraints

As of Grails 2.0, constrained properties in command object classes are no longer nullable by default. Nullable command object properties must be explicitly configured as such in the same way that nullable persistent properties in domain classes are configured.
Grails 2.0よりコマンドオブジェクトのプロパティ制約はnullableが既存値ではなくなりました。Nullable指定のコマンドオブジェクトプロパティは明示的に指定する必要があります。指定方法はドメインクラスと同じです。

The redirect Method

The redirect method no longer commits the response. The result of this is code that relies of this behavior will break in 2.0. For example:
リダイレクト redirect メソッドがレスポンスを返さなくなります。以下のコードは2.0では動作しなくなります:

redirect action: "next"
if (response.committed) {
    // do something

In this case in Grails 1.3.x and below the response.committed property would return true and the if block will execute. In Grails 2.0 this is no longer the case and you should instead use the new isRedirected() method of the request object:
このケースが1.3.xの場合では、 response.committed プロパティがtrueを返すため if ブロックが実行されます。Grails 1.4では、同等の動きをしないため、代わりに request インスタンスの isRedirected() メソッドを使用します。

redirect action: "next"
if (request.redirected) {
    // do something

Another side-effect of the changes to the redirect method is that it now always uses the grails.serverURL configuration option if it's set. Previous versions of Grails included default values for all the environments, but when upgrading to Grails 2.0 those values more often than not break redirection. So, we recommend you remove the development and test settings for grails.serverURL or replace them with something appropriate for your application.
他のリダイレクトメソッドへの変更による副作用は、 grails.serverURL が設定されていれば常に使用するという点です。以前のバージョンのGrailsではデフォルトの値を保持していました、Grails 2.0に更新するとそれらを参照するために問題が発生します。したがって、test、developmentの定義から grails.serverURL を外すか、妥当な値に設定することを推奨します。

Content Negotiation

As of Grails 2.0 the withFormat method of controllers no longer takes into account the request content type (dictated by the CONTENT_TYPE header), but instead deals exclusively with the response content type (dictated by the ACCEPT header or file extension). This means that if your application has code that relies on reading XML from the request using withFormat this will no longer work:
Grails 2.0からコントローラのwithFormatメソッドは、リクエストのコンテントタイプ(CONTENT_TYPEヘッダ)を評価しなくなりました。これにかわって、レスポンスのコンテントタイプ(ACCEPTヘッダまたはファイル拡張子)が排他的に処理を行います。これによって今までのアプリケーションのwithFormatを使用してリクエストからXMLを読み込む等のコードは動作しなくなります。

def processBook() {
    withFormat {
        xml {
            // read request XML
        html {
            // read request parameters

Instead you use the withFormat method provided on the request object:
withFormat の代わりに、 request オブジェクトで提供されているwithFormatメソッドを使用できます:

def processBook() {
    request.withFormat {
        xml {
            // read request XML
        html {
            // read request parameters

Unit Test Framework

Grails 2 introduces a new unit testing framework that is simpler and behaves more consistently than the old one. The old framework based on the GrailsUnitTestCase class hierarchy is still available for backwards compatibility, but it does not work with the new annotations.
Grails 2では、古い仕様より単純でかつ安定した、新しいユニットテストフレームワークを実装しています。下位互換としてGrailsUnitTestCaseクラス階層をベースとした古いフレームワークも使用可能です。但し、新しい仕組みのアノテーションとは平行利用できません。

Migrating unit tests to the new approach is non-trivial, but recommended. Here are a set of mappings from the old style to the new:

  1. Remove extends *UnitTestCase and add a @TestFor annotation to the class if you're testing a core artifact (controller, tag lib, domain class, etc.) or @TestMixin(GrailsUnitTestMixin) for non-core artifacts and non-artifact classes.
  2. Add @Mock annotation for domain classes that must be mocked and use new MyDomain().save() in place of mockDomain().
  3. Replace references to mockRequest, mockResponse and mockParams with request, response and params.
  4. Remove references to renderArgs and use the view and model properties for view rendering, or response.text for all others.
  5. Replace references to redirectArgs with response.redirectedUrl. The latter takes into account the URL mappings as is a string URL rather than a map of redirect() arguments.
  6. The mockCommandObject() method is no longer needed as Grails automatically detects whether an action requires a command object or not.

  1. コアアーテファクト(コントローラ、タグリブ、ドメインクラス等)のテストの場合は、 extends *UnitTestCaseを削除して、@TestForアノテーションをクラスに追加します。コアアーティファクト以外やアーティファクト以外の場合は、@TestMixin(GrailsUnitTestMixin)アノテーションを追加します。
  2. モックするドメインクラスで、mockDomain()の代わりに、new MyDomain().save()を使用するために、@Mockアノテーションでドメインクラスを指定します。
  3. mockRequestmockResponsemockParamsへの参照をrequestresponseparamsに変更します。
  4. renderArgsを参照している部分を削除して、viewmodelプロパティをビューレンダリング用に、また他はresponse.textを使用するようにします。
  5. redirectArgsは、response.redirectedUrlに変更します。後者はURLマッピングの内容を、redirect()のマップのでは無く、文字列のURLで返します。
  6. mockCommandObject()メソッドは、アクションが必要であれば自動的にコマンドオブジェクトを認識するため必要無くなりました。

There are other differences, but these are the main ones. We recommend that you read the chapter on testing thoroughly to understand everything that has changed.
他にも違いは多数有りますが、これらがメインとなります。chapter on testingをしっかり読んで理解することを推奨します。

Note that the Grails annotations don't need to be imported in your test cases to run them from the command line, but your IDE may need them. So, here are the relevant classes with packages:
  • grails.test.mixin.TestFor
  • grails.test.mixin.TestMixin
  • grails.test.mixin.Mock
  • grails.test.mixin.support.GrailsUnitTestMixin
  • grails.test.mixin.domain.DomainClassUnitTestMixin
  • grails.test.mixin.services.ServiceUnitTestMixin
  • grails.test.mixin.web.ControllerUnitTestMixin
  • grails.test.mixin.web.FiltersUnitTestMixin
  • grails.test.mixin.web.GroovyPageUnitTestMixin
  • grails.test.mixin.web.UrlMappingsUnitTestMixin
  • grails.test.mixin.webflow/WebFlowUnitTestMixin

Note that you're only ever likely to use the first two explicitly. The rest are there for reference.

Command Line Output

Ant output is now hidden by default to keep the noise in the terminal to a minimum. That means if you use ant.echo in your scripts to communicate messages to the user, we recommend switching to an alternative mechanism.
ターミナルの表示を最小にするためにAnt出力は表示されなくなりました。これによりスクリプトでの出力としての ant.echo からのメッセージは表示されなくなります。それに変わる方法に変更することをお勧めします。

For status related messages, you can use the event system:

event "StatusUpdate", ["Some message"]
event "StatusFinal",  ["Some message"]
event "StatusError",  ["Some message"]

For more control you can use the grailsConsole script variable, which gives you access to an instance of GrailsConsole. In particular, you can log information messages with log() or info(), errors and warnings with error() and warning(), and request user input with userInput().
さらなる制御として、api:grails.build.logging.GrailsConsoleインスタンスにアクセスするスクリプト変数 GrailsConsole|api:grails.build.logging.GrailsConsole] を使用することもできます。特に情報のログをとるための、 log()info() 、エラーや警告用に error()warning() を使用したり、ユーザからの入力を要求する場合は userInput() を使用できます。

Custom Plugin Repositories

Many plugins have dependencies, both other plugins and straight JAR libraries. These are often located in Maven Central, the Grails core repository or the Grails Central Plugin Repository in which case applications are largely unaffected if they upgrade to Grails 2. But sometimes such dependencies are located elsewhere and Grails must be told where they can be found.

Due to changes in the way Grails handles the resolution of dependencies, Grails 2.0 requires you to add any such custom repository locations to your project if an affected plugin is to install properly.

Ivy cache location has changed

The default Ivy cache location for Grails has changed. If the thought of yet another cache of JARs on your disk horrifies you, then you can change this in your settings.groovy:

grails.dependency.cache.dir = "${userHome}/.ivy2/cache"

If you do this, be aware that you may run into problems running Grails 2 and earlier versions of Grails side-by-side. These problems can be avoided by excluding "xml-apis" and "commons-digester" from the inherited global dependencies in Grails 1.3 and earlier projects.

URL Domain Properties

If your domain model has any properties of type java.net.URL, they may cease to work once you upgrade to Grails 2. It seems that the default mapping of URL to database column has changed with the new version of Hibernate. This is a tricky problem to solve, but in the long run it's best if you migrate your URL properties to strings. One technique is to use the database migration plugin to add a new text column and then execute some code in BootStrap (using Grails 1.3.x or earlier) to fetch each row of the table as a domain instance, convert the URL properties to string URLs, and then write those values to the new column.

Updated Underlying APIs

Grails 2.0 contains updated dependencies including Servlet 3.0, Tomcat 7, Spring 3.1, Hibernate 3.6 and Groovy 1.8. This means that certain plugins and applications that depend on earlier versions of these APIs may no longer work. For example the Servlet 3.0 HttpServletRequest interface includes new methods, so if a plugin implements this interface for Servlet 2.5 but not for Servlet 3.0 then said plugin will break. The same can be said of any Spring interface.
Grails 2.0では、Servlet 3.0、Tomcat 7、Spring 3.1、Hibernate 3.6、Groovy 1.8などのライブラリを更新しました。以前のバージョンのプラグインなどでこれらのライブラリに依存がある場合動作しなくなります。例としてServlet 3.0の HttpServletRequest インターフェイスは新しい物を多く含んでいます。この逆もあり得るので、Servlet 2.5のインターフェイスで実装され、Servlet 3.0に存在しない機能を持っているプラグインは動作しません。もちろんこの事はSpringなど他のライブラリにも同じ事が言えます。注意しましょう。

Removal of release-plugin

The built in release-plugin command for releases plugins to the central Grails plugin repository has been removed. The new release plugin should be used instead which provides an equivalent publish-plugin command.
プラグインを公式リポジトリに発行するコマンド release-plugin が除去されました。新たに リリースプラグイン を使用して同じ意味を持つ publish-plugin コマンドを使用してください。

Removal of Deprecated Classes

The following deprecated classes have been removed: grails.web.JsonBuilder, grails.web.OpenRicoBuilder
次のクラスが除去されました。 grails.web.JsonBuilder , grails.web.OpenRicoBuilder

Grails 1.2.x からのアップグレード
Upgrading from Grails 1.2.x

Plugin Repositories

As of Grails 1.3, Grails no longer natively supports resolving plugins against secured SVN repositories. The plugin resolution mechanism in Grails 1.2 and below has been replaced by one built on Ivy, the upside of which is that you can now resolve Grails plugins against Maven repositories as well as regular Grails repositories.
Grails 1.3では、認証付きSVNリポジトリ内のプラグイン解決に標準では対応しなくなりました。Grails 1.2以前のプラグイン解決の仕組みは、Ivyをベースに構築された実装により、Grailsのライブラリと同等にMavenリポジトリを対象に、プラグイン解決の仕組みに変更されました。

Ivy supports a much richer set of repository resolvers for resolving plugins, including support for Webdav, HTTP, SSH and FTP. See the section on resolvers in the Ivy docs for all the available options and the section of plugin repositories in the user guide which explains how to configure additional resolvers.
Ivyでは、WebDAV, HTTP, SSHやFTPなど豊富なリポジトリ解決方法があります。利用可能なオプションについてはIvyのドキュメントのリゾルバのセクションを、追加のリゾルバの設定方法については、このユーザーガイドのプラグイン・リポジトリのセクションを参照してください。

If you still need support for resolving plugins against secured SVN repositories then the IvySvn project provides a set of resolvers for SVN repositories.

Grails 1.1.x からのアップグレード
Upgrading from Grails 1.1.x

翻訳チームの判断により、Grails 1.1.xからの更新は翻訳を行いません。ご了承ください。

Plugin paths

In Grails 1.1.x typically a pluginContextPath variable was used to establish paths to plugin resources. For example:
Grails 1.1.xではプラグイン内のリソースを参照するために変数pluginContextPathが、以下のように使用されていました:

<g:resource dir="${pluginContextPath}/images" file="foo.jpg" />

In Grails 1.2 views have been made plugin aware and this is no longer necessary:
Grails 1.2からはプラグイン認識されるため、この変数は不要になりました:

<g:resource dir="images" file="foo.jpg" />

Additionally the above example will no longer link to an application image from a plugin view. To do so change the above to:

<g:resource contextPath="" dir="images" file="foo.jpg" />

The same rules apply to the javascript and render tags.

Tag and Body return values

Tags no longer return java.lang.String instances but instead return a Grails StreamCharBuffer instance. The StreamCharBuffer class implements all the same methods as String but doesn't extend String, so code like this will break:

def foo = body()
if (foo instanceof String) {
    // do something

In these cases you should check for the java.lang.CharSequence interface, which both String and StreamCharBuffer implement:

def foo = body()
if (foo instanceof CharSequence) {
    // do something

New JSONBuilder

There is a new version of JSONBuilder which is semantically different from the one used in earlier versions of Grails. However, if your application depends on the older semantics you can still use the deprecated implementation by setting the following property to true in Config.groovy:


Validation on Flush

Grails now executes validation routines when the underlying Hibernate session is flushed to ensure that no invalid objects are persisted. If one of your constraints (such as a custom validator) executes a query then this can cause an additional flush, resulting in a StackOverflowError. For example:

static constraints = {
    author validator: { a ->
        assert a != Book.findByTitle("My Book").author

The above code can lead to a StackOverflowError in Grails 1.2. The solution is to run the query in a new Hibernate session (which is recommended in general as doing Hibernate work during flushing can cause other issues):

static constraints = {
    author validator: { a ->
        Book.withNewSession {
            assert a != Book.findByTitle("My Book").author

Grails 1.0.xからのアップグレード
Upgrading from Grails 1.0.x

翻訳チームの判断により、Grails 1.0.xからの更新は翻訳を行いません。ご了承ください。

Groovy 1.6

Grails 1.1 and above ship with Groovy 1.6 and no longer supports code compiled against Groovy 1.5. If you have a library that was compiled with Groovy 1.5 you must recompile it against Groovy 1.6 or higher before using it with Grails 1.1.

Java 5.0

Grails 1.1 now no longer supports JDK 1.4, if you wish to continue using Grails then it is recommended you stick to the Grails 1.0.x stream until you are able to upgrade your JDK.

Configuration Changes

1) The setting grails.testing.reports.destDir has been renamed to grails.project.test.reports.dir for consistency.

2) The following settings have been moved from grails-app/conf/Config.groovy to grails-app/conf/BuildConfig.groovy:

    • grails.config.base.webXml
    • grails.project.war.file (renamed from grails.war.destFile)
    • grails.war.dependencies
    • grails.war.copyToWebApp
    • grails.war.resources

3) The grails.war.java5.dependencies option is no longer supported, since Java 5.0 is now the baseline (see above).

4) The use of jsessionid (now considered harmful) is disabled by default. If your application requires jsessionid you can re-enable its usage by adding the following to grails-app/conf/Config.groovy:


5) The syntax used to configure Log4j has changed. See the user guide section on Logging for more information.

Plugin Changes

As of version 1.1, Grails no longer stores plugins inside your PROJECT_HOME/plugins directory by default. This may result in compilation errors in your application unless you either re-install all your plugins or set the following property in grails-app/conf/BuildConfig.groovy:


Script Changes

1) If you were previously using Grails 1.0.3 or below the following syntax is no longer support for importing scripts from GRAILS_HOME:

grailsHome = Ant.antProject.properties."env.GRAILS_HOME"

includeTargets << new File("${grailsHome}/scripts/Bootstrap.groovy")

Instead you should use the new grailsScript method to import a named script:

includeTargets << grailsScript("_GrailsBootstrap")

2) Due to an upgrade of Gant all references to the variable Ant should be changed to ant.

3) The root directory of the project is no longer on the classpath, so loading a resource like this will no longer work:

def stream = getClass().classLoader.getResourceAsStream(

Instead you should use the Java File APIs with the basedir property:

new File("${basedir}/grails-app/conf/my-config.xml").withInputStream { stream ->
    // read the file

Command Line Changes

The run-app-https and run-war-https commands no longer exist and have been replaced by an argument to run-app:

grails run-app -https

Data Mapping Changes

1) Enum types are now mapped using their String value rather than the ordinal value. You can revert to the old behavior by changing your mapping as follows:

static mapping = {
    someEnum enumType:"ordinal"

2) Bidirectional one-to-one associations are now mapped with a single column on the owning side and a foreign key reference. You shouldn't need to change anything; however you should drop column on the inverse side as it contains duplicate data.

REST Support

Incoming XML requests are now no longer automatically parsed. To enable parsing of REST requests you can do so using the parseRequest argument inside a URL mapping:


Alternatively, you can use the new resource argument, which enables parsing by default: