6

Are there any hooks into the Spring ApplicationContext loading process?

I want to run a piece of code just before the application context loads (before any beans/properties/aspects/etc... are instantiated).

thanks in advance

skaffman
  • 398,947
  • 96
  • 818
  • 769
mlo55
  • 6,663
  • 6
  • 33
  • 26

3 Answers3

6

Maybe BeanFactoryPostProcessors will suite your needs? They are run after the whole XML configuration files are read, but before any (other) beans are instantiated.

Grzegorz Oledzki
  • 23,614
  • 16
  • 68
  • 106
5

You can also use the ApplicationListener to receive notification of events like ContextClosedEvent, ContextStartedEvent or ContextStoppedEvent.

More information in the IoC Container chapter.

Vladimir
  • 6,853
  • 2
  • 26
  • 25
  • 1
    I don't think `ApplicationListeners` get notified *before* the context starts up, there doesn't seem to be an event for that. – skaffman Nov 16 '09 at 13:52
  • from the ContextRefreshedEvent JavaDoc: "Event raised when an ApplicationContext gets initialized or refreshed." I'll ckeck tonight if the event is sent *before* the initialization or just after. – Vladimir Nov 16 '09 at 16:11
  • 2
    I'm trying to listen on ContextStartedEvent but it seems that the default lifecycle of a context doesn't explicity call the start method, and so the event doesn't get published. By default lifecycle I simply mean the starting of the entire web server and context (which I expected to fire ContextStartedEvent). Any idea why that is? – Eugen May 09 '11 at 08:24
  • Yes, figured it out in the meantime, but what still puzzles me is why doesn't the context actually get refreshed on initialization. It seems to me that, since ContextRefreshedEvent gets fired several times, it's not something you can rely on, so ContextStartedEvent looks like the only valid alternative. I would expect that to be fired on initialization, and if the only way is to explicitly call: ConfigurableAppicationContext.start() on init, then that call should be there. So I guess the question now becomes - why isn't it? – Eugen Mar 01 '12 at 09:46
2

I just declared my own ContextLoaderListener in order to perform the desired work before loading the Spring context. It suits for web-apps, just declare it before the Spring context listener:

public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        //Perform your stuff here
    }

}
<listener>
    <listener-class>
        com.myCompany.listeners.MyServletContextListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Aritz
  • 30,971
  • 16
  • 136
  • 217