views:

97

answers:

1

I have a Wicket Web Application running in Tomcat. The application uses Spring (via org.springframework.web.context.ContextLoaderListener) to initialise the application. This is all well and good for start up, but what I would also like is to receive some sort of notification that the Context is being destroyed so that I can shutdown spawned threads. Is there a way of receiving such a notification? I've included excerpts from my application to aid your understanding of my question.

web.xml extract

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/mysite/web/spring/applicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

Spring applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
    "http://www.springframework.org/dtd/spring-beans-2.0.dtd"&gt;

<beans>
    <bean id="MyWebService" class="com.mysite.web.MyWebApp">
    </bean>
</beans>

MyWebApp.java extract

public class MyWebApp extends org.apache.wicket.protocol.http.WebApplication {
    private MyWebServiceServiceAPI webservice =
       MyWebServiceAppImpl.getMyWebService();

    public MyWebServiceWebApp() {
    }

    @Override
    public void init() {
        super.init();
        webservice.start();
    }
}

MyWebServiceAppImpl.java extract

    public class MyWebServiceAppImpl  extends ServiceImpl
        implements MyWebServiceServiceAPI  {
        // The ServiceImpl implements the Callable<T> interface

    private static MyWebServiceServiceAPI instance;
    private List<Future<ServiceImpl>> results =
        new ArrayList<Future<ServiceImpl>>();
    private ExecutorService pool = Executors.newCachedThreadPool();


    private MyWebServiceAppImpl() {
        super(.....);
    }

    public synchronized static MyWebServiceServiceAPI getMyWebService() {
        if (instance == null) {
            instance = new MyWebServiceAppImpl();
            instance.start();
        }
        return instance;
    }

@Override
public synchronized void start() {

    if (!started()) {
        pool.submit(this);
        super.start();
    }
}
+3  A: 

Yes, you can implement your own ContextListener.

package myapp;

public class MyContextListener implements ServletContextListener {



    public void contextInitialized(ServletContextEvent arg0) {
        //called when context is started
    }


    public void contextDestroyed(ServletContextEvent arg0) {
      //called context destroyed
    }   
}

You need to add that listener to your web.xml

 <listener>
    <listener-class>myapp.MyContextListener</listener-class>
 </listener>
nos
Hi Thanks for the answer. Are you saying that in addition to the Spring ContextListener I can specify my own, and that both can co-exist?
leftbrainlogic
Yes, you can have as many context listeners as you want.
nos