我的申请完成后,我想关闭春天的背景
相关代码有ApplicationContext
引用,但我找不到close
方法。
答案 0 :(得分:132)
将您的ApplicationContext
转发给定义ConfigurableApplicationContext
方法的close()
:
((ConfigurableApplicationContext)appCtx).close();
答案 1 :(得分:34)
您需要向JVM注册一个关闭钩子,如下所示:
((AbstractApplicationContext)appCtx).registerShutdownHook();
有关详细信息,请参阅:Spring Manual: 3.6.1.6 Shutting down the Spring IoC container gracefully in non-web applications
答案 2 :(得分:11)
如果你初始化下面的上下文
ApplicationContext context = new ClassPathXmlApplicationContext(beansXML);
像这些一样清理上下文
((ClassPathXmlApplicationContext) context).close();
答案 3 :(得分:10)
如果Java SE 7及更高版本,请不要关闭,请使用try-with-resources确保在语句结束时关闭每个资源。
try(final AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"classpath*:META-INF/spring/*.xml" }))
{
//write your code
}
答案 4 :(得分:1)
关闭ApplicationContext
对象
ApplicationContext
对象转换为ConfigurableApplicationContext
对象。示例:
ApplicationContext context = new ClassPathXmlApplicationContext("mybeans.xml");
((ConfigurableApplicationContext)context ).close();
答案 5 :(得分:0)
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("SpringCnf.xml");
Resturant rstro1=(Resturant)context.getBean("resturantBean");
rstro1.setWelcome("hello user");
rstro1.welcomeNote();
((ClassPathXmlApplicationContext) context).close();