在基于web的ApplicationContext实现中,已有相应的实现来处理关闭web应用时恰当地关闭Spring IoC容器。但,如果你正在一个非web应用的环境下使用Spring的IoC容器,如dubbo服务,你想让容器优雅的关闭,并调用singleton的bean相应destory回调方法,你需要在JVM里注册一个“关闭钩子”(shutdown hook)。这一点非常容易做到,并且将会确保你的Spring IoC容器被恰当关闭,以及所有由单例持有的资源都会被释放。
packagecom.hcm.dubbo.service;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassDubboServiceStart {
privatestaticfinal Logger LOG = LoggerFactory.getLogger(DubboServiceStart.class);
publicstaticfinal String DUBBO_PROVIDER = "spring/dubbo-provider.xml";
publicstaticvoid init() {
LOG.info("开始启动dubo服务,载入的配置服务提供文件为["+ DUBBO_PROVIDER + "]");
ClassPathXmlApplicationContext context = newClassPathXmlApplicationContext(newString[] { DUBBO_PROVIDER });
context.registerShutdownHook();
context.start();
LOG.info("dubbo启动服务完毕,请查看日志");
String[] names = context.getBeanDefinitionNames();
System.out.print("Beans:");
for(String string : names) {
System.out.print(string + ",");
}
System.out.println();
}
publicstaticvoid main(String[] args) throwsInterruptedException {
DubboServiceStart.init();
while(true) {
try{
Thread.currentThread();
Thread.sleep(3L);
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
packagecom.hcm.dubbo.service;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassDubboServiceStart {
privatestaticfinal Logger LOG = LoggerFactory.getLogger(DubboServiceStart.class);
publicstaticfinal String DUBBO_PROVIDER = "spring/dubbo-provider.xml";
publicstaticvoid init() {
LOG.info("开始启动dubo服务,载入的配置服务提供文件为["+ DUBBO_PROVIDER + "]");
ClassPathXmlApplicationContext context = newClassPathXmlApplicationContext(newString[] { DUBBO_PROVIDER });
context.registerShutdownHook();
context.start();
LOG.info("dubbo启动服务完毕,请查看日志");
String[] names = context.getBeanDefinitionNames();
System.out.print("Beans:");
for(String string : names) {
System.out.print(string + ",");
}
System.out.println();
}
publicstaticvoid main(String[] args) throwsInterruptedException {
DubboServiceStart.init();
while(true) {
try{
Thread.currentThread();
Thread.sleep(3L);
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
转载自:http://my.oschina.net/huangcongmin12/blog/357538