Discuss / Java / 为什么最后需要close context呢

为什么最后需要close context呢

Topic source

我理解的close context可以释放资源,但是这个情况下应该是main跑完就自动close释放了?还是说作为一个好习惯每次都close一下?

而且为什么要转成ConfigurableApplicationContext再去close

((ConfigurableApplicationContext) context).close();

谢谢

何小狗____

#2 Created at ... [Delete] [Delete and Lock User]

这是stack overflow上的回答,我觉得很有道理:

ApplicationContext: This the most powerful Container, compare to Bean-factory (Core container).

ConfigurableApplicationContext: One of the implementation of the ApplicationContext container. This container is used for Event Handling propose.

If you implement the following methods and your Bean Class extends the ApplicationListner interface, then when these methods are executed, your Bean will get related Events。

void refresh()
void close();
void shutdown();

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

close()的时候,所有@PreDestroy方法会自动执行

可以不close(),但是这些@PreDestroy方法就没机会执行了

run()返回的类型是ConfigurableApplicationContext,继承关系:

ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable

你想调用close(),得看这个方法定义在哪一层。如果转型为ApplicationContext,并没有close()方法


  • 1

Reply