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

时间:2012-12-14 15:43:06

标签: spring grails groovy static code-injection

如何使用static中定义的值初始化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变量作为static变量。

我尝试了这个没有成功:

class ApiService {

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

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

我得到Cannot get property 'config' on null object。同样的:

class ApiService {

    def grailsApplication
    static http

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

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

我也尝试过没有static定义,但同样的错误Cannot get property 'config' on null object

class ApiService {

    def grailsApplication
    def http

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

有任何线索吗?

1 个答案:

答案 0 :(得分:14)

而不是静态,使用实例属性(因为服务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
}