GrailsApplication null in service

I have a service in a Grails application. However, I need to get the configuration for some configuration in my application. But when I try to use def grailsApplication in my service, it still gets null.

My service is located in the "Services" section.

 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 looked at the Grails application configuration for applications , but it does not give me an answer, since everything seems to be correct.

However, I call my Service as follows: def xml = new RelationService().getRequest(url)

EDIT:

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

+4
source share
1 answer

Your service is correct, but the way to call it is not as follows:

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

Since you are creating the new object “manually”, you are actually bypassing the injection made by Spring, and therefore the grailsApplication object is null.

What you need to do is enter your service using Spring as follows:

 class MyController{ def relationService def home(){ def xml = relationService.getRequest(...) } } 
+3
source

Source: https://habr.com/ru/post/1447987/


All Articles