Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

groovy - How to access Grails configuration in Grails 2.0?

I have obtained the latest Grails 2.0 milestone, and I am seeing a deprecation warning for the ConfigurationHolder class:

org.codehaus.groovy.grails.commons.ConfigurationHolder

The deprecation message simply says "Use dependency injection instead" which is not very helpful to me. I understand dependency injection, but how can I wire up a bean with the proper Grails configuration so I can access it at runtime? I need to access the configuration from places other than my Controllers and Tags (such as BootStrap).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • If you need it in an artifact that supports dependency injection, simply inject grailsApplication

    class MyController {
        def grailsApplication
    
        def myAction = {
            def bar = grailsApplication.config.my.property
        }
    }
    
  • If you need it in a bean in, say, src/groovy or src/java, wire it up using conf/spring/resources.groovy

    // src/groovy/com/example/MyBean.groovy
    class MyBean {
        def grailsApplication
    
        def foo() {
            def bar = grailsApplication.config.my.property
        }
    }
    
    // resources.groovy
    beans = {
        myBean(com.example.MyBean) {
            grailsApplication = ref('grailsApplication')
            // or use 'autowire'
        }
    }
    
  • Anywhere else, it's probably easiest to either pass the configuration object to the class that needs it, or pass the specific properties that are needed.

    // src/groovy/com/example/NotABean.groovy
    class NotABean {
        def foo(def bar) {
           ...
        }
    }
    
    // called from a DI-supporting artifact
    class MyController {
        def grailsApplication
        def myAction = {
            def f = new NotABean()
            f.foo(grailsApplication.config.my.property)
        }
    }
    

Update:

Burt Beckwith recently wrote a couple of blog posts on this. One discusses using getDomainClass() from within domain classes, while the other offers the option of creating your own holder class (if none of the solutions above are appropriate).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...