4 設定 - 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.
【注意】このドキュメントの内容はスナップショットバージョンを元に*意訳*されているため、一部現行バージョンでは未対応の機能もあります。
Table of Contents
4 設定
4.1 基本設定
grails-app/conf/BuildConfig.groovy
grails-app/conf/Config.groovy
BuildConfig.groovy
, is for settings that are used when running Grails commands, such as compile
, doc
, etc. The second file, Config.groovy
, is for settings that are used when your application is running. This means that Config.groovy
is packaged with your application, but BuildConfig.groovy
is not. Don't worry if you're not clear on the distinction: the guide will tell you which file to put a particular setting in.
BuildConfig.groovy
はcompile
やdoc
等のようなGrailsコマンドを実行するときに使われる設定です。
2つめのConfig.groovy
はアプリケーションを実行するときに使われる設定です。
つまり、Config.groovy
はアプリケーションにパッケージされますが、BuildConfig.groovy
はされません。
違いがよく分からなくても心配する必要はありません。
どの設定をどのファイルに書くべきかはこのガイドで示していきます。foo.bar.hello = "world"
foo.bar.hello = "world" foo.bar.good = "bye"
foo.bar
. The above syntax works but it's quite repetitive and verbose. You can remove some of that verbosity by nesting properties at the dots:
foo.bar
という同じベースを持っています。
上記の構文は動作しますが、繰り返しがかなり冗長です。
プロパティのドットの箇所でネストして、冗長さを無くすことができます:foo { bar { hello = "world" good = "bye" } }
foo { bar.hello = "world" bar.good = "bye" }
// Won't work! foo.bar { hello = "world" good = "bye" }
BuildConfig.groovy
and Config.groovy
you can access several implicit variables from configuration values:
BuildConfig.groovy
とConfig.groovy
内では、設定値からいくつかの暗黙の変数にアクセスできます:Variable | Description |
---|---|
userHome | Location of the home directory for the account that is running the Grails application. |
grailsHome | Location of the directory where you installed Grails. If the GRAILS_HOME environment variable is set, it is used. |
appName | The application name as it appears in application.properties. |
appVersion | The application version as it appears in application.properties. |
変数 | 説明 |
---|---|
userHome | Grailsアプリケーションを実行しているアカウントのホームディレクトリの場所です。 |
grailsHome | Grailsがインストールされているディレクトリの場所です。環境変数GRAILS_HOME が設定されているときはその値が格納されます。 |
appName | application.properties内に表記しているアプリケーション名です。 |
appVersion | application.properties内に表記しているアプリケーションバージョンです。 |
my.tmp.dir = "${userHome}/.grails/tmp"
BuildConfig.groovy
has
BuildConfig.groovy
は以下の変数を持っています。Variable | Description |
---|---|
grailsVersion | The version of Grails used to build the project. |
grailsSettings | An object containing various build related settings, such as baseDir . It's of type BuildSettings . |
変数 | 説明 |
---|---|
grailsVersion | プロジェクトをビルドするために使われたGrailsのバージョンです。 |
grailsSettings | baseDir のような、ビルドに関連する様々な設定を格納したオブジェクトです。型はBuildSettings です。 |
Config.groovy
has
Config.groovy
は以下の変数を持っています。Variable | Description |
---|---|
grailsApplication | The GrailsApplication instance. |
変数 | 説明 |
---|---|
grailsApplication | GrailsApplication のインスタンスです。 |
BuildConfig.groovy
are only available from command scripts and can be accessed via the grailsSettings.config
property like so:
BuildConfig.groovy
内の設定はコマンドスクリプトからしか取得できません。
以下のようにgrailsSettings.config
プロパティを経由してアクセスできます:target(default: "Example command") { def maxIterations = grailsSettings.config.myapp.iterations.max … }
Config.groovy
, use the grailsApplication
object, which is available as a variable in controllers and tag libraries:
Config.groovy
に定義されたものを読みたい場合は、grailsApplication
オブジェクトを使って、コントローラやタグライブラリから変数として取得できます:class MyController { def hello() { def recipient = grailsApplication.config.foo.bar.hellorender "Hello ${recipient}" } }
class MyService { def grailsApplicationString greeting() { def recipient = grailsApplication.config.foo.bar.hello return "Hello ${recipient}" } }
4.1.1 組込オプション
Build settings
ビルド設定
BuildConfig.groovy
:
BuildConfig.groovy
内で次のように設定します:grails.project.source.level = "1.5" grails.project.target.level = "1.5"
grails.servlet.version
setting appropriately:
grails.servlet.version
を適切に設定します:grails.servlet.version = "3.0"
Runtime settings
ランタイム設定
Config.groovy
, there are quite a few more core settings:
Config.groovy
には非常に多くのコアな設定があります:grails.config.locations
- The location of properties files or addition Grails Config files that should be merged with main configuration. See the section on externalised config.grails.enable.native2ascii
- Set this to false if you do not require native2ascii conversion of Grails i18n properties files (default: true).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: 'utf-8').grails.mime.file.extensions
- Whether to use the file extension to dictate the mime type in Content Negotiation (default: true).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. Also used by redirects.grails.views.gsp.sitemesh.preprocess
- Determines whether SiteMesh preprocessing happens. Disabling this slows down page rendering, but if you need SiteMesh to parse the generated HTML from a GSP view then disabling it is the right option. Don't worry if you don't understand this advanced property: leave it set to true.grails.reload.excludes
andgrails.reload.includes
- Configuring these directives determines the reload behavior for project specific source files. Each directive takes a list of strings that are the class names for project source files that should be excluded from reloading behavior or included accordingly when running the application in development with therun-app
command. If thegrails.reload.includes
directive is configured, then only the classes in that list will be reloaded.
grails.config.locations
- メイン設定にマージされるべきプロパティファイルや追加のGrails設定ファイルの場所です。設定の外部化セクションを参照してください。grails.enable.native2ascii
- Grailsのi18nプロパティファイルのnative2ascii変換が必要ない場合はこれをfalseに設定します(デフォルト: true)。grails.views.default.codec
- GSPのデフォルトエンコーディング形式を設定します。'none'、'html'、または'base64'のいずれかを設定できます(デフォルト: none)。XSS攻撃によるリスクを減らすためには、これを'html'に設定します。grails.views.gsp.encoding
- GSPのソースファイルに使用するファイルエンコーディングです(デフォルト: 'utf-8')。grails.mime.file.extensions
- コンテントネゴシエーションにおいてmime typeの判定にファイルの拡張子を使うかどうかです。(デフォルト: true)grails.mime.types
- コンテントネゴシエーションで使う、サポートするMIMEタイプのマップです。grails.serverURL
- 絶対リンクのサーバURLの部分を指定する文字列です。grails.serverURL="http://my.yourportal.com"のようにサーバ名を含みます。createLinkを参照してください。この設定はリダイレクトにも使われます。grails.views.gsp.sitemesh.preprocess
- SiteMeshプリプロセッシングさせるかどうかを決めます。これを無効にするとページのレンダリングが遅くなりますが、GSPビューから生成されたHTMLをパースするためにSiteMeshが必要であれば、無効にすることは正しい選択です。この上級者向けのプロパティを理解していなくても気にする必要はありません。trueのままにしておきましょう。grails.reload.excludes
とgrails.reload.includes
- このディレクティブの設定は、プロジェクト固有のソースファイルに対するリロードの挙動を決めます。それぞれのディレクティブは文字列のリストを取ります。この文字列はrun-app
コマンドを使って開発時にアプリケーションを動作させる際、リロード対象から除外または含めるべきプロジェクトのソースファイルのクラス名です。grails.reload.includes
ディレクティブが設定されている場合、リストにあるクラスだけがリロードされます。
War generation
Warの生成
grails.project.war.file
- Sets the name and location of the WAR file generated by the war commandgrails.war.dependencies
- A closure containing Ant builder syntax or a list of JAR filenames. Lets you customise what libaries are included in the WAR file.grails.war.copyToWebApp
- A closure containing Ant builder syntax that is legal inside an Ant copy, for example "fileset()". Lets you 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 work before building the final WAR file
grails.project.war.file
- warコマンドによって生成されるWARファイルの名前と場所を設定します。grails.war.dependencies
- Antビルダシンタックスを含むクロージャ、またはJARファイル名のリストです。WARファイルに含まれるライブラリをカスタマイズできます。grails.war.copyToWebApp
- "fileset()"等のAntコピーで定義されているAntビルダシンタックスを含むクロージャです。WARファイルに含めるために、"web-app"ディレクトリから何を取得するかを制御できます。grails.war.resources
- Antビルダシンタックスを含むクロージャです。最終的にWARファイルをビルドする前に、その他の作業を行うことをアプリケーションに許可します。
4.1.2 ロギング
The Basics
基本
log4j
setting to the file grails-app/conf/Config.groovy
.
log4j
設定をgrails-app/conf/Config.groovy
ファイルに追加するだけです。log4j
setting look like? Here's a basic example:
log4j
の設定はどのように見えるでしょうか?
基本的な例を示します:log4j = { error 'org.codehaus.groovy.grails.web.servlet', // controllers 'org.codehaus.groovy.grails.web.pages' // GSPwarn 'org.apache.catalina' }
Logging levels
ログレベル
- off
- fatal
- error
- warn
- info
- debug
- trace
- all
log.error(msg)
will log a message at the 'error' level. Likewise, log.debug(msg)
will log it at 'debug'. Each of the above levels apart from 'off' and 'all' have a corresponding log method of the same name.
log.error(msg)
メソッドは「error」レベルでメッセージを記録します。
同様に、log.debug(msg)
は「debug」で記録します。
「off」と「all」を除いた上記のレベルには、それぞれに対応する同名のログメソッドがあります。warn 'org.example.domain'
Loggers
ロガー
log.debug(msg)
, log
is a logger instance (of type Log). These loggers are cached and uniquely identified by name, so if two separate classes use loggers with the same name, those loggers are actually the same instance.
log.debug(msg)
という呼び出しにおいては、log
が(Log型の)ロガーインスタンスです。
これらのロガーはキャッシュされ、名前によって一意に識別されます。
2つの別々のクラスが同じ名前のロガーを使う場合、そのロガーは実際に同一のインスタンスとなります。- use the
log
instance injected into artifacts such as domain classes, controllers and services; - use the Commons Logging API directly.
- ドメインクラスやコントローラ、サービスのようなアーティファクトに注入される
log
インスタンスを使う - Commons Logging APIを直接使う
log
property, then the name of the logger is 'grails.app.<type>.<className>', where type
is the type of the artifact, for example 'controllers' or 'services', and className
is the fully qualified name of the artifact. For example, if you have this service:
log
プロパティを使う場合、ロガーの名前は「grails.app.<type>.<className>」になります。
このtype
はアーティファクトの種類で、例えば「controllers」や「services」が入ります。
そして、className
にはそのアーティファクトの完全修飾名が入ります。
例えば、このサービスの場合:package org.exampleclass MyService { … }
package org.otherimport org.apache.commons.logging.LogFactory
class MyClass { private static final log = LogFactory.getLog(this) … }
getLog()
method, such as "myLogger", but this is less common because the logging system treats names with dots ('.') in a special way.
getLog()
メソッドに渡すこともできます。
しかし、ロギングシステムがドット(.)付きの名前を特別な方法で扱うため、これはあまり一般的ではありません。Configuring loggers
log4j = { error 'org.codehaus.groovy.grails.web.servlet' }
org.codehaus.groovy.grails.web.servlet.GrailsDispatcherServlet
class and the org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest
one.
org.codehaus.groovy.grails.web.servlet.GrailsDispatcherServlet
クラスとorg.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest
クラスの両方に適用されます。log4j = { // Set level for all application artifacts info "grails.app"// Set for a specific controller in the default package debug "grails.app.controllers.YourController"
// Set for a specific domain class debug "grails.app.domain.org.example.Book"
// Set for all taglibs info "grails.app.taglib" }
conf
- For anything undergrails-app/conf
such asBootStrap.groovy
(but excluding filters)filters
- For filterstaglib
- For tag librariesservices
- For service classescontrollers
- For controllersdomain
- For domain entities
conf
-BootStrap.groovy
のようなgrails-app/conf
配下にあるもの (フィルタは除く)filters
- フィルタtaglib
- タグライブラリservices
- サービスクラスcontrollers
- コントローラdomain
- ドメインエンティティ
org.codehaus.groovy.grails.commons
- Core artifact information such as class loading etc.org.codehaus.groovy.grails.web
- Grails web request processingorg.codehaus.groovy.grails.web.mapping
- URL mapping debuggingorg.codehaus.groovy.grails.plugins
- Log plugin activitygrails.spring
- See what Spring beans Grails and plugins are definingorg.springframework
- See what Spring is doingorg.hibernate
- See what Hibernate is doing
org.codehaus.groovy.grails.commons
- クラスローディング等のようなコアとなるアーティファクト情報org.codehaus.groovy.grails.web
- GrailsのWebリクエスト処理org.codehaus.groovy.grails.web.mapping
- URLマッピングのデバッグorg.codehaus.groovy.grails.plugins
- プラグインの動作ログgrails.spring
- GrailsとプラグインがどんなSpringビーンを定義しているかorg.springframework
- Springが何をするのかorg.hibernate
- Hibernateが何をするのか
The Root Logger
ルートロガー
log4j = { root { info() } … }
log4j = {
appenders {
file name:'file', file:'/var/logs/mylog.log'
}
root {
debug 'stdout', 'file'
}
}
stdout
(コンソール)アペンダと自前のfile
アペンダの2つに対してログ出力します。org.apache.log4j.Logger
instance is passed as an argument to the log4j closure. This lets you work with the logger directly:
org.apache.log4j.Logger
インスタンスが渡されます。
これでロガーを直接操作できます:log4j = { root -> root.level = org.apache.log4j.Level.DEBUG … }
Logger
instance, refer to the Log4j API documentation.
Logger
インスタンスでできることについての詳細は、Log4jのAPIドキュメントを参照してください。Appenders
アペンダ
stdout
という名前のコンソールアペンダが、ルートロガーの設定を通じて全てのロガーに繋がっています。
しかし、それ以外のアペンダはありません。
appenders
ブロックで、さらにアペンダを追加することができます:log4j = { appenders { rollingFile name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log" } }
Name | Class | Description |
---|---|---|
jdbc | JDBCAppender | Logs to a JDBC connection. |
console | ConsoleAppender | Logs to the console. |
file | FileAppender | Logs to a single file. |
rollingFile | RollingFileAppender | Logs to rolling files, for example a new file each day. |
名前 | クラス | 説明 |
---|---|---|
jdbc | JDBCAppender | JDBC接続に記録します。 |
console | ConsoleAppender | コンソールに記録します。 |
file | FileAppender | 単一ファイルに記録します。 |
rollingFile | RollingFileAppender | ローテーションするファイルに記録します。例えば日次で新しいファイルにします。 |
name
, maxFileSize
and file
properties of the RollingFileAppender
instance.
RollingFileAppender
のインスタンスのname
とmaxFileSize
、file
プロパティを設定しています。appender
entry with an instance of the appender you want:
appender
エントリを単純に宣言してください。import org.apache.log4j.*log4j = { appenders { appender new RollingFileAppender( name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log") } }
JMSAppender
, SocketAppender
, SMTPAppender
, and more.
JMSAppender
、SocketAppender
、SMTPAppender
などを設定するために使われます。error myAppender: "grails.app.controllers.BookController"
grails.app.controllers.BookController
のロガーが、ルートロガーによって設定されたアペンダだけでなく、myAppender
にもログメッセージを送るようにします。
1つ以上のアペンダをロガーに追加するには、同じレベルの宣言に追加します:error myAppender: "grails.app.controllers.BookController", myFileAppender: ["grails.app.controllers.BookController", "grails.app.services.BookService"], rollingFile: "grails.app.controllers.BookController"
myFileAppender
) by using a list.
myFileAppender
)に対して、リストを使ってどのように1つ以上のロガーを同時に設定するかについても示しています。error myAppender: "grails.app.controllers.BookController" debug myFileAppender: "grails.app.controllers.BookController" fatal rollingFile: "grails.app.controllers.BookController"
grails.app.controllers.BookController
のために「fatal」レベルのメッセージだけを記録するというのがわかるでしょう。
特定のロガーに対して宣言した最後のレベルが勝つためです。
おそらく行いたいことは、アペンダが書き込むメッセージのレベルを制限することです。log4j = {
appenders {
console name: "stdout", threshold: org.apache.log4j.Level.INFO
}
}
threshold
argument which determines the cut-off for log messages. This argument is available for all appenders, but do note that you currently have to specify a Level
instance - a string such as "info" will not work.
threshold
引数でログメッセージを遮断するか決めることです。
この引数は全てのアペンダで利用可能ですが、Level
インスタンスを指定する必要があることに注意してください。
info
のような文字列では動作しません。Custom Layouts
カスタムレイアウト
xml
- Create an XML log filehtml
- Creates an HTML log filesimple
- A simple textual logpattern
- A Pattern layout
xml
- XMLログファイルを作成html
- HTMLログファイルを作成simple
- シンプルなテキストログpattern
- パターンレイアウト
layout
setting:
layout
設定を使ってアペンダに独自のパターンを指定できます:log4j = { appenders { console name: "customAppender", layout: pattern(conversionPattern: "%c{2} %m%n") } }
stdout
でも動作します。log4j = { appenders { console name: "stdout", layout: pattern(conversionPattern: "%c{2} %m%n") } }
Environment-specific configuration
環境ごとの設定
Config.groovy
, you can put it inside an environment-specific block. However, there is a problem with this approach: you have to provide the full logging configuration each time you define the log4j
setting. In other words, you cannot selectively override parts of the configuration - it's all or nothing.
Config.groovy
内にあるため、環境ごとのブロックの内側にその設定一式を記述できます。
しかし、この方法には問題があります。
環境ごとにlog4j
の完全なロギング設定を記述しなければならないのです。
言い換えると、設定の特定の部分だけ都合良く上書きすることができません。
全部書くか、まったく書かないかのどちらかしかありません。log4j = { appenders { console name: "stdout", layout: pattern(conversionPattern: "%c{2} %m%n")environments { production { rollingFile name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log" } } }
root { //… }
// other shared config info "grails.app.controller"
environments { production { // Override previous setting for 'grails.app.controller' error "grails.app.controllers" } } }
root
definition, but you can put the root
definition inside an environment block.
root
定義 内 では環境ブロックが使用できませんが、代わりに環境ブロック内へroot
定義を配置してください。Full stacktraces
完全なスタックトレース
StackTrace
logger, which by default writes its output to a file called stacktrace.log
. As with other loggers though, you can change its behaviour in the configuration. For example if you prefer full stack traces to go to the console, add this entry:
StackTrace
ロガーへ出力されます。
デフォルトはstacktrace.log
と呼ばれるファイルへの出力です。
他のロガーと同じように、設定でこの振る舞いを変更できます。
例えば、フルスタックトレースをコンソールに出力したい場合、次の設定を追加します:error stdout: "StackTrace"
stacktrace.log
ファイルを作成しなくなるわけではありません。
単にスタックトレースが書かれるべき場所を変更するだけです。
別の方法はstacktrace
アペンダのファイル場所を変更することです:log4j = { appenders { rollingFile name: "stacktrace", maxFileSize: 1024, file: "/var/tmp/logs/myApp-stacktrace.log" } }
stacktrace
アペンダがまったく必要なければ、null
アペンダとして設定します:log4j = { appenders { 'null' name: "stacktrace" } }
StackTrace
ロガーのstdout
アペンダへの接続と、このnull
アペンダの設定を組み合わせることができます。grails.full.stacktrace
VM property to true
:
grails.full.stacktrace
をtrue
に設定すると、スタックトレースフィルタを完全に無効にできます:grails -Dgrails.full.stacktrace=true run-app
Masking Request Parameters From Stacktrace Logs
スタックトレースログからリクエストパラメータをマスクする
grails.exceptionresolver.params.exclude
config property:
grails.exceptionresolver.params.exclude
の設定値にパラメータ名を指定します。grails.exceptionresolver.params.exclude = ['password', 'creditCard']
grails.exceptionresolver.logRequestParameters
config property to false
. The default value is true
when the application is running in DEVELOPMENT mode and false
for all other modes.
grails.exceptionresolver.logRequestParameters
の設定値にfalse
を設定すると、リクエストパラメータのロギングが完全に停止します。
デフォルト値は、DEVELOPMENT
モードでアプリケーションを起動している場合はtrue
、それ以外のモードではfalse
になります。grails.exceptionresolver.logRequestParameters=false
Logger inheritance
ロガーの継承
log4j = {
appenders {
file name:'file', file:'/var/logs/mylog.log'
}
root {
debug 'stdout', 'file'
}
}
stdout
アペンダとfile
アペンダの両方にログが出力されます。
もし特定のロガーに対してのみstdout
にログを出力したい場合はどうすればよいでしょう?このような場合は、ロガーに対してadditivity
を変更してください。false
の場合、親から設定を継承しません。
すべてのロガーのデフォルトはtrue
で親の設定を継承します。
この設定をどのように変更するのでしょうか?
以下に例を示します:log4j = { appenders { … } root { … }info additivity: false stdout: ["grails.app.controllers.BookController", "grails.app.services.BookService"] }
additivity
という名前の引数を追加します。
additivity
を指定するときは、名前付きのアペンダに対してロガーの設定をしなければなりません。
例えば以下の構文では正しく動作 しません :info additivity: false, ["grails.app.controllers.BookController", "grails.app.services.BookService"]
Customizing stack trace printing and filtering
スタックトレースの表示とフィルタリングをカスタマイズする
org.codehaus.groovy.grails.exceptions.StackTraceFilterer
interface to filter out irrelevant stack frames. To customize the approach used for filtering, implement that interface in a class in src/groovy or src/java and register it in Config.groovy
:
org.codehaus.groovy.grails.exceptions.StackTraceFilterer
インタフェースの実装を使用しています。このフィルタリング方法をカスタマイズするには、src/groovy
またはsrc/java
にインタフェースの実装クラスを配置し、そのクラスをConfig.groovy
で登録します:grails.logging.stackTraceFiltererClass = 'com.yourcompany.yourapp.MyStackTraceFilterer'
org.codehaus.groovy.grails.exceptions.StackTracePrinter
interface in a class in src/groovy or src/java and register it in Config.groovy
:
src/groovy
またはsrc/java
にorg.codehaus.groovy.grails.exceptions.StackTracePrinter
インタフェースの実装クラスを配置し、そのクラスをConfig.groovy
で登録します:grails.logging.stackTracePrinterClass = 'com.yourcompany.yourapp.MyStackTracePrinter'
org.codehaus.groovy.grails.web.errors.ErrorsViewStackTracePrinter
and it's registered as a Spring bean. To use your own implementation, either implement the org.codehaus.groovy.grails.exceptions.StackTraceFilterer
directly or subclass ErrorsViewStackTracePrinter
and register it in grails-app/conf/spring/resources.groovy
as:
org.codehaus.groovy.grails.web.errors.ErrorsViewStackTracePrinter
で、これはSpringビーンとして登録されています。
独自の実装を使うには、org.codehaus.groovy.grails.exceptions.StackTraceFilterer
を直接実装するか、ErrorsViewStackTracePrinter
のサブクラスとして実装し、grails-app/conf/spring/resources.groovy
でそれを登録します:import com.yourcompany.yourapp.MyErrorsViewStackTracePrinterbeans = {
errorsViewStackTracePrinter(MyErrorsViewStackTracePrinter, ref('grailsResourceLocator')) }
Alternative logging libraries
ロギングライブラリの変更
grails.project.dependency.resolution = { inherits("global") { excludes "grails-plugin-logging", "log4j" } … dependencies { runtime "ch.qos.logback:logback-core:0.9.29" … } … }
4.1.3 GORM
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.grails.gorm.failOnError
=true
に設定すると、保存中にバリデーションが失敗した場合、ドメインクラスのsave()
メソッドはgrails.validation.ValidationException
をスローするようになります。
このオプションには、パッケージ名のリストを指定することもできます。 値が文字列のリストである場合、failOnErrorの挙動は指定されたパッケージの(サブパッケージを含む)ドメインクラスのみに適用されます。 詳細については、saveメソッドのドキュメントを参照してください。
grails.gorm.failOnError=true
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 explicitly flush using save(flush: true)
.grails.gorm.autoFlush
=true
にセットすると、save(flush: true)
を使用して明示的にフラッシュする必要がなくなり、merge、save、deleteメソッドはセッションをフラッシュするようになります。
4.2 環境
環境ごとの設定
Config.groovy
, DataSource.groovy
, and BootStrap.groovy
files in the grails-app/conf
directory can use per-environment configuration using the syntax provided by ConfigSlurper. As an example consider the following default DataSource
definition provided by Grails:grails-app/conf
ディレクトリ内のConfig.groovy
, DataSource.groovy
,BootStrap.groovy
ファイルはConfigSlurperによって提供される構文を使用して、環境ごとの設定を行うことができます。次の例では、Grailsによって与えられるデフォルトのDataSource
定義について記述しています。dataSource { pooled = false driverClassName = "org.h2.Driver" username = "sa" password = "" } environments { development { dataSource { dbCreate = "create-drop" url = "jdbc:h2:mem:devDb" } } test { dataSource { dbCreate = "update" url = "jdbc:h2:mem:testDb" } } production { dataSource { dbCreate = "update" url = "jdbc:h2:prodDb" } } }
environments
block specifies per environment settings for the dbCreate
and url
properties of the DataSource
.environments
ブロックにはDataSource
のdbCreate
やurl
プロパティを環境ごとに指定している様子がわかります。異なる環境のパッケージングと実行
grails [environment] [command name]
dev
, prod
, and test
for development
, production
and test
. For example to create a WAR for the test
environment you wound run:dev
,prod
,test
(development
,production
,test
)といった、あらかじめ定義されている3つの環境が知られています。例えば、test
環境でWARを作成するには、以下のように実行します。grails test war
grails.env
variable to any command:grails.env
変数を渡すことで実現できます。grails -Dgrails.env=UAT run-app
プログラマチック環境検出
import grails.util.Environment...
switch (Environment.current) { case Environment.DEVELOPMENT: configureForDevelopment() break case Environment.PRODUCTION: configureForProduction() break }
環境ごとのブートストラップ
grails-app/conf/BootStrap.groovy
file's support for per-environment execution:grails-app/conf/BootStrap.groovy
ファイルの環境ごとの実行サポートを使います。def init = { ServletContext ctx -> environments { production { ctx.setAttribute("env", "prod") } development { ctx.setAttribute("env", "dev") } } ctx.setAttribute("foo", "bar") }
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:BootStrap
の例では、内部的にgrails.util.Environment
クラスを使用して実行しています。独自の環境ロジックを実行するために、このクラスを以下のように使うこともできます。Environment.executeForCurrentEnvironment { production { // do something in production } development { // do something only in development } }
4.3 データソース
grails.project.dependency.resolution = { inherits("global") log "warn" repositories { grailsPlugins() grailsHome() grailsCentral() mavenCentral() } dependencies { runtime 'mysql:mysql-connector-java:5.1.16' } }
mavenCentral()
repository is included here since that's a reliable location for this library.mavenCentral()
リポジトリが記述されているのは、このライブラリの取得元として信頼できる場所だからです。lib
directory.lib
ディレクトリにJARを置いてください。grails-app/conf/DataSource.groovy
. This file contains the dataSource definition which includes the following settings:grails-app/conf/DataSource.groovy
ファイルで使用する、Grailsにおけるデータソースの定義方法を覚える必要があります。このファイルはデータソースの定義として、以下の項目を含んでいます。driverClassName
- The class name of the JDBC driver
username
- The username used to establish a JDBC connectionpassword
- The password used to establish a JDBC connectionurl
- The JDBC URL of the databasedbCreate
- Whether to auto-generate the database from the domain model - one of 'create-drop', 'create', 'update' or 'validate'pooled
- Whether to use a pool of connections (defaults to true)logSql
- Enable SQL logging to stdoutformatSql
- Format logged SQLdialect
- A String or Class that represents the Hibernate dialect used to communicate with the database. See the org.hibernate.dialect package for available dialects.readOnly
- Iftrue
makes the DataSource read-only, which results in the connection pool callingsetReadOnly(true)
on eachConnection
persistenceInterceptor
- The default datasource is automatically wired up to the persistence interceptor, other datasources are not wired up automatically unless this is set totrue
properties
- Extra properties to set on the DataSource bean. See the Commons DBCP BasicDataSource documentation.
driverClassName
- JDBCドライバのクラス名username
- JDBCコネクションの接続に使用するユーザ名password
- JDBCコネクションの接続に使用するパスワードurl
- データベースのJDBC URLdbCreate
- ドメインモデルからデータベースを自動で生成するか。'create-drop'、'create'、'update'、もしくは'validate'の中から1つ指定pooled
- コネクションプールを使うか(デフォルトではtrue)logSql
- 標準出力へのSQLロギングを有効にするかformatSql
- SQLログをフォーマットするかdialect
- データベースの通信に使用されるHibernateの方言を表す文字型かクラス。利用できる方言はorg.hibernate.dialectパッケージを参照readOnly
- true
にした場合は読み取り専用のデータソースとなり、各Connection
でsetReadOnly(true)
がコネクションプールより呼ばれるpersistenceInterceptor
- The default datasource is automatically wired up to the persistence interceptor, other datasources are not wired up automatically unless this is set to true
properties
- DataSourceビーンを設定するための追加プロパティ。Commons DBCP BasicDataSourceドキュメント参照dataSource { pooled = true dbCreate = "update" url = "jdbc:mysql://localhost/yourDB" driverClassName = "com.mysql.jdbc.Driver" dialect = org.hibernate.dialect.MySQL5InnoDBDialect 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 ignored local variable … }
dataSource { pooled = true dbCreate = "update" url = "jdbc:mysql://localhost/yourDB" driverClassName = "com.mysql.jdbc.Driver" dialect = org.hibernate.dialect.MySQL5InnoDBDialect username = "yourUser" password = "yourPassword" properties { maxActive = 50 maxIdle = 25 minIdle = 5 initialSize = 5 minEvictableIdleTimeMillis = 60000 timeBetweenEvictionRunsMillis = 60000 maxWait = 10000 validationQuery = "/* ping */" } }
dbCreateの詳細
dbCreate
property, which can take these values:dbCreate
プロパティを使い、どのようにテーブルの作成を行うのかコントロールすることができ、以下のような値を取ることができます。- create-drop - Same as create, but also drops the tables when the application shuts down cleanly.
- update - Creates missing tables and indexes, and updates the current schema without dropping any tables or data. Note that this can't properly handle many schema changes like column renames (you're left with the old column containing the existing data).
- validate - Makes no changes to your database. Compares the configuration with the existing database schema and reports warnings.
- any other value - does nothing
dbCreate
setting completely, which is recommended once your schema is relatively stable and definitely when your application and database are deployed in production. Database changes are then managed through proper migrations, either with SQL scripts or a migration tool like Liquibase (the Database Migration plugin uses Liquibase and is tightly integrated with Grails and GORM).dbCreate
設定を完全に削除することもできます。それは、アプリケーションとデータベースが本番環境にデプロイされている場合、スキーマが比較的安定してきた段階で推奨されています。データベースの変更は、SQLスクリプトやLiquibaseのようなマイグレーションツールのどちらかで、適切にマイグレーションを管理してください。(Database Migration プラグインはLiquibaseを使用し、GrailsやGORMと統合されます。)
4.3.1 データソースと環境
dataSource { pooled = true driverClassName = "com.mysql.jdbc.Driver" dialect = org.hibernate.dialect.MySQL5InnoDBDialect // other common settings here }environments { production { dataSource { url = "jdbc:mysql://liveip.com/liveDb" // other environment-specific settings here } } }
4.3.2 JNDI データソース
JNDIデータソースの参照
DataSource
instances via Java Naming and Directory Interface (JNDI). Grails supports the definition of JNDI data sources as follows:DataSource
インスタンスを提供しています。Grailsでは次のようにJNDIデータソースの定義をサポートしています。dataSource {
jndiName = "java:comp/env/myDataSource"
}
DataSource
in Grails remains the same.DataSource
を定義する方法は変わらず同じです。開発時におけるJNDIリソースの設定
grails.naming.entries
setting in grails-app/conf/Config.groovy
:grails-app/conf/Config.groovy
内のgrails.naming.entries
の設定を使用することで、JNDIリソースを定義します。grails.naming.entries = [ "bean/MyBeanFactory": [ auth: "Container", type: "com.mycompany.MyBean", factory: "org.apache.naming.factory.BeanFactory", bar: "23" ], "jdbc/EmployeeDB": [ type: "javax.sql.DataSource", //required auth: "Container", // optional description: "Data source for Foo", //optional driverClassName: "org.h2.Driver", url: "jdbc:h2:mem:database", username: "dbusername", password: "dbpassword", maxActive: "8", maxIdle: "4" ], "mail/session": [ type: "javax.mail.Session, auth: "Container", "mail.smtp.host": "localhost" ] ]
4.3.3 自動データベースマイグレーション
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 described in the DataSource section:DataSource
定義のdbCreate
プロパティは、Grailsが実行時にGORMのクラスから自動的にデータベーステーブルを生成すべきかを指示する重要なプロパティです。以下のオプションはDataSourceのセクションで説明しています。
create
create-drop
update
validate
- no value
dbCreate
is by default set to "create-drop", but at some point in development (and certainly once you go to production) you'll need to stop dropping and re-creating the database every time you start up your server.dbCreate
はデフォルト値が"create-drop"で設定されていますが、開発中(もしくは本番以前)では、サーバの起動ごとにデータベースが削除、再作成されることが不都合な場合があります。update
so you retain existing data and only update the schema when your code changes, but Hibernate's update support is very conservative. It won't make any changes that could result in data loss, and doesn't detect renamed columns or tables, so you'll be left with the old one and will also have the new one.update
に切り替えたくなりますが、Hibernateの更新サポートはあまりパッとしません。データの損失につながる可能性のある変更をすることはありませんが、テーブルやカラム名の変更を見つけることができないので、古いテーブルやカラムは残されて新しいものも持つことになります。grails-app/conf/BuildConfig.groovy
:grails-app/conf/BuildConfig.groovy
に宣言することでプラグインとしてインストールすることができます。:grails.project.dependency.resolution = { … plugins { runtime ':database-migration:1.3.1' } }
4.3.4 Transaction-awareデータソースプロキシ
dataSource
bean is wrapped in a transaction-aware proxy so you will be given the connection that's being used by the current transaction or Hibernate Session
if one is active.dataSource
ビーンはトランザクション対応のプロキシでラップされているため、それらが開始されているのであれば、現在のトランザクションやHibernateセッションで使われているコネクションが得られます。dataSource
would be a new connection, and you wouldn't be able to see changes that haven't been committed yet (assuming you have a sensible transaction isolation setting, e.g. READ_COMMITTED
or better).dataSource
としてトランザクション対応のプロキシを使っていなかったとしたら、そのdataSource
から取得したコネクションは新規コネクションであり、(READ_COMMITTED
やより上位の適切なトランザクション分離が設定されていると仮定すれば)まだコミットされていない変更はみえないことでしょう。
dataSource
is still available to you if you need access to it; its bean name is dataSourceUnproxied
.dataSource
にアクセスする必要があるなら、dataSourceUnproxied
というビーン名を使って利用できます。class MyService {def dataSourceUnproxied … }
ApplicationContext
:ApplicationContext
から取得できます。def dataSourceUnproxied = ctx.dataSourceUnproxied
4.3.5 データベースコンソール
grails.dbconsole.urlRoot
attribute in Config.groovy and defaults to '/dbconsole'
.grails.dbconsole.urlRoot
属性を使って設定することが可能で、デフォルト値は'/dbconsole'
になっています。grails.dbconsole.enabled
attribute in Config.groovy. For example you could enable the console in production usinggrails.dbconsole.enabled
属性を使って無効にしたり、他のモードで有効にすることができます。例えば、本番環境(production)でコンソールを有効にするには、次のように記述します。environments { production { grails.serverURL = "http://www.changeme.com" grails.dbconsole.enabled = true grails.dbconsole.urlRoot = '/admin/dbconsole' } development { grails.serverURL = "http://localhost:8080/${appName}" } test { grails.serverURL = "http://localhost:8080/${appName}" } }
If you enable the console in production be sure to guard access to it using a trusted security framework.
本番環境でコンソールを有効にする場合は、信頼されるセキュリティフレームワークを使用して、コンソールへのアクセスを保護するようにしてください。
設定
jdbc:h2:mem:devDB
. If you've configured an external database (e.g. MySQL, Oracle, etc.) then you can use the Saved Settings dropdown to choose a settings template and fill in the url and username/password information from your DataSource.groovy.jdbc:h2:mem:devDB
に変更してください。外部データベース(例えば、MySQL,Oracleなど)を設定する場合には、ドロップダウンのリストから設定テンプレートを選択し、DataSource.groovyからurlやユーザ名/パスワードを設定します。
4.3.6 複数データソース
DataSource
and a single database, but you have the option to partition your domain classes into two or more DataSource
s.DataSource
configuration in grails-app/conf/DataSource.groovy
looks something like this:DataSource
はgrails-app/conf/DataSource.groovy
で設定されており、次のようになっています。dataSource { pooled = true driverClassName = "org.h2.Driver" username = "sa" password = "" } hibernate { cache.use_second_level_cache = true cache.use_query_cache = true cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider' }environments { development { dataSource { dbCreate = "create-drop" url = "jdbc:h2:mem:devDb" } } test { dataSource { dbCreate = "update" url = "jdbc:h2:mem:testDb" } } production { dataSource { dbCreate = "update" url = "jdbc:h2:prodDb" } } }
DataSource
with the Spring bean named dataSource
. To configure extra DataSource
s, add another dataSource
block (at the top level, in an environment block, or both, just like the standard DataSource
definition) with a custom name, separated by an underscore. For example, this configuration adds a second DataSource
, using MySQL in the development environment and Oracle in production:dataSource
と命名されたSpringビーンとして、単一のDataSource
を設定しています。複数のDataSource
を設定するには、アンダースコア(_)で区切られたカスタム名を持つ、別のdataSource
ブロックを(トップレベルかenvironmentブロック、または両方へ標準のDataSource
定義と同様に)追加します。例えば、以下の設定では開発環境にMySQLを、本番環境にOracleを2番目のDataSource
として追加しています。environments { development { dataSource { dbCreate = "create-drop" url = "jdbc:h2:mem:devDb" } dataSource_lookup { dialect = org.hibernate.dialect.MySQLInnoDBDialect driverClassName = 'com.mysql.jdbc.Driver' username = 'lookup' password = 'secret' url = 'jdbc:mysql://localhost/lookup' dbCreate = 'update' } } test { dataSource { dbCreate = "update" url = "jdbc:h2:mem:testDb" } } production { dataSource { dbCreate = "update" url = "jdbc:h2:prodDb" } dataSource_lookup { dialect = org.hibernate.dialect.Oracle10gDialect driverClassName = 'oracle.jdbc.driver.OracleDriver' username = 'lookup' password = 'secret' url = 'jdbc:oracle:thin:@localhost:1521:lookup' dbCreate = 'update' } } }
ドメインクラスの設定
DataSource
configuration, it defaults to the standard 'dataSource'
. Set the datasource
property in the mapping
block to configure a non-default DataSource
. For example, if you want to use the ZipCode
domain to use the 'lookup'
DataSource
, configure it like this;DataSource
の設定をしていない場合、デフォルトで標準の'dataSource'
が設定されます。デフォルトでないDataSource
を設定をするには、mapping
ブロック内でdatasource
プロパティを使用します。例えば、ZipCode
ドメインで'lookup'
DataSource
を利用したい場合、以下のように設定します。class ZipCode {String code
static mapping = { datasource 'lookup' } }
DataSource
s. Use the datasources
property with a list of names to configure more than one, for example:DataSource
を使用することもできます。複数の設定をするためには、datasources
プロパティにデータソース名のリストを設定します。例えば:class ZipCode {String code
static mapping = { datasources(['lookup', 'auditing']) } }
DataSource
and one or more others, use the special name 'DEFAULT'
to indicate the default DataSource
:DataSource
を持ち、デフォルトのDataSource
を使う場合はデフォルトのDataSource
を指す特別な名前として'DEFAULT'
を使うことができます。class ZipCode {String code
static mapping = { datasources(['lookup', 'DEFAULT']) } }
DataSource
s use the special value 'ALL'
:DataSource
を使う場合、特別な値として'ALL'
を使います。class ZipCode {String code
static mapping = { datasource 'ALL' } }
名前空間とGORMメソッド
DataSource
then you can use the namespace implied by each DataSource
name to make GORM calls for a particular DataSource
. For example, consider this class which uses two DataSource
s:DataSource
を使用している場合、特定のDataSource
へGORMの呼び出しを行うために、DataSource
名ごとに暗黙で定義された名前空間を使うことが出来ます。例えば、2つのDataSource
が使われているこのクラスを考えます。class ZipCode {String code
static mapping = { datasources(['lookup', 'auditing']) } }
DataSource
specified is the default when not using an explicit namespace, so in this case we default to 'lookup'. But you can call GORM methods on the 'auditing' DataSource
with the DataSource
name, for example:DataSource
がデフォルトとして使用されます。この場合デフォルトは'lookup'となります。また、以下のように'auditing' DataSource
上でGORMメソッドを呼ぶことができます。def zipCode = ZipCode.auditing.get(42) … zipCode.auditing.save()
DataSource
to the method call in both the static case and the instance case.DataSource
を追加します。ドメインクラスのHibernateマップ
grails-app/conf/hibernate/hibernate.cfg.xml
. To specify that an annotated class uses a non-default datasource, create a hibernate.cfg.xml
file for that datasource with the file name prefixed with the datasource name.grails-app/conf/hibernate/hibernate.cfg.xml
に登録されます。デフォルトでないデータソースを使う注釈されたクラスを明示するためには、ファイル名の先頭にデータソース名をつけたhibernate.cfg.xml
を作成します。Book
class is in the default datasource, you would register that in grails-app/conf/hibernate/hibernate.cfg.xml
:Book
クラスがデフォルトのデータソースを使う場合、grails-app/conf/hibernate/hibernate.cfg.xml
に登録します。<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC '-//Hibernate/Hibernate Configuration DTD 3.0//EN' 'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'> <hibernate-configuration> <session-factory> <mapping class='org.example.Book'/> </session-factory> </hibernate-configuration>
Library
class is in the "ds2" datasource, you would register that in grails-app/conf/hibernate/ds2_hibernate.cfg.xml
:Library
クラスが"ds2"データソースを使う場合、grails-app/conf/hibernate/ds2_hibernate.cfg.xml
に登録します。<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC '-//Hibernate/Hibernate Configuration DTD 3.0//EN' 'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'> <hibernate-configuration> <session-factory> <mapping class='org.example.Library'/> </session-factory> </hibernate-configuration>
サービス
DataSource
and PlatformTransactionManager
. To configure a Service to use a different DataSource
, use the static datasource
property, for example:DataSource
とPlatformTransactionManager
が使用されます。サービスの設定で異なるDataSource
を使用する場合は、staticなdatasource
プロパティを使用します。例えば:class DataService {static datasource = 'lookup'
void someMethod(...) { … } }
DataSource
, so be sure to only make changes for domain classes whose DataSource
is the same as the Service.DataSource
がサービスと同じドメインクラスだけ値を変更できることに注意してください。XAと2相コミット
DataSource
s or two-phase commit, but the Atomikos plugin makes it easy. See the plugin documentation for the simple changes needed in your DataSource
definitions to reconfigure them as XA DataSource
s.DataSource
や2相コミットに対応していませんが、Atomikosプラグインで簡単に行うことができます。DataSource
定義をXA DataSource
として再設定するのには簡単な変更が必要となるため、プラグインのドキュメントを参照してください。4.4 設定の外部化
grails.config.locations
setting in Config.groovy
, for example:Config.groovy
ファイルにgrails.config.locations
の設定を追加し、設定ファイルの位置をGrailsに伝えます。例えば:grails.config.locations = [ "classpath:${appName}-config.properties", "classpath:${appName}-config.groovy", "file:${userHome}/.grails/${appName}-config.properties", "file:${userHome}/.grails/${appName}-config.groovy" ]
USER_HOME
.USER_HOME
内のファイルといった異なる場所から、設定ファイル(Javaのプロパティファイルや ConfigSlurper 設定ファイル)を読み込んでいます。grails.config.locations = [com.my.app.MyConfig]
config
property of the GrailsApplication object and are hence obtainable from there.config
プロパティへ統合され、そこから取得可能です。デフォルトの設定
grails.config.locations
property will override any values defined in your application Config.groovy
file which may not be what you want. You may want to have a set of default values be be loaded that can be overridden in either your application's Config.groovy
file or in a named config location. For this you can use the grails.config.defaults.locations
property.grails.config.defaults.locations
プロパティから読み込んだ設定値は、アプリケーションのConfig.groovy
で定義された任意の値を上書きします。アプリケーションのConfig.groovy
ファイルか、指定した設定ファイル場所のいずれかで値をオーバライドすることで、デフォルト値として値を読み込ませることが出来ます。これについては、grails.config.defaults.locations
プロパティを使用することができます。
grails.config.locations
property (i.e. paths to config scripts, property files or classes), but the config described by grails.config.defaults.locations
will be loaded before all other values and can therefore be overridden. Some plugins use this mechanism to supply one or more sets of default configuration that you can choose to include in your application config.grails.config.locations
プロパティと同じ値(すなわち、設定スクリプト、プロパティのファイルやクラスへのパス)をサポートしています。しかし、grails.config.defaults.locations
で記述された設定ははじめに読み込まれるため、あとから読み込む設定値で上書きすることができます。プラグインの中にはこのメカニズムを利用して、プラグインが提供するデフォルト値をアプリケーションに含めるかをユーザが選択する形をとっているものがあります。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
GrailsはSpringで定義されているようなプレースホルダや設定のオーバライドといったプロパティの概念をサポートしています。より詳しい情報はGrails and Springの章を参照してください。
4.5 バージョニング
バージョン管理の基本
0.1
when you first create an application with the create-app command. The version is stored in the application meta data file application.properties
in the root of the project.0.1
に設定されています。バージョンは、プロジェクトルートにあるアプリケーションのメタデータファイルのapplication.properties
に記述されます。grails set-version 0.2
実行時のバージョン検出
def version = grailsApplication.metadata['app.version']
def grailsVersion = grailsApplication.metadata['app.grails.version']
GrailsUtil
class:GrailsUtil
クラスを使います。import grails.util.GrailsUtil
…
def grailsVersion = GrailsUtil.grailsVersion
4.6 プロジェクト・ドキュメント
プロジェクトドキュメントの作成
src/docs/guide
directory where your documentation source files will go. Then, you need to create the source docs themselves. Each chapter should have its own gdoc file as should all numbered sub-sections. You will end up with something like:src/docs/guide
ディレクトリを作る必要があります。次に、ソースファイル自体を作成する必要があります。すべてのサブセクションに番号が振られているように、各章には独自のgdocファイルをもつべきです。以下のようになります。+ src/docs/guide/introduction.gdoc + src/docs/guide/introduction/changes.gdoc + src/docs/guide/gettingStarted.gdoc + src/docs/guide/configuration.gdoc + src/docs/guide/configuration/build.gdoc + src/docs/guide/configuration/build/controllers.gdoc
src/docs/guide/toc.yml
file that contains the structure and titles for each section. This file is in YAML format and basically represents the structure of the user guide in tree form. For example, the above files could be represented as:src/docs/guide/toc.yml
ファイルを追加します。このファイルはYAML形式で、基本的にはツリー形式でユーザガイドの構造を表しています。例えば、上記のファイル構造は次のように表すことができます。introduction: title: Introduction changes: Change Log gettingStarted: Getting Started configuration: title: Configuration build: title: Build Config controllers: Specifying Controllers
title:
plus the title of the section as seen by the end user. Every sub-section then has its own line after the title. Leaf nodes, i.e. those without any sub-sections, declare their title on the same line as the section name but after the colon.title:
に加えて、エンドユーザが目にするセクションのタイトルを記述します。すべてのサブセクションではタイトルの後に独自のラインを持っています。サブセクションを持たないセクションでは、セクション名と同じ行のコロンの後にタイトルを宣言します。toc.yml
to restructure the generated user guide. You should also make sure that all section names, i.e. the gdoc filenames, should be unique since they are used for creating internal links and for the HTML filenames. Don't worry though, the documentation engine will warn you of duplicate section names.toc.yml
内部で簡単にセクションの追加や削除、移動ができます。すべてのセクション名(gdocのファイル名)はユニークである必要があります。なぜなら、それらは内部リンクの作成やHTMLのファイル名に使用されるからです。しかし、心配はいりません。ドキュメンテーションエンジンはセクション名が重複していた場合に警告を表示します。参照項目の作成
src/docs/ref
directory. For example, suppose you have defined a new controller method called renderPDF
. That belongs to the Controllers
category so you would create a gdoc text file at the following location:src/docs/ref
ディレクトリに配置します。例えば、コントローラに新しくrenderPDF
のメソッドを定義したとしましょう。これがControllers
カテゴリに所属する場合、以下のようにgdocのテキストファイルを作成します。:+ src/docs/ref/Controllers/renderPDF.gdoc
出力プロパティの設定
grails-app/conf/Config.groovy
file that customize the output of the documentation such as:grails-app/conf/Config.groovy
内で設定できる様々なプロパティがあります。- grails.doc.title - The title of the documentation
- grails.doc.subtitle - The subtitle of the documentation
- 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
- grails.doc.title - ドキュメントのタイトル
- grails.doc.subtitle - ドキュメントのサブタイトル
- grails.doc.authors - ドキュメントの著者
- grails.doc.license - ソフトウェアライセンス
- grails.doc.copyright - copyrightメッセージの表示
- grails.doc.footer - 使用するフッター
- grails.doc.css - The location of a directory containing custom CSS files (type
java.io.File
) - grails.doc.js - The location of a directory containing custom JavaScript files (type
java.io.File
) - grails.doc.style - The location of a directory containing custom HTML templates for the guide (type
java.io.File
) - grails.doc.images - The location of a directory containing image files for use in the style templates and within the documentation pages themselves (type
java.io.File
)
- grails.doc.css - カスタマイズしたCSSファイルを含むディレクトリ場所(
java.io.File
クラスの型) - grails.doc.js - カスタマイズしたJavaScriptファイルを含むディレクトリ場所(
java.io.File
クラスの型) - grails.doc.style - ガイド用にカスタマイズしたHTMLテンプレートを含むディレクトリ場所(
java.io.File
クラスの型) - grails.doc.images - スタイルテンプレートやドキュメントページ自身で使用する画像ファイルを含むディレクトリ場所(
java.io.File
の型)
grails.doc.css
and then put a custom.css file in the corresponding directory. Grails will automatically include this CSS file in the guide. You can also place a custom-pdf.css file in that directory. This allows you to override the styles for the PDF version of the guide.grails.doc.css
の値を記述し、対応するディレクトリにcustom.cssファイルを置くことです。Grailsは自動的にドキュメント内にこのCSSファイルを取り込みます。また、そのディレクトリにcustom-pdf.cssファイルを置くことができます。これは、ドキュメントのpdfバージョンのスタイルを上書きできます。ドキュメントの生成
grails doc
docs/manual/index.html
which can be opened in a browser to view your documentation.docs/manual/index.html
に出力されます。ドキュメントの構文
基本的なフォーマット
monospace
monospace
@monospace@
_italic_
*bold*

!http://grails.org/images/new/grailslogo_topNav.png!
!someFolder/my_diagram.png!
grails.doc.images
setting in Config.groovy like so:grails.doc.images
の設定で指定できます。grails.doc.images = new File("src/docs/images")
リンク生成
[SpringSource|http://www.springsource.com/]
or
"SpringSource":http://www.springsource.com/
guide:
prefix with the name of the section you want to link to:guide:
をつけることで実現できます。[Intro|guide:introduction]
[controllers|renderPDF]
api:
prefix. For example:api:
プレフィックスを使うことで外部APIへリンクできます。例えば:[String|api:java.lang.String]
grails-app/conf/Config.groovy
. For example:grails-app/conf/Config.groovy
に設定を追加することで、エンジンに追加のAPIを加えることができます。例えば:grails.doc.api.org.hibernate=
"http://docs.jboss.org/hibernate/stable/core/javadocs"
org.hibernate
package to link to the Hibernate website's API docs.org.hibernate
パッケージ内のクラスを、HibernateのAPIドキュメントへリンクするように設定しています。リストと見出し
h3.<space>Heading3 h4.<space>Heading4
* item 1 ** subitem 1 ** subitem 2 * item 2
# item 1
table
macro:table
マクロを使って作成できます。Name | Number |
---|---|
Albert | 46 |
Wilma | 1348 |
James | 12 |
{table}
*Name* | *Number*
Albert | 46
Wilma | 1348
James | 12
{table}
コードとノート
code
macro:code
マクロでコードブロックを定義できます。class Book {
String title
}
{code}
class Book {
String title
}
{code}
<hello>world</hello>
{code:xml} <hello>world</hello> {code}
Note:
This is a note!
{note} This is a note! {note}
Warning:
This is a warning!
{warning} This is a warning! {warning}
4.7 依存性解決
grails.project.dependency.resolver
setting in grails-app/conf/BuildConfig.groovy
. The default setting is shown below:grails-app/conf/BuildConfig.groovy
ファイル内のgrails.project.dependency.resolver
を設定することで指定出来ます。デフォルト設定は次のとおりです:grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution
property inside the grails-app/conf/BuildConfig.groovy
file that configures how dependencies are resolved:grails-app/conf/BuildConfig.groovyの
ファイル内の、grails.project.dependency.resolution
プロパティを次のように指定することで、依存関係を解決する方法が設定できます:grails.project.dependency.resolution = { // config here }
grails.project.class.dir = "target/classes" grails.project.test.class.dir = "target/test-classes" grails.project.test.reports.dir = "target/test-reports" //grails.project.war.file = "target/${appName}-${appVersion}.war"grails.project.dependency.resolution = { // inherit Grails' default dependencies inherits("global") { // uncomment to disable ehcache // excludes 'ehcache' } log "warn" repositories { grailsPlugins() grailsHome() grailsCentral() mavenCentral() mavenLocal()
// uncomment these to enable remote dependency resolution // from public Maven repositories //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 'mysql:mysql-connector-java:5.1.16' build "org.grails:grails-plugin-tomcat:$grailsVersion" runtime "org.grails:grails-plugin-hibernate:$grailsVersion" }
plugins {
compile ":jquery:1.8.3" compile ":resources:1.1.6"
build ":tomcat:$grailsVersion" } }
4.7.1 設定と依存
build
: Dependencies for the build system only-
build
: ビルドシステムのためだけの依存関係
compile
: Dependencies for the compile step-
compile
: コンパイルのための依存関係
runtime
: Dependencies needed at runtime but not for compilation (see above)-
runtime
: 実行時には必要だが、コンパイル時には不必要な依存関係(上記参照)
test
: Dependencies needed for testing but not at runtime (see above)-
test
: テスト時には必要だが、実行時には不必要な依存関係(上記参照)
provided
: Dependencies needed at development time, but not during WAR deployment-
provided
: 開発時には必要だが、WARファイルのデプロイ時には不必要な依存関係
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 that like this:dependencies
ブロックの内部で上記のメソッドを呼び出すことにより、依存関係を指定することができます。たとえば、アプリケーションがruntime
時にMySQLドライバを必要とする場合は、次のように指定することができます:runtime 'com.mysql:mysql-connector-java:5.1.16'
group:name:version
. グループ:名前:バージョン
というString構文を使用しています。
<groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>
runtime group: 'com.mysql', name: 'mysql-connector-java', version: '5.1.16'
group
- The group / organization (or groupId in Maven terminology)group
- グループ/組織(Mavenの用語ではgroupId)
name
- The dependency name (or artifactId in Maven terminology)name
- 依存関係名 (Mavenの用語ではartifactId)
version
- The version of the dependencyversion
- 依存関係のバージョン
extension
(Aether only) - The file extension of the dependencyextension
(Aetherのみ) - 依存関係のファイル拡張子
classifier
- The dependency classifierclassifier
- 依存関係の分類
branch
(Ivy only) - The branch of the dependencybranch
(Ivyのみ) - 依存関係のブランチ
transitive
(Ivy only) - Whether the dependency has transitive dependenciestransitive
(Ivyのみ) - 推移的依存関係の有無
runtime 'com.mysql:mysql-connector-java:5.1.16', 'net.sf.ehcache:ehcache:1.6.1'// Or
runtime( [group:'com.mysql', name:'mysql-connector-java', version:'5.1.16'], [group:'net.sf.ehcache', name:'ehcache', version:'1.6.1'] )
推移的依存関係解決の無効化
runtime('com.mysql:mysql-connector-java:5.1.16', 'net.sf.ehcache:ehcache:1.6.1') { transitive = false }// Or runtime group:'com.mysql', name:'mysql-connector-java', version:'5.1.16', transitive:false
Disabling transitive dependency resolution only works with the Ivy dependency manager. Aether does not support disabling of transitive resolution, instead explicit exclusions are required (see below).
推移的依存関係解決の無効化は、Ivy依存関係マネージャとだけ連携して動作します。Aetherは推移的解決をサポートしておらず、明示的に除外する必要があります(下記参照)。
特定の推移的依存関係の除外
excludes
option comes in:excludes
オプションを使用します:runtime('com.mysql:mysql-connector-java:5.1.16', 'net.sf.ehcache:ehcache:1.6.1') { excludes "xml-apis", "commons-logging" }// Or runtime(group:'com.mysql', name:'mysql-connector-java', version:'5.1.16') { excludes([ group: 'xml-apis', name: 'xml-apis'], [ group: 'org.apache.httpcomponents' ], [ name: 'commons-logging' ])
exclude
as well, but that can only accept a single string or Map:exclude
オプションを利用する場合も同様ですが、こちらは単一の文字列またはMapのみを許容します:runtime('com.mysql:mysql-connector-java:5.1.16',
'net.sf.ehcache:ehcache:1.6.1') {
exclude "xml-apis"
}
Ivyモジュール構成の使用
dependencyConfiguration
method to specify the configuration to use.dependencyConfiguration
メソッドを用いて使用する構成を指定できます。provided("my.org:web-service:1.0") { dependencyConfiguration "api" }
"default"
will be used (which is also the correct value for dependencies coming from Maven style repositories)."default"
設定が使用されます。(これは、Mavenスタイルのリポジトリから来る依存関係に対しても正しい値です)JARファイルの場所
user.home/.grails/ivy-cache
or user.home/.m2/repository
when using Aether. You can change this either via the settings.groovy
file:user.home/.grails/ivy-cache
もしくはuser.home/.m2/repository
(Aether使用時)に配置されます。settings.groovy
ファイルによって、この場所を変更できます:grails.dependency.cache.dir = "${userHome}/.my-dependency-cache"
grails.project.dependency.resolution = {
…
cacheDir "target/ivy-cache"
…
}
settings.groovy
option applies to all projects, so it's the preferred approach.settings.groovy
オプションを使用すると、すべてのプロジェクトに適用されるため、こちらがおすすめの方法です。
4.7.2 依存管理リポジトリ
リモートリポジトリ
grailsHome()
repository that will locate the JAR files Grails needs from your Grails installation. To use a public repository, specify it in the repositories
block:grailsHome()
リポジトリが存在します。公開リポジトリを使用するには、repositories
ブロック内で以下を指定します:repositories { mavenCentral() }
repositories {
mavenRepo "http://repository.codehaus.org"
}
repositories { mavenRepo name: "Codehaus", root: "http://repository.codehaus.org" }
プラグインから継承したリポジトリの制御
repositories {
inherit false
}
オフラインモード
offline
flag to execute Grails commands and Grails will not connect to any remote repositories:offline
フラグを付加してGrailsコマンドを実行すれば、Grailsはリモートリポジトリに接続しません:grails --offline run-app
Note that this command will fail if you do not have the necessary dependencies in your local Ivy cache
ローカルIvyキャッシュ内に必要な依存関係が存在しない場合、このコマンドは失敗することに注意してください。
grails.offline.mode
to true
in ~/.grails/settings.groovy
or in your project's BuildConfig.groovy
file:~/.grails/settings.groovy
ファイルか、プロジェクトのBuildConfig.groovy
ファイルのgrails.offline.mode
をtrue
にすることでにオフラインモードを設定することができます:grails.offline.mode=true
ローカルリゾルバ
repositories { flatDir name:'myRepo', dirs:'/path/to/repo' }
Aether does not support the flatDir
resolver or any custom file system resolvers. The above feature works only if you are using the Ivy dependency manager.
AetherはflatDir
リゾルバを含め、いかなるカスタムファイルシステムリゾルバもサポートしていません。上記の機能は、Ivy依存関係マネージャを使用している場合にのみ動作します。
~/.m2/repository
) as a repository:~/.m2/repository
)をリポジトリとして指定する場合は以下のようにします:repositories { mavenLocal() }
カスタムリゾルバ
/* * Configure our resolver. */ def libResolver = new org.apache.ivy.plugins.resolver.URLResolver() ['libraries', 'builds'].each {libResolver.addArtifactPattern( "http://my.repository/${it}/" + "[organisation]/[module]/[revision]/[type]s/[artifact].[ext]")
libResolver.addIvyPattern( "http://my.repository/${it}/" + "[organisation]/[module]/[revision]/[type]s/[artifact].[ext]") }
libResolver.name = "my-repository" libResolver.settings = ivySettings
resolver libResolver
import org.apache.ivy.plugins.resolver.SshResolver … repositories { ...def sshResolver = new SshResolver( name: "myRepo", user: "username", host: "dev.x.com", keyFile: new File("/home/username/.ssh/id_rsa"), m2compatible: true)
sshResolver.addArtifactPattern( "/home/grails/repo/[organisation]/[artifact]/" + "[revision]/[artifact]-[revision].[ext]")
sshResolver.latestStrategy = new org.apache.ivy.plugins.latest.LatestTimeStrategy()
sshResolver.changingPattern = ".*SNAPSHOT"
sshResolver.setCheckmodified(true)
resolver sshResolver }
grails -classpath /path/to/jsch compile|run-app|etc.
CLASSPATH
environment variable but be aware this it affects many Java applications. An alternative on Unix is to create an alias for grails -classpath ...
so that you don't have to type the extra arguments each time.CLASSPATH
環境変数にパスを通すことでも追加できますが、多くのJavaアプリケーションに影響を与えることに注意する必要があります。Unix上で引数を毎回入力する面倒を避けるには、grails -classpath...
コマンドのエイリアスを作成するのが良いでしょう。認証
credentials
block:credentials
ブロックを使用してこれを設定することができます:credentials { realm = ".." host = "localhost" username = "myuser" password = "mypass" }
USER_HOME/.grails/settings.groovy
file using the grails.project.ivy.authentication
setting:grails.project.ivy.authentication
を使用してUSER_HOME/.grails/settings.groovy
ファイル内に記述することができます:grails.project.ivy.authentication = { credentials { realm = ".." host = "localhost" username = "myuser" password = "mypass" } }
4.7.3 依存解決デバッグ
log
method:log
メソッドを使用して内部システムからより詳細なデバッグ情報を得ることができます:// log level of the Aether or Ivy resolver, either 'error', 'warn',
// 'info', 'debug' or 'verbose'
log "warn"
grails.project.dependency.resolution = { … log "warn" checksums false … }
4.7.4 依存の受け継ぎ
inherits "global"
BuildConfig.groovy
file. To exclude specific inherited dependencies you use the excludes
method:BuildConfig.groovy
ファイル内に記載します。特定の依存関係を除外するには、excludes
メソッドを使用します:inherits("global") { excludes "oscache", "ehcache" }
4.7.5 基本依存管理の提供
defaultDependenciesProvided
method and passing true
as an argument:defaultDependenciesProvided
メソッドにtrue
を引数として渡して呼び出すことで実行されます: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 { … } }
grails.project.dependency.resolution = {defaultDependenciesProvided true // 全てのデフォルトの依存関係は // コンテナによって提供される
inherits "global" // Grailsのデフォルト依存関係を継承する
repositories { grailsHome() … } dependencies { … } }
defaultDependenciesProvided
must come beforeinherits
, otherwise the Grails dependencies will be included in the war.
defaultDependenciesProvided
は、inherits
より前に記述されている必要があり、そうしなければGrailsの依存関係はWARファイルに含まれます。
4.7.6 スナップショットと他の変化する依存関係
変化する依存関係の設定
group
, name
and version
the jar (or plugin) that it refers to will never change. The Grails dependency management system uses this fact to cache dependencies in order to avoid having to download them from the source repository each time. Sometimes this is not desirable. For example, many developers use the convention of a snapshot (i.e. a dependency with a version number ending in “-SNAPSHOT”) that can change from time to time while still retaining the same version number. We call this a "changing dependency".グループ
、名前
、バージョン
の組み合わせが参照するjar(もしくはプラグイン)は変化することはない、ということです。これによりGrailsの依存関係管理システムは、ソースリポジトリから毎回ダウンロードすることを回避するために、依存関係をキャッシュできます。時に、この仕様には不都合が生じます。例えば、多くの開発者は慣習的にスナップショット(つまり、バージョン番号が”-SNAPSHOT”で終わる依存関係)を使っています。このスナップショットは同一のバージョン番号を保持しつつ、変更される可能性があります。このことは”変化する依存関係”と呼ばれています。Be sure to read the next section on “Dependency Resolution Caching” in addition to this one as it affects changing dependencies.
変化する依存関係に作用する、依存関係解決キャッシングについて、次のセクションを必ずお読みください。
-SNAPSHOT
are implicitly considered to be changing by Grails. You can also explicitly specify that a dependency is changing by setting the changing flag in the dependency DSL (This is only required for Ivy, Aether does not support the 'changing' flag and treats dependencies that end with -SNAPSHOT as changing):暗黙的に
バージョン番号が-SNAPSHOT
で終わるすべての依存関係(jarファイルもしくはプラグイン)を、変化する依存関係として扱います。また、明示的に依存DSLクエリー言語に変更フラグを設定することでも、変化する依存関係として扱う事ができます。(このDSLクエリー言語はIvyにのみ必要です。Aetherは'changing'フラグをサポートしておらず、-SNAPSHOTで終わる場合は変化する依存関係として扱います)runtime ('org.my:lib:1.2.3') {
changing = true
}
Aether and SNAPSHOT dependencies
AetherとSNAPSHOTの依存関係
updatePolicy
for the repository where the snapshot was resolved from, for example:
updatePolicy
を設定します。
例えば以下のようにします:repositories {
mavenCentral {
updatePolicy "interval:1"
}
}
updatePolicy
like the above will seriously impact performance of dependency resolution. The possibly configuration values for updatePolicy
are as follows:
updatePolicy
のように、この設定は依存関係解決のパフォーマンスに影響を与えることに注意してください。
updatePolicy
に設定が可能な値は以下のとおりです:never
- Never check for new snapshotsalways
- Always check for new snapshotsdaily
- Check once a day for new snapshots (the default)interval:x
- Check once every x minutes for new snapshots
never
- 新しいスナップショットをチェックしないalways
- 常に新しいスナップショットをチェックするdaily
- 1日に1回新しいスナップショットをチェックする (デフォルト)interval:x
- x分ごとに1回新しいスナップショットをチェックする
Ivyと変化する依存関係
grails.project.dependency.resolution = { repositories { mavenLocal() mavenRepo "http://my.org/repo" } dependencies { compile "myorg:mylib:1.0-SNAPSHOT" }
- Mavenのローカルリポジトリが検索されますが、依存関係は見つかりません。
- Mavenのネットワークリポジトリが検索され、依存関係をキャッシュへダウンロードして使用します。
BuildConfig.groovy
file. BuildConfig.groovy
のファイルに定義されている順にチェックされることに注意してください。- Mavenのローカルリポジトリが検索されますが、依存関係は見つかりません。
- Mavenのネットワークリポジトリが検索され依存関係が見つかりますが、キャッシュ内のバージョンと同じ最終更新日時のため更新(すなわちダウンロード)はされません。
mylib 1.0-SNAPSHOT
is published changing the version on the server. The next time we perform dependency resolution, the following will happen:mylib 1.0-SNAPSHOT
の新しいバージョンが公開され、サーバ上のファイルが更新されたとします。この状況で依存関係の解決を実行した場合、以下の処理が行われます。- Mavenのローカルリポジトリが検索されますが、依存関係は見つかりません。
- Mavenのネットワークリポジトリが検索され、キャッシュ内のバージョンよりも新しい依存関係が見つかり、更新(つまり、キャッシュにダウンロード)されます。
mylib
library. To do this we build it locally and install it to the local Maven cache (how doesn't particularly matter). The next time we perform a dependency resolution, the following will occur:mylib
ライブラリのローカル上での変更をテストしたい場合を考えてみます。これを行うには、ライブラリをローカル上でビルドし、Mavenのローカルキャッシュにインストールします(方法は特に重要ではありません)。この状況で、依存関係の解決を実行した場合、以下のようになります。mylib 1.0-SNAPSHOT
is published changing the version on the server. The next time we perform dependency resolution, the following will happen:mylib 1.0-SNAPSHOT
の新しいバージョンが公開され、サーバ上のファイルが更新されたとします。この状況で依存関係の解決を実行した場合、以下の処理が行われます。- Mavenのローカルリポジトリが検索され、キャッシュ内バージョンと同じ”年齢”の依存関係が見つかりますが、更新(すなわちダウンロード)はされません。
- すでに依存関係を発見したため、Mavenのネットワークリポジトリは検索されません。
しません
。mylib 1.0-SNAPSHOT
in the remote repository), you can either:mylib 1.0-SNAPSHOT
をビルドするために)、次のいずれかを実行できます。- Mavenのローカルリポジトリからバージョンを削除する
BuildConfig.groovy
fileBuildConfig.groovy
ファイル内のリポジトリの順序を変更する
This changing dependency behaviour is an unmodifiable characteristic of the underlying dependency management system Apache Ivy. It is currently not possible to have Ivy search all repositories to look for newer versions (in terms of modification date) of the same dependency (i.e. the same combination ofgroup
,name
andversion
). If you want this behavior consider switching to Aether as the dependency manager.
この変化する依存関係の挙動は、Grailsの依存関係管理システムの基礎となっているApache Ivyの変更不可能な特性です。現在のところIvyは、すべてのリポジトリを検索し、同じ依存関係(すなわち等しいグループ
、名前
、バージョン
の組み合わせ)の中から(修正日付の面で)より新しいバージョンのものを探すことはできません。
4.7.7 依存管理レポート
grails dependency-report
target/dependency-report
directory. You can specify which configuration (scope) you want a report for by passing an argument containing the configuration name:target/dependency-report
ディレクトリにレポートが生成されます。設定名を引数に渡すことで、レポートを作成したい設定(スコープ)を指定することもできます:grails dependency-report runtime
dependency-report
command will also output to the console a graph of the dependencies of an application. Example output it shown below:dependency-report
コマンドはアプリケーションの依存関係のグラフをコンソールへ出力します。出力例を以下に示します:compile - Dependencies placed on the classpath for compilation (total: 73)
+--- org.codehaus.groovy:groovy-all:2.0.6
+--- org.grails:grails-plugin-codecs:2.3.0
| --- org.grails:grails-web:2.3.0
| --- commons-fileupload:commons-fileupload:1.2.2
| --- xpp3:xpp3_min:1.1.4c
| --- commons-el:commons-el:1.0
| --- opensymphony:sitemesh:2.4
| --- org.springframework:spring-webmvc:3.1.2.RELEASE
| --- commons-codec:commons-codec:1.5
| --- org.slf4j:slf4j-api:1.7.2
+--- org.grails:grails-plugin-controllers:2.3.0
| --- commons-beanutils:commons-beanutils:1.8.3
| --- org.grails:grails-core:2.3.0
...
4.7.8 プラグインJAR依存
プラグインJARの依存関係を指定する
export
property of the dependency:エクスポートしたくない
依存関係を定義するには、export
プロパティを使用します:
compile('org.spockframework:spock-core:0.5-groovy-1.8') {
export = false
}
compile group: 'org.spockframework', name: 'spock-core',
version: '0.5-groovy-1.8', export: false
You can useexported = false
instead ofexport = false
, but we recommend the latter because it's consistent with the Map argument.
export=false
の代わりにexported=false
を使用することができますが、Mapの引数と一致しているため前者を推奨します。
独自アプリケーションでプラグインのJAR依存関係をオーバーライドする
plugins { compile(":hibernate:$grailsVersion") { excludes "javassist" } }dependencies { runtime "javassist:javassist:3.4.GA" }
excludes
method, effectively excluding the javassist library as a dependency.excludes
メソッドを使用して除外する依存関係を指定することで、Javassistライブラリを依存関係から除外します。
4.7.9 Maven統合
pom.xml
file.pom.xml
ファイルで依存関係の解決が行なわれると判断し、Grailsでの依存関係解決機能は無効化されますpom.xml
file instead.pom.xml
ファイルから依存関係をロードするように教えることができますBuildConfig.groovy
:BuildConfig.groovy
に以下の行を追加するだけで簡単にできます:grails.project.dependency.resolution = {
pom true
..
}
pom true
tells Grails to parse Maven's pom.xml
and load dependencies from there.pom true
行は、Mavenのpom.xml
ファイルの構文解析を行いそこから依存関係をロードする、ということをGrailsに通達します。
4.7.10 Mavenリポジトリへのデプロイ
mvn install
and mvn deploy
.mvn install
およびmvn deploy
を使用できます。
- maven-install - MavenのローカルキャッシュにGrailsプロジェクトやプラグインをインストールします。
- maven-deploy - MavenのリモートリポジトリにGrailsプロジェクトやプラグインをデプロイします。
pom.xml
for you unless a pom.xml
is already present in the root of the project, in which case this pom.xml
file will be used.pom.xml
を生成します。ただし、pom.xml
がすでにプロジェクトルートに存在する場合には、プロジェクトルート上のpom.xml
ファイルが使用されます。maven-installコマンド
maven-install
command will install the Grails project or plugin artifact into your local Maven cache:maven-install
コマンドは、MavenのローカルキャッシュにGrailsプロジェクトやプラグインをインストールします:grails maven-install
maven-deployコマンド
maven-deploy
command will deploy a Grails project or plugin into a remote Maven repository:maven-deploy
コマンドは、MavenのリモートリポジトリにGrailsプロジェクトやプラグインをデプロイします:grails maven-deploy
<distributionManagement>
configuration within a pom.xml
or that you specify the id
of the remote repository to deploy to:pom.xml
ファイル内に必要な<distributionManagement>
の設定がされているか、もしくはデプロイするリモートリポジトリのid
を指定すること前提としています:grails maven-deploy --repository=myRepo
repository
argument specifies the 'id' for the repository. Configure the details of the repository specified by this 'id' within your grails-app/conf/BuildConfig.groovy
file or in your $USER_HOME/.grails/settings.groovy
file:repository
引数は、リポジトリの'id'を指定します。この指定した'id'に対するリポジトリの詳細を、grails-app/conf/BuildConfig.groovy
ファイルもしくは$USER_HOME/.grails/settings.groovy
ファイル内で設定します:grails.project.dependency.distribution = { localRepository = "/path/to/my/local" remoteRepository(id: "myRepo", url: "http://myserver/path/to/repo") }
<remoteRepository id="myRepo" url="scp://localhost/www/repository"> <authentication username="..." privateKey="${user.home}/.ssh/id_dsa"/> </remoteRepository>
remoteRepository(id: "myRepo", url: "scp://localhost/www/repository") { authentication username: "...", privateKey: "${userHome}/.ssh/id_dsa" }
grails maven-deploy --repository=myRepo --protocol=webdav
- http
- scp
- scpexe
- ftp
- webdav
グループ、アーティファクト、バージョン
プロジェクト
pom.xml
file. To change the version you can run the set-version
command:pom.xml
ファイル生成時にGrailによって提供されるGrailsアプリケーションの名前とバージョンを使用します。バージョンを変更するには、set-version
コマンドを実行します:grails set-version 0.2
groupId
will be the same as the project name, unless you specify a different one in Config.groovy:groupId
は、Config.groovyに別の名前を指定しない限り、プロジェクト名と同じになります:grails.project.groupId="com.mycompany"
プラグイン
groupId
and version
are taken from the following properties in the GrailsPlugin.groovy
descriptor:groupId
とversion
は、GrailsPlugin.groovy
内の以下のプロパティから取得されます:
String groupId = 'myOrg' String version = '0.1'
FeedsGrailsPlugin
the artifactId
will be "feeds". If your plugin does not specify a groupId
then this defaults to "org.grails.plugins".FeedsGrailsPlugin
というプラグインの場合、artifactId
は "feeds"になります。プラグインがgroupId
を指定していない場合、デフォルト設定の"org.grails.plugins"となります。
4.7.11 プラグイン依存管理
grails.project.dependency.resolution = { … repositories { … }plugins { runtime ':hibernate:1.2.1' }
dependencies { … } … }
org.grails.plugins
is used. org.grails.plugins
が使用されます。Latest Integrationラベル
Only the Ivy dependency manager supports the "latest.integration" version. For Aether you can achieve a similar effect with version ranges.
Ivy依存関係マネージャは"latest.integration"バージョンをサポートしています。Aetherの場合は、バージョンの範囲指定で同様の効果を得ることができます。
plugins { runtime ':hibernate:latest.integration' }
Integrationラベル vs. Releaseラベル
plugins { runtime ':hibernate:latest.release' }
The "latest.release" label only works with Maven compatible repositories. If you have a regular SVN-based Grails repository then you should use "latest.integration".
"latest.release"ラベルはMavenの互換リポジトリでのみ動作します。通常のSVNベースのGrailsリポジトリの場合は、"latest.integration"を使用する必要があります。
plugins { runtime 'mycompany:hibernate:latest.integration' }
プラグインの除外
plugins {
runtime(':weceem:0.8') {
excludes "searchable"
}
}
excludes
method you can tell Grails not to transitively install the searchable plugin. You can combine this technique to specify an alternative version of a plugin:excludes
メソッドを使用することで、Grailsにsearchableプラグインを推移的にインストール_しない_ことを教えることができます。あわせて、プラグインの代替バージョンを指定することもできます:plugins {
runtime(':weceem:0.8') {
excludes "searchable" // excludes most recent version
}
runtime ':searchable:0.5.4' // specifies a fixed searchable version
}
plugins {
runtime(':weceem:0.8') {
transitive = false
}
runtime ':searchable:0.5.4' // specifies a fixed searchable version
}
4.7.12 依存管理のキャッシュ
grails clean
)- プロジェクトがクリーンな場合(すなわち、チェックアウト直後または
grails clean
の実行後)
BuildConfig.groovy
file has changed since the last command was run- 最後にコマンドが実行された後に、
BuildConfig.groovy
ファイルが変更された場合
--refresh-dependencies
command line switch is provided to the command (any command)--refresh-dependencies
引数が、何らかのコマンドに与えられる場合
refresh-dependencies
command is the command being executedrefresh-dependencies
コマンドが実行された場合
BuildConfig.groovy
) Grails will do the right thing and resolve your new dependencies.BuildConfig.groovy
を変更するたびに)Grailsは正しく新たに依存関係解決を実行します。latest.integration
).
{info}
{info}
変化する依存関係 は、バージョン番号が変更されずに、内容が変化するもの(スナップショットなど)です。 動的な依存関係 は多くの可能なオプションのいずれかとして定義されるものです。(バージョンが範囲指定されている、またはlatest.integration
のように抽象的なバージョン番号を持つ依存関係など)
{info}
latest.integration
. Or if you declare a SNAPSHOT
dependency, you may not automatically get the latest that's available on the server.latest.integration
を使用している場合、プロジェクトは依存関係の最新バージョンを自動的に取得しないでしょう。また、SNAPSHOT
の依存関係を宣言した場合、サーバー上で使用可能な最新のものを自動的に取得できない可能性があります。- プロジェクトのクリーンアップ
refresh-dependencies
commandrefresh-dependencies
コマンドの実行
--refresh-dependencies
switch; or任意のコマンド
に--refresh-dependencies
を付与して実行
BuildConfig.groovy
BuildConfig.groovy
を変更
--refresh-dependencies
switch to the command you use to build your projects.--refresh-dependencies
を追加しておくと有効でしょう。