2012-12-14 1 views
5

config.groovy에 정의 된 값으로 static 변수를 초기화하는 방법은 무엇입니까?Grails : config.groovy에 정의 된 값으로 정적 변수를 초기화하십시오.

은 현재 내가 이런 일이 : 나는 각 방법 안에 http 변수를 정의하지 않으

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 변수를 서비스 내에 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}") 
    } 
} 

어떤 단서?

답변

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

관련 문제