6

staticで定義された値で変数を初期化するにはどうすればよいconfig.groovyですか?

現在、私はこのようなものを持っています:

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}")
        ...
    }
}

http各メソッド(いくつかのGET、POST、PUT、およびDELETE)内で変数を定義したくありません。

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}")
    }
}

どんな手掛かり?

4

1 に答える 1

15

静的ではなく、インスタンスプロパティを使用します(サービス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
}
于 2012-12-14T16:02:35.453 に答える