微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

spring – Grails:使用config.groovy中定义的值初始化静态变量

如何使用config.groovy中定义的值初始化静态变量?

目前我有这样的事情:

class ApiService {
    JSON get(String path) {
        def http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")
        ...
    }
    JSON get(String path,String token) {
        def http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")
        ...
    }
    ...
    JSON post(String path,String token) {
        def http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")
        ...
    }
}

我不想在每个方法中定义http变量(几个GET,POST,PUT和DELETE).

我希望将http变量作为服务中的静态变量.

我尝试了这个没有成功:

class ApiService {

    static grailsApplication
    static http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")

    JSON get(String path) {
        http.get(...)
        ...
    }
}

我得到无法在null对象上获取属性’config’.同样的:

class ApiService {

    def grailsApplication
    static http

    ApiService() {
        super()
        http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")
    }

    JSON get(String path) {
        http.get(...)
        ...
    }
}

我也试过没有静态定义,但同样的错误无法在null对象上获取属性’config’:

class ApiService {

    def grailsApplication
    def http

    ApiService() {
        super()
        http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")
    }
}

任何线索?

最佳答案
而不是静态,使用实例属性(因为服务bean是单例作用域).您无法在构造函数中进行初始化,因为尚未注入依赖项,但您可以使用带注释的@postconstruct方法,该方法将在依赖项注入后由框架调用.

import javax.annotation.postconstruct

class ApiService {
  def grailsApplication
  HTTPBuilder http

  @postconstruct
  void init() {
    http = new HTTPBuilder(grailsApplication.config.grails.api.server.url)
  }

  // other methods as before
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐