LoginSignup
1
1

More than 5 years have passed since last update.

[Grails] 起動時・終了時になにか処理をしたい場合

Last updated at Posted at 2013-10-23

Grailsの起動時や終了時になにか処理を挟みたい場合、BootStrap.groovy の中にその処理を記述します。

  • Environment.executeForCurrentEnvironment
  • environments

上記のどちらかを利用することで、起動モードで処理を切り分けられます。
それぞれ開始時と終了時で使ってみた場合のサンプルです。

grails-app/conf/BootStrap.groovy
import grails.util.Environment
import grailssamples.Person

class BootStrap {

    // Grails開始時に実行される
    def init = { servletContext ->
        Environment.executeForCurrentEnvironment {
            development {
                println "dev!"
            }
            test {
                println "test!"
            }
            production{
                println "production!"
            }
        }
    }

    // Grails終了時に実行される
    def destroy = {
        environments {
            development {
                println "dev end!"
            }
            test {
                println "test end!"
            }
            production{
                println "production end!"
            }
        }
    }
}

それぞれの起動方法は

grails dev run-app
grails test run-app
grails prod run-app

実行結果は以下のような感じ。

grails> run-app
| Running Grails application
Okt 24, 2013 10:00:23 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Okt 24, 2013 10:00:23 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
Okt 24, 2013 10:00:23 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.39
Okt 24, 2013 10:00:23 AM org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
INFO: No global web.xml found
Okt 24, 2013 10:00:23 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
dev!
| Server running. Browse to http://localhost:8080/grailssamples
| Application loaded in interactive mode. Type 'stop-app' to shutdown.
| Enter a script name to run. Use TAB for completion:
grails>
grails> stop-app
| Stopping Grails server
dev end!
grails>

devの場合は grails run-app のように省略できます。
importすればドメインクラスも問題なく利用できます。
主に、開発時点でのテストデータの挿入などに利用できそうです。

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1