Announcement Announcement Module
No announcement yet.
Fire Code Once at Application Context Load Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

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

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