Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grailsApplication null in Service

Tags:

grails

I have a Service in my Grails application. However I need to reach the config for some configuration in my application. But when I am trying to use def grailsApplication in my Service it still gets null.

My service is under "Services".

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()

    }

}

I have looked on Inject grails application configuration into service but it doesn't give me an answer as everything seems correct.

However I call my Service like this: def xml = new RelationService().getRequest(url)

EDIT:

Forgot to type my error, which is: Cannot get property 'config' on null object

like image 656
Ms01 Avatar asked Nov 23 '12 15:11

Ms01


1 Answers

Your service is correct but the way you are calling it is not:

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

Because you are instantiating a new object "manually "you are actually bypassing the injection made by Spring and so the "grailsApplication" object is null.

What you need to do is injecting your service using Spring like this:

class MyController{

    def relationService 

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

}
like image 56
Benoit Wickramarachi Avatar answered Oct 24 '22 07:10

Benoit Wickramarachi