【问题标题】:grailsApplication null in Service服务中的 grailsApplication null
【发布时间】:2012-11-12 00:17:24
【问题描述】:

我的 Grails 应用程序中有一个服务。但是,我需要在我的应用程序中访问配置以进行某些配置。但是当我尝试在我的服务中使用def grailsApplication 时,它仍然为空。

我的服务在“服务”下。

class RelationService {

    def grailsApplication

    private String XML_DATE_FORMAT = "yyyy-MM-dd"
    private String token = 'hej123'
    private String tokenName
    String WebserviceHost = 'xxx'

    def getRequest(end_url) {

        // Set token and tokenName and call communicationsUtil
        setToken();
        ComObject cu = new ComObject(tokenName)

        // Set string and get the xml data
        String url_string = "http://" + WebserviceHost + end_url
        URL url = new URL(url_string)

        def xml = cu.performGet(url, token)

        return xml
    }

    private def setToken() {
        tokenName = grailsApplication.config.authentication.header.name.toString()
        try {
            token = RequestUtil.getCookie(grailsApplication.config.authentication.cookie.token).toString()
        }
        catch (NoClassDefFoundError e) {
            println "Could not set token, runs on default instead.. " + e.getMessage()
        }
        if(grailsApplication.config.webservice_host[GrailsUtil.environment].toString() != '[:]')
            WebserviceHost = grailsApplication.config.webservice_host[GrailsUtil.environment].toString()

    }

}

我查看了Inject grails application configuration into service,但它没有给我答案,因为一切似乎都是正确的。

但是我这样称呼我的服务:def xml = new RelationService().getRequest(url)

编辑:

忘记输入我的错误,即:Cannot get property 'config' on null object

【问题讨论】:

    标签: grails


    【解决方案1】:

    您的服务是正确的,但您调用它的方式不正确:

    def xml = new RelationService().getRequest(url)
    

    因为您正在“手动”实例化一个新对象,所以您实际上绕过了 Spring 进行的注入,因此“grailsApplication”对象为空。

    你需要做的是像这样使用 Spring 注入你的服务:

    class MyController{
    
        def relationService 
    
        def home(){
           def xml = relationService.getRequest(...)
        }
    
    }
    

    【讨论】:

    • 非常感谢 :) 之前尝试过,但我认为它在编译时出错了,因为之前我遇到了一些静态错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多