泽西2资源需要清理

时间:2016-11-18 04:32:46

标签: java jersey-2.0

我有一个在其构造函数中创建对象的单例资源,当应用程序关闭并且服务器终止时,我需要释放这些对象。这怎么在泽西岛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?
    }
    ...
}

1 个答案:

答案 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
    }
}