如何使用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方法,该方法将在依赖项注入后由框架调用.
原文链接:https://www.f2er.com/spring/431857.htmlimport 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
}