Grails ways of getting grails application object



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.
1
2
3
4
5
6
7
8
9
10
11
12
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 :
1
2
3
applicationContextHolder(ApplicationContextHolder) { bean ->
  bean.factoryMethod = 'getInstance'
}

Now get grailsApplication wherever you need using :
1
2
def applicationContextHolder
def grailsApplication = applicationContextHolder.getGrailsApplication()

5. Using Holders :
1
Holders.getGrailsApplication()

6.  Using servletContext :
1
2
3
ApplicationContext context = ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
  as ApplicationContext
GrailsApplication grailsApplication = context.getBean(GrailsApplication)
- See more at: http://www.oodlestechnologies.com/blogs/Ways-to-access-grailsApplication-in-Grails-Project#sthash.gfbXCX24.dpuf

Comments

Popular posts from this blog

Conversion from Clob To String in java and Vice versa

Portable Java 8/ JDK8 setup without admin rights

Multi Threading , Producer consumer problem in Java