[英]Jax-rs, Jersey initialize method on startup
我有這樣的代碼:
@Path("/test")
public class MyServlet {
static final Dictionary stuff = new Hashtable();
@GET
public Response response(@QueryParam....)
throws FileNotFoundException {
File directory = new File("test\");
File[] directoryListing = directory.listFiles();
while .......
我想做這個部分我打開文件並在啟動時將它們放在我的字典中,而不是每個請求,我該怎么做? 所以我稍后可以在響應方法中使用字典。
您可以使用靜態初始化塊 ,該塊將在加載類后運行:
public class MyServlet {
static final Dictionary stuff = new Hashtable();
static {
// load files
}
// ...
}
這種技術對於jax-rs / jersey或任何其他框架並不特殊,它是一種語言功能。
如果您希望以后能夠再次調用它,請將代碼移動到某個方法:
public class MyServlet {
static final Dictionary stuff = new Hashtable();
static {
// load at startup
reloadDictionary();
}
// call this whenever you want to reload the files
static void reloadDictionary() {
// reload files
}
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.