2012-12-14 5 views
5

में परिभाषित मान के साथ एक स्थैतिक चर प्रारंभ करें config.groovy में परिभाषित मान के साथ static चर प्रारंभ कैसे कर सकता हूं? (कई मिलता है, पोस्ट, डाल दिया और DELETE)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 चर को परिभाषित नहीं करना चाहती:

वर्तमान में मैं कुछ इस तरह की है।

मैं 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

एक स्थिर की बजाय, एक आवृत्ति संपत्ति का उपयोग करें (क्योंकि सेवा बीन्स सिंगलटन स्कॉप्ड हैं)। आप कन्स्ट्रक्टर में प्रारंभिकता नहीं कर सकते हैं, क्योंकि निर्भरताओं को अभी तक इंजेक्शन नहीं दिया गया है, लेकिन आप @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

धन्यवाद इयान! एक जादू की तरह काम करता है :) – Agorreca