Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access grailsApplication.config from a groovy class?

I'm using Grails 1.2.1. How do I access my grailsApplication.config variable? I have this class ...

public class Utility {
    def grailsApplication
...
    public static boolean isAuthorizedHost(String hostIpAddr) {
        // Simple validation
        if (hostIpAddr == null || hostIpAddr.length() == 0)
            return false;
        //
        def allowedDomains = grailsApplication.config.proxy.allowedDomains

but I'm getting this compilation error ...

 [groovyc] /Users/davea/Documents/workspace-sts-2.6.0.SR1/socialmediaproxy/src/groovy/com/nna/tool/proxy/Utility/Utility.groovy: 26: Apparent variable 'grailsApplication' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
  [groovyc] You attempted to reference a variable in the binding or an instance variable from a static context.
  [groovyc] You misspelled a classname or statically imported field. Please check the spelling.
  [groovyc] You attempted to use a method 'grailsApplication' but left out brackets in a place not allowed by the grammar.
  [groovyc]  @ line 26, column 24.
  [groovyc]         def allowedDomains = grailsApplication.config.proxy.allowedDomains

Thanks for any advice, - Dave

like image 751
Dave Avatar asked Dec 01 '22 03:12

Dave


2 Answers

The automatic injection of grailsApplication instance is only available in your Spring-managed beans (Grails artefacts and beans declared in resource.groovy).

To read configuration values from other classes, you can use this method:

def config = org.codehaus.groovy.grails.commons.ConfigurationHolder.config
def allowedDomains = config.proxy.allowedDomains
like image 72
deluan Avatar answered Jan 26 '23 00:01

deluan


import grails.util.Holders

def grailsApplication = Holders.grailsApplication

The other answer is depreciated. (Answer tested on Grails 2.5.0)

like image 34
Priyanshu Chauhan Avatar answered Jan 25 '23 23:01

Priyanshu Chauhan