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...?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With