简体   繁体   中英

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM