How can I initialize a static
variable with a value defined in config.groovy
?
Currently I have something like this:
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}")
...
}
}
I don't want to define the http
variable inside each method (several GET, POST, PUT and DELETE).
I want to have the http
variable as a static
variable inside the service.
I tried this without success:
class ApiService {
static grailsApplication
static http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")
JSON get(String path) {
http.get(...)
...
}
}
I get Cannot get property 'config' on null object
. The same with:
class ApiService {
def grailsApplication
static http
ApiService() {
super()
http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")
}
JSON get(String path) {
http.get(...)
...
}
}
Also I tried without a static
definition, but the same error Cannot get property 'config' on null object
:
class ApiService {
def grailsApplication
def http
ApiService() {
super()
http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")
}
}
Any clue?
Rather than a static, use an instance property (as service beans are singleton scoped). You can't do the initialization in the constructor, as dependencies haven't yet been injected, but you can use a method annotated @PostConstruct
, which will be called by the framework after dependency injection.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With