6

Grails アプリケーションに Service があります。ただし、アプリケーションの一部の構成の構成に到達する必要があります。しかしdef grailsApplication、サービスで使用しようとすると、まだ null になります。

私のサービスは「サービス」の下にあります。

class RelationService {

    def grailsApplication

    private String XML_DATE_FORMAT = "yyyy-MM-dd"
    private String token = 'hej123'
    private String tokenName
    String WebserviceHost = 'xxx'

    def getRequest(end_url) {

        // Set token and tokenName and call communicationsUtil
        setToken();
        ComObject cu = new ComObject(tokenName)

        // Set string and get the xml data
        String url_string = "http://" + WebserviceHost + end_url
        URL url = new URL(url_string)

        def xml = cu.performGet(url, token)

        return xml
    }

    private def setToken() {
        tokenName = grailsApplication.config.authentication.header.name.toString()
        try {
            token = RequestUtil.getCookie(grailsApplication.config.authentication.cookie.token).toString()
        }
        catch (NoClassDefFoundError e) {
            println "Could not set token, runs on default instead.. " + e.getMessage()
        }
        if(grailsApplication.config.webservice_host[GrailsUtil.environment].toString() != '[:]')
            WebserviceHost = grailsApplication.config.webservice_host[GrailsUtil.environment].toString()

    }

}

Inject grails application configuration into serviceを見てきましたが、すべてが正しいように見えるため、答えが得られません。

ただし、次のように Service を呼び出します。def xml = new RelationService().getRequest(url)

編集:

次のエラーを入力するのを忘れました。Cannot get property 'config' on null object

4

1 に答える 1

3

あなたのサービスは正しいですが、あなたがそれを呼んでいる方法はそうではありません:

def xml = new RelationService().getRequest(url)

新しいオブジェクトを「手動で」インスタンス化しているため、実際にはSpringによる注入をバイパスしているため、「grailsApplication」オブジェクトはnullです。

あなたがする必要があるのは、次のように Spring を使用してサービスを注入することです。

class MyController{

    def relationService 

    def home(){
       def xml = relationService.getRequest(...)
    }

}
于 2012-11-23T16:24:02.100 に答える