2012-12-14 29 views
5

config.groovyで定義された値でstatic変数を初期化するにはどうすればよいですか?私は(いくつかのGET、POSTとPUTおよびDELETE)の各メソッド内http変数を定義する必要はありませんGrails: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変数をサービス内の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 
    def http 

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

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

答えて

14

静的ではなく、インスタンスプロパティを使用します(サービス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 
} 
+0

ありがとうIan!魅力的な作品:) – Agorreca

関連する問題