Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: initialize a static variable with a value defined in config.groovy

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?

like image 520
Agorreca Avatar asked Dec 14 '12 15:12

Agorreca


1 Answers

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
}
like image 161
Ian Roberts Avatar answered Nov 02 '22 23:11

Ian Roberts