代码场景:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ultimate.cloudutil.qcloud.QCloudUtil;
import com.ultimate.util.PropertyConfig;
public class SpringAppContextTest {
public static void main(String[] args) {
QCloudUtil util = new QCloudUtil(
2 * 60 * 1000,
PropertyConfig.getProperty(PropertyConfig.CLOUD, "region"),
PropertyConfig.getProperty(PropertyConfig.CLOUD, "appId"),
PropertyConfig.getProperty(PropertyConfig.CLOUD, "secretId"),
PropertyConfig.getProperty(PropertyConfig.CLOUD, "secretKey"));
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext.xml");
// System.exit(0);
util.shutdown();//这里创建了2个对象,真正没关闭的不是ApplicationContext,而是util!!!
}
}
本地执行,加载ApplicationContext,
这里使用了applicationContext后,后面执行完具体逻辑后,程序不退出
问题场景:
这里我是main为入口,手动创建了spring ApplicationContext对象,jvm启动了一个非守护线程,程序运行完后,跳到Thread类的exit方法,然而并未退出
为什么没有自动关闭呢?
applicationContext随着程序的退出已经结束了,代码中还有创建QCloudUtil对象,是这个对象需要调用util.shutdown();方法关闭。
借此时遇到这个问题,再延申下如何关闭?
方法一:在程序内主动调用System.exit(0);强制关闭
附:
在test junit 中注解的方式,是会自动关闭的,如下:
package com.ultimate.service.finance.impl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.ultimate.dao.DaoSupport;
import com.ultimate.domain.finance.DetailBySongsDTO;
import com.ultimate.domain.finance.DetailBySongsVO;
/**
* test
*/
@SuppressWarnings("all")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/ApplicationContext-mvc.xml","classpath:spring/ApplicationContext.xml"})
public class DetailBySongsServiceImplTest {
@Resource(name = "daoSupport")
private DaoSupport dao;
@Test
public void testSearchSongsDetail() throws Exception {
DetailBySongsDTO det = new DetailBySongsDTO();
//det.setSpid("133");
det.setDatetimes("2017-09-2017-12");
List<DetailBySongsVO> songsList = new ArrayList<DetailBySongsVO>();
songsList = (List<DetailBySongsVO>) dao
.findForList("DetailBySongsMapper.querySongsDetail", det);
for (DetailBySongsVO fin : songsList) {
System.out.println(fin.getDate());
}
System.out.println("-=-=-=--=================-=-=-=--==-=-=-=-=-=");
}
}