我有一个在其构造函数中创建对象的单例资源,当应用程序关闭并且服务器终止时,我需要释放这些对象。这怎么在泽西岛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 :(得分:4)
Jersey支持@PreDestroy
生命周期钩子。所以只需使用@PreDestroy
在类中注释一个方法,Jersey将在资源被释放之前调用它
import javax.annotation.PreDestroy;
@Path("/")
@Singleton
public class MyResource {
private Map<String, MyObject> cache;
public MyResource() {
}
@PreDestroy
public void preDestroy() {
// do cleanup
}
}