我使用 Jersey 将一些统计数据公开为 REST 服务。 我正在使用 Weblogic
但是每次当我执行一个获取统计的请求时 System.out.println("In PostConstruct");被称为。
即使我在路径旁边注释@Stateless,也会发生这种情况。
这就像在每个请求(请求范围)上实例化 StorageService 一样
有没有办法只调用一次初始化并避免在每次请求时都创建 StorageService?
@Path("/statistics")
public class StorageService {
@Context
private ServletContext application;
StatisticsStorage statisticsStorage;
@PostConstruct
public void initialize() {
System.out.println("In PostConstruct");
try {
statisticsStorage = new StatisticsStorage((String) application.getAttribute(AppProperties.PropKey.STATS_OUTPUT_PATH_PROP.toString()));
} catch (Exception sqle) {
sqle.printStackTrace();
}
}
@GET
// The Java method will produce content identified by the MIME Media type "text/plain"
@Produces({MediaType.APPLICATION_JSON})
public Domain getSnapshot() {}
谢谢
最佳答案
Jersey 会根据每个请求实例化该类。请注意,您可以使用 @Context 注释的大多数内容都是特定于请求的。最好的办法是将 StatisticsStorage 字段设置为静态并在第一次请求时对其进行初始化(需要同步)。也许是这样的:
public StorageService(@Context ServletContext application) {
super(servletConfig, request, httpServletRequest, uriInfo, httpHeaders, securityContext);
synchronized (this.getClass()) {
if (statisticsStorage == null) {
try {
statisticsStorage = new StatisticsStorage((String) application.getAttribute(AppProperties.PropKey.STATS_OUTPUT_PATH_PROP.toString()));
} catch (Exception sqle) {
sqle.printStackTrace();
}
}
}
}
static StatisticsStorage statisticsStorage;
关于java - @PostConstruct 与 Jersey 1.17、Weblogic 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27317608/