Blog

  • 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.

Tags: grails