springmodel-view-controllerapplicationcontext

How to add a hook to the application context initialization event?


For a regular Servlet, I guess you could declare a context listener, but for Spring MVC would Spring make this any easier?

Furthermore, if I define a context listener and then would need to access the beans defined in my servlet.xml or applicationContext.xml, how would I get access to them?


Solution

  • Spring has some standard events which you can handle.

    To do that, you must create and register a bean that implements the ApplicationListener interface, something like this:

    package test.pack.age;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationEvent;
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    
    public class ApplicationListenerBean implements ApplicationListener {
    
        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            if (event instanceof ContextRefreshedEvent) {
                ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
                // now you can do applicationContext.getBean(...)
                // ...
            }
        }
    }
    

    You then register this bean within your servlet.xml or applicationContext.xml file:

    <bean id="eventListenerBean" class="test.pack.age.ApplicationListenerBean" />
    

    and Spring will notify it when the application context is initialized.

    In Spring 3 (if you are using this version), the ApplicationListener class is generic and you can declare the event type that you are interested in, and the event will be filtered accordingly. You can simplify a bit your bean code like this:

    public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            ApplicationContext applicationContext = event.getApplicationContext();
            // now you can do applicationContext.getBean(...)
            // ...
        }
    }