【问题标题】:Grails: initialize a static variable with a value defined in config.groovyGrails:使用 config.groovy 中定义的值初始化静态变量
【发布时间】:2012-12-02 15:21:35
【问题描述】:

如何使用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定义,但同样的错误Cannot get property 'config' on null object

class ApiService {

    def grailsApplication
    def http

    ApiService() {
        super()
        http = new HTTPBuilder("${grailsApplication.config.grails.api.server.url}")
    }
}

有什么线索吗?

【问题讨论】:

    标签: spring grails groovy static code-injection


    【解决方案1】:

    使用实例属性而不是静态属性(因为服务 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
    }
    

    【讨论】:

    • 谢谢伊恩!像魅力一样工作:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 2017-05-13
    • 2011-08-22
    • 2010-12-22
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多