如何使用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}")
}
}
有任何线索吗?
答案 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
}