2016-11-18 122 views
2

我有一個單一資源,在其構造函數中創建對象,當應用程序關閉,服務器終止時,我需要釋放這些對象。澤西島2隊是如何完成的?澤西島2資源需要清理

@Path("/") 
@Singleton 
public class MyResource { 
    private Map<String, MyObject> cache; 

    public MyResource() { 
     cache = new ConcurrentHashMap<>(); 
     // at some point I need to remove all entries 
     // from the map and close all MyObject objects there 
     // 
     // the reason is because MyObject might have files open 
     // and I need to close the files 
     // 
     // where can I do that? 
    } 
    ... 
} 
+0

您需要更具體的說,「在某些時候」之前。在/哪一點?容器管理生命週期的重點在於那些點被定義併成爲配置項目。手動調用「釋放/清除這些」方法完全濫用整個想法。 – BadZen

+0

謝謝。我將編輯該問題。 – akonsu

+0

(另外,作爲一般來說,你可能不希望容器管理的生命週期是打開/關閉文件,這不是CDI的原因。) – BadZen

回答

3

Jersey支持@PreDestroy生命週期掛鉤。因此,只要標註在類中的方法與@PreDestroy和澤西將它稱爲資源配置

import javax.annotation.PreDestroy; 

@Path("/") 
@Singleton 
public class MyResource { 
    private Map<String, MyObject> cache; 

    public MyResource() { 
    } 

    @PreDestroy 
    public void preDestroy() { 
     // do cleanup 
    } 
}