开发者

Can webapplication be notified that the web container (ex. Tomcat) is reloading, unloading or shutting down

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.springframewo开发者_如何学Pythonrk.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">

<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();
    }
}


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜