-
Feb 17th, 2011, 11:06 AM
#1
Fire Code Once at Application Context Load
I looking for a way to execute some code when the application context has been loaded and when it is shutdown. I only need to do this once for the root application context (not any of the other application contexts like spring-mvc, struts, etc...).
I looked into using the ContextStartedEvent but it flat out doesn't work. It never fires...period. It is either really poorly named or there is some bug there. Next I looked into the ContextRefreshedEvent but that fires for each of the other contexts as well, and I can only execute my code once at startup.
The only other method I have found is to use a ServletContextListener but I rather not bind my code to being web app specific and I really want to keep my code attached to Spring, rather than attached to the web.xml file. It would also be much more difficult to unit test a ServletContextListener than a class injected via Spring.
Does anyone know how to execute code at application context load only once? Thanks in advance for your help.
-
Feb 17th, 2011, 07:24 PM
#2
ContextStartedEvent gets fired when the ApplicationContext is manually started. So unless you are explicitly starting your context, this event will not fire.
All ApplicationContexts that I have used always end up calling refresh() inside their constructor. So in my case, I can use ContextRefreshedEvent successfully. Furthermore, I can check is the refresh event I received is from the root context or not by calling getApplicationContext().getParent(). Null means the event was from the root context.
Using the ContextClosedEvent is similar.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules