如何使用 config.groovy
中定义的值初始化 static
变量?
目前我有这样的东西:
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}")
...
}
}
我不想在每个方法(多个 GET、POST、PUT 和 DELETE)中定义 http
变量。
我希望将 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
定义,但出现同样的错误无法在空对象上获取属性“config”
:
class ApiService {
def grailsApplication
def http
ApiService() {
super()
http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")
}
}
有什么线索吗?
最佳答案
使用实例属性而不是静态属性(因为服务 bean 是单例范围的)。您无法在构造函数中进行初始化,因为尚未注入(inject)依赖项,但您可以使用带注释的 @PostConstruct
方法,该方法将在依赖项注入(inject)后由框架调用。
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
}
关于spring - Grails:使用 config.groovy 中定义的值初始化静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13881821/