Access grailsApplication or Service in groovy class

后端 未结 4 786
长情又很酷
长情又很酷 2021-02-14 15:20

I am trying to access grailsApplication in groovy class under src/groovy but I get a null pointer exception. I also tried to inject a service into the

相关标签:
4条回答
  • 2021-02-14 15:43

    Dependency injection does not work for groovy classes under src/groovy. You can get the access to grailsApplication using ApplicationHolder like this:

    import org.codehaus.groovy.grails.commons.ApplicationHolder
    
    def grailsApplication = ApplicationHolder.application
    

    You can access all services like this:

    def allServicesArtefacts = grailsApplication.services
    
    0 讨论(0)
  • 2021-02-14 15:49

    If you have classes that you want to participate with dependency injection from src/groovy or src/java or even 3rd party jars all you have to do is configure them in grails-app/conf/spring/resources.groovy.

    If you had the class mypackage.MyClass in your src/groovy directory that looked like this:

    package mypackage
    class MyClass{
        def grailsApplication
        def myMethod(){
            //uses grailsApplication
        }
    }
    

    Then by adding the following to grails-app/conf/spring/resoruces.groovy it would get auto-injected:

    myClass(mypackage.MyClass){bean->
        bean.autowire = "byName"    
    }
    

    This will work in any version of grails thusfar, and like I said you can even use 3rd party jars - for example I ALWAYS have the following in my resources.groovy:

    jdbcTemplate(org.springframework.jdbc.core.JdbcTemplate){
        dataSource = ref('dataSource')
    }
    

    For more comprehensive Spring/Grails documentation see:

    http://grails.github.io/grails-doc/latest/guide/spring.html

    0 讨论(0)
  • 2021-02-14 15:57

    The ApplicationHolder class is deprecated in newer Grails versions (2.0 and above).

    There is another way, which is described in one of Burt's blogposts: http://burtbeckwith.com/blog/?p=1017

    0 讨论(0)
  • 2021-02-14 15:58

    After Grails 2.0, you should use:

     def grailsApplication = Holders.grailsApplication
    
    0 讨论(0)
提交回复
热议问题