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 thegrails.databinding.useSpringBinder property to true in grails-app/conf/Config.groovyh4. 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 ingrails-app/conf/BuildConfig.groovy:grails.project.dependency.resolver = "maven" // or ivyDependency 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"| Configuring classpath
:: problems summary ::
:::: WARNINGS
::::::::::::::::::::::::::::::::::::::::::::::
:: 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
::::::::::::::::::::::::::::::::::::::::::::::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'
}
}grails.project.dependency.resolver="maven"h4. No initial offline mode with Aether
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'
}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
$ grails // load interactive mode $ grails -> test-app $ grails -> test-app
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
-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
フォーク実行とリモートデバッグ
Thegrails-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
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 liketomcat 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:7.0.40.1' // plugins needed at runtime but not for compilation
runtime ':hibernate:3.6.10.M3'
}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
エンコーディング・エスケーピング(XSS)の変更
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.公式版では以下のドキュメントはこのページに存在しません。公式版で過去の更新注意点を確認する際には該当するバージョンのドキュメントを参照してください。
2.2以前(保存用)
公式版では以下のドキュメントはこのページに存在しません。公式版で過去の更新注意点を確認する際には該当するバージョンのドキュメントを参照してください。
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
*
Spring 3.1によって、同じ名称の環境が environment bean added by Spring 3.1, which will be auto-wired into properties of the same name.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. release-pluginコマンドが無くなります。代わりに、 Releaseプラグイン をインストールして、publish-pluginコマンド を使用してください。
* 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.JsonBuilder、grails.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 openBuildConfig and set the legacyResolve settings to true:grails.project.dependency.resolution = {
…
legacyResolve false
…
}Grails 1.3.xからのアップグレード Upgrading from Grails 1.3.x
web.xmlテンプレートの内容変更 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からH2へ変更 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.
HSQLDBは現在もGrailsにバンドルされていますが、デフォルトでは依存定義されていません。アップグレードした場合はDataSource.groovyのHSQLDB定義をH2に変更するか、依存管理にHSQLDBを追加する必要があります。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:
もしアプリケーションを他のバージョンのGrailsと平行して動作させたい場合は、単純にBuildConfig.groovyの依存定義にHSQLDBを追加しましょう: // Add HSQLDB as a runtime dependency
grails.project.dependency.resolution = {
inherits("global") {
}
repositories {
grailsPlugins()
grailsHome()
grailsCentral()
} dependencies {
// HSQLDBの依存定義 (Add HSQLDB as a runtime dependency)
runtime 'hsqldb:hsqldb:1.8.0.10'
}
}A default DataSource.groovy which is compatible with H2 looks like this:
H2データベースへ変更する場合は、以下を参考にして、DataSource.groovyを変更してください: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
他にH2とHSQLDBの重大な違いは、ドメインクラスのプロパティで定義した 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: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カラムは、 data column set to BINARY(2097152) by Hibernate.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
Grails 1.3.xの場合は、 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.BOOK テーブルが生成され、BOOKテーブルに Sellable クラスのプロパティも含まれました。Grails 2.0からは、デフォルトのtable-per-hierarchy (クラス階層ごとのテーブル)継承ルールで、 BOOK クラスの全てのプロパティが含まれた SELLABLE テーブルが生成されます。You have two options when upgrading in this scenario:
これを更新するには2つの方法があります:- Move the abstract
Sellableclass into the src/groovy package. If theSellableclass is in thesrc/groovydirectory it will no longer be regarded as persistent. - 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).
- 抽象クラス
Sellableをsrc/groovyに移動する。src/groovyに移動すれば永続化対象のクラスとしては認識しません。 - データベースマイグレーションプラグイン を使用して、データベースに適した変更を行う。(通常はルート抽象クラスのテーブル名称に変更すれば良いです。)
クライテリアクエリのデフォルトが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:
以前は存在しないプロパティをconstraintに定義してもエラーが出ませんでした:
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:
Grailsアーテファクトのパッケージのほぼ全てが変更になりました:service->servicescontroller->controllerstagLib->taglib(case change)bootstrap->confdataSource->conf
service->servicescontroller->controllerstagLib->taglib(Lが小文字に)bootstrap->confdataSource->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.PrototypeからjQueryに変更 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.
JavascriptライブラリPrototypeはGrailsのコアから削除されました。今後はjQueryがデフォルトとして定義されます。この変更では、ProtoypeベースのAJAXライブラリを使用してる場合に影響を受けます。例えば<g:remoteLink/>などは、アップデートをしたら直ちに影響を受けます。To resolve this issue, simply install the Prototype plugin in your application. You can also remove the prototype files from your
この問題は Prototypeプラグイン をインストールすることで解決できます。Prototypeはプラグイン内から参照するようになるので、不用になるweb-app/js/prototypeディレクトリは削除できます。web-app/js/prototype directory if you want.Resourcesプラグイン 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
Grails 2.0からは、今までのクロージャに加えて、コントローラのパブリックメソッドもアクションとして扱われるようになりました。もし補助機能や内部機能としてメソッドを使用している場合は必ずメソッドを private methods.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
このケースが1.3.xの場合では、 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: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
Grails 2.0からコントローラのwithFormatメソッドは、リクエストのコンテントタイプ(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: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
Grails 2では、古い仕様より単純でかつ安定した、新しいユニットテストフレームワークを実装しています。下位互換としてGrailsUnitTestCase class hierarchy is still available for backwards compatibility, but it does not work with the new annotations.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:
新しい仕組みのユニットテストへの移行は大変ですが推奨します。以下は古い仕組みから新しい仕組みへ更新する方法です:- Remove
extends *UnitTestCaseand add a@TestForannotation 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. - Add
@Mockannotation for domain classes that must be mocked and usenew MyDomain().save()in place ofmockDomain(). - Replace references to
mockRequest,mockResponseandmockParamswithrequest,responseandparams. - Remove references to
renderArgsand use theviewandmodelproperties for view rendering, orresponse.textfor all others. - Replace references to
redirectArgswithresponse.redirectedUrl. The latter takes into account the URL mappings as is a string URL rather than a map ofredirect()arguments. - The
mockCommandObject()method is no longer needed as Grails automatically detects whether an action requires a command object or not.
- コアアーテファクト(コントローラ、タグリブ、ドメインクラス等)のテストの場合は、
extends *UnitTestCaseを削除して、@TestForアノテーションをクラスに追加します。コアアーティファクト以外やアーティファクト以外の場合は、@TestMixin(GrailsUnitTestMixin)アノテーションを追加します。 - モックするドメインクラスで、
mockDomain()の代わりに、new MyDomain().save()を使用するために、@Mockアノテーションでドメインクラスを指定します。 mockRequest、mockResponse、mockParamsへの参照をrequest、response、paramsに変更します。renderArgsを参照している部分を削除して、viewとmodelプロパティをビューレンダリング用に、また他はresponse.textを使用するようにします。redirectArgsは、response.redirectedUrlに変更します。後者はURLマッピングの内容を、redirect()のマップのでは無く、文字列のURLで返します。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のアノテーションはコマンドラインで実行する場合はインポートする必要が有りませんが、IDEは必要とします。ここに関連するクラスとパッケージを列挙します。
grails.test.mixin.TestForgrails.test.mixin.TestMixingrails.test.mixin.Mockgrails.test.mixin.support.GrailsUnitTestMixingrails.test.mixin.domain.DomainClassUnitTestMixingrails.test.mixin.services.ServiceUnitTestMixingrails.test.mixin.web.ControllerUnitTestMixingrails.test.mixin.web.FiltersUnitTestMixingrails.test.mixin.web.GroovyPageUnitTestMixingrails.test.mixin.web.UrlMappingsUnitTestMixingrails.test.mixin.webflow/WebFlowUnitTestMixin
コマンドライン出力 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出力は表示されなくなりました。これによりスクリプトでの出力としての ant.echo in your scripts to communicate messages to the user, we recommend switching to an alternative mechanism.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
さらなる制御として、api:grails.build.logging.GrailsConsoleインスタンスにアクセスするスクリプト変数 GrailsConsole|api:grails.build.logging.GrailsConsole] を使用することもできます。特に情報のログをとるための、 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().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キャッシュ場所が変更 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"URL型のドメインプロパティ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.基盤となるAPIの更新 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
Grails 2.0では、Servlet 3.0、Tomcat 7、Spring 3.1、Hibernate 3.6、Groovy 1.8などのライブラリを更新しました。以前のバージョンのプラグインなどでこれらのライブラリに依存がある場合動作しなくなります。例として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.HttpServletRequest インターフェイスは新しい物を多く含んでいます。この逆もあり得るので、Servlet 2.5のインターフェイスで実装され、Servlet 3.0に存在しない機能を持っているプラグインは動作しません。もちろんこの事はSpringなど他のライブラリにも同じ事が言えます。注意しましょう。release-pluginコマンド除去 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.OpenRicoBuildergrails.web.JsonBuilder , grails.web.OpenRicoBuilderGrails 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.
認証付きSVNリポジトリ内に対してのプラグイン解決が必要な場合は、SVNリポジトリに対してのIvyリゾルバを提供しているIvySvnプロジェクトを参考にしてください。Grails 1.1.x からのアップグレード Upgrading from Grails 1.1.x
翻訳チームの判断により、Grails 1.1.xからの更新は翻訳を行いません。ご了承ください。
プラグインのパス Plugin paths
In Grails 1.1.x typically a
Grails 1.1.xではプラグイン内のリソースを参照するために変数pluginContextPath variable was used to establish paths to plugin resources. For example: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:
この変更により、上記の例ではプラグイン内のビューからアプリケーション本体の/imagesなどへのパスを生成しません。従って、アプリケーション本体へのパスを生成するためには、次のようにする必要があります:<g:resource contextPath="" dir="images" file="foo.jpg" />
The same rules apply to the javascript and render tags.
javascriptタグやrenderタグも同様の記述ができます。タグとボディの戻り値 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:java.lang.Stringインスタンスを返さず、その代わりにStreamCharBufferインスタンスを返します。StreamCharBufferクラスは、Stringと同じメソッドを実装していますが、このようなコードの場合は破綻します: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:StringとStreamCharBufferの両方が実装しているjava.lang.CharSequenceインタフェースを使用します:def foo = body() if (foo instanceof CharSequence) { // do something }
新しいJSONBuilder 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:grails.json.legacy.builder=trueフラッシュでのバリデーション 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 } }
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 settinggrails.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.webXmlgrails.project.war.file(renamed fromgrails.war.destFile)grails.war.dependenciesgrails.war.copyToWebAppgrails.war.resources
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:grails.views.enable.jsessionid=truePlugin Changes
As of version 1.1, Grails no longer stores plugins inside yourPROJECT_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:grails.project.plugins.dir="./plugins"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:Ant.property(environment:"env") grailsHome = Ant.antProject.properties."env.GRAILS_HOME"includeTargets << new File("${grailsHome}/scripts/Bootstrap.groovy")
grailsScript method to import a named script:includeTargets << grailsScript("_GrailsBootstrap")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(
"grails-app/conf/my-config.xml")basedir property:new File("${basedir}/grails-app/conf/my-config.xml").withInputStream { stream -> // read the file }
Command Line Changes
Therun-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" }
REST Support
Incoming XML requests are now no longer automatically parsed. To enable parsing of REST requests you can do so using theparseRequest argument inside a URL mapping:"/book"(controller:"book",parseRequest:true)
resource argument, which enables parsing by default:"/book"(resource:"book")

