Ways to access grailsApplication in Grails Project
Posted By : Archna Dhingra | 07-Jul-2014
In one of my projects I had this requirement to access grailsApplication, so I tried a number of methods and found them useful to share with you.
Following are the few ways which you can use in your grails project.
1. def grailsApplication
This has been the most common method to access grailsApplication till now, but after grails 2.3.6 this sometimes gives null pointer exception. So you can go with the next method.
2. GrailsApplication grailsApplication
The null pointer exception is resolved when you access grailsApplication using this method. But don’t forget to import "org.codehaus.groovy.grails.commons.GrailsApplication".
3. domainClass.grailsApplication
While trying to access grailsApplication in a domain class use this method.
4. ApplicationContextHolder
You can also access it from ApplicationContext using the following approach.
class ApplicationContextHolder implements ApplicationContextAware { private ApplicationContext appContext void setApplicationContext(ApplicationContext applicationContext) { appContext = applicationContext } static ApplicationContext getApplicationContext() { getInstance().appContext } static GrailsApplication getGrailsApplication() { getBean('grailsApplication') } }
Declaration in bean :
applicationContextHolder(ApplicationContextHolder) { bean -> bean.factoryMethod = 'getInstance' }
Now get grailsApplication wherever you need using :
def applicationContextHolder def grailsApplication = applicationContextHolder.getGrailsApplication()
5. Using Holders :
Holders.getGrailsApplication()
6. Using servletContext :
ApplicationContext context = ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT) as ApplicationContext GrailsApplication grailsApplication = context.getBean(GrailsApplication)
Thanks,
Archna Dhingra.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Archna Dhingra
Archna is a bright Groovy and Grails developer and has worked on development of various SaaS applications using Grails framework.