Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: Accessing spring beans in the destory closure of Bootstrap code?

I'm looking to access a bean in my destroy closure in the Bootstrap.groovy of my grails project. Any ideas on how to achieve this?

I seem to have no access to servletContext...?

like image 383
wilth Avatar asked Feb 22 '09 11:02

wilth


1 Answers

You can obtain a a reference to the applicationContext from everywhere (including the destroy closure of BootStrap) using that chunk of code:

def ctx = org.codehaus.groovy.grails.web.context.ServletContextHolder.servletContext.getAttribute(org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes.APPLICATION_CONTEXT);

Getting a reference to a bean is as easy as ctx.beanName.

Here is a small util class (written in Java) that can simplify this task:

import org.springframework.context.ApplicationContext;
import org.codehaus.groovy.grails.web.context.ServletContextHolder;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;

public class SpringUtil {

    public static ApplicationContext getCtx() {
        return getApplicationContext();
    }

    public static ApplicationContext getApplicationContext() {
        return (ApplicationContext) ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        return (T) getApplicationContext().getBean(beanName);
    }

}

and an example:

def bean = SpringUtil.getBean("beanName")

Cheers, Sigi

like image 84
Siegfried Puchbauer Avatar answered Oct 14 '22 02:10

Siegfried Puchbauer