Grails: Access spring beans in closing Bootstrap program.

I am looking for access to a bean in my closure destruction in Bootstrap.groovy of my grails project. Any ideas on how to achieve this?

It seems I don't have access to servletContext ...?

+6
spring grails bootstrapping
source share
3 answers

You can get a link to applicationContext everywhere (including destroying BootStrap closure) using this piece of code:

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

Getting a bean reference is as simple 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 example:

 def bean = SpringUtil.getBean("beanName") 

Cheers, Sigi

+15
source share

I know that everything here is late, and that’s all, but since I found it through Google ...

Spring beans by name is introduced into the BootStrap class, like all services and controllers and so on. If you want a bean, just identify it by name and it will appear. Otherwise, just define grailsApplication and go to grailsApplication.mainContext.getBean etc.

+6
source share

Hmm, I can't find a single example of anyone even using closing the kill block in Bootstrap. From the docs:

  It is not guaranteed that {{destroy}} will be called unless the 
 application exits gracefully (for example by using the application 
 server shutdown command) so don't rely on it too much 

As I said, I have to say that the servletContext was already destroyed before the {{destroy}} Bootstrap closes, so the bean you are trying to access is already gone. Can anyone confirm?

+2
source share

All Articles