Spring在非web应用中关闭IoC容器 (registerShutdownHook)

时间:2014-12-18 12:07:22   收藏:0   阅读:238

        在基于web的ApplicationContext实现中,已有相应的实现来处理关闭web应用时恰当地关闭Spring IoC容器。

       但,如果你正在一个非web应用的环境下使用Spring的IoC容器,如dubbo服务,你想让容器优雅的关闭,并调用singleton的bean相应destory回调方法,你需要在JVM里注册一个“关闭钩子”(shutdown hook)。这一点非常容易做到,并且将会确保你的Spring IoC容器被恰当关闭,以及所有由单例持有的资源都会被释放。

      为了注册“关闭钩子”,你只需要简单地调用在org.springframework.context.support.AbstractApplicationContext实现中的registerShutdownHook()方法即可。


import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public final class StartServer {

    public static void main(final String[] args) throws Exception {
        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(new String []{"spring.xml"});

        // add a shutdown hook for the above context... 
        ctx.registerShutdownHook();
        ctx.start();
        // app runs here...
	    // main method exits, hook is called prior to the app shutting down...
    }
}



 


评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!