简体   繁体   English

在groovy类中访问grailsApplication或Service

[英]Access grailsApplication or Service in groovy class

I am trying to access grailsApplication in groovy class under src/groovy but I get a null pointer exception. 我试图在src/groovy下的groovy类中访问grailsApplication ,但是我得到一个空指针异常。 I also tried to inject a service into the same class and same result. 我还尝试将服务注入到同一个类和相同的结果中。 How can I access grailsApplication or a service from groovy class? 如何从groovy类访问grailsApplication或服务? (I am using Grails 1.3.7) (我使用的是Grails 1.3.7)

The ApplicationHolder class is deprecated in newer Grails versions (2.0 and above). ApplicationHolder类在较新的Grails版本(2.0及更高版本)中已弃用。

There is another way, which is described in one of Burt's blogposts: http://burtbeckwith.com/blog/?p=1017 还有另一种方式,在Burt的一篇博文中有描述: http ://burtbeckwith.com/blog/?p = 1017

在Grails 2.0之后,你应该使用:

 def grailsApplication = Holders.grailsApplication

Dependency injection does not work for groovy classes under src/groovy . 依赖注入对src/groovy下的groovy类不起作用。 You can get the access to grailsApplication using ApplicationHolder like this: 您可以使用ApplicationHolder访问grailsApplication如下所示:

import org.codehaus.groovy.grails.commons.ApplicationHolder

def grailsApplication = ApplicationHolder.application

You can access all services like this: 您可以访问以下所有服务:

def allServicesArtefacts = grailsApplication.services

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. 如果您希望参与src / groovy或src / java或第三方jar的依赖注入,那么您所要做的就是在grails-app / conf / spring / resources.groovy中配置它们。

If you had the class mypackage.MyClass in your src/groovy directory that looked like this: 如果你的src / groovy目录中的类mypackage.MyClass看起来像这样:

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: 然后通过将以下内容添加到grails-app / conf / spring / resoruces.groovy中,它将自动注入:

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: 这将适用于任何版本的grails,就像我说你甚至可以使用第三方罐子 - 例如我总是在我的resources.groovy中有以下内容:

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

For more comprehensive Spring/Grails documentation see: 有关更全面的Spring / Grails文档,请参阅:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM