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

Ago*_*eca 5 grails groovy spring 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}")
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我不想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(...)
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到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(...)
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我也试过没有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}")
    }
}
Run Code Online (Sandbox Code Playgroud)

任何线索?

Ian*_*rts 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
}
Run Code Online (Sandbox Code Playgroud)