假设我在servlet的init方法中实例化了一个EntityManagerFactory引用:
StartServlet.java:
@WebServlet("/start")
public class StartServlet extends HttpServlet {
private EntityManagerFactory factory;
@Override
public void init() {
factory = Persistence.createEntityManagerFactory("jpa");
getServletContext().setAttribute("factory", factory);
}
}
我也可以在"容器"中看到所有其他servlet。现在,假设我想在另一个servlet中访问此引用,例如:
AnotherServlet.java:
@WebServlet("/another")
public class AnotherServlet extends HttpServlet {
private EntityManagerFactory factory;
@Override
public void init() {
factory = (EntityManagerFactory) getServletContext().getAttribute("factory");
if(factory == null) {
//factory not instantiated from StartServlet, what to do?
}
}
}
如果未从StartServlet.java实例化(未调用init),该怎么办?希望我的问题足够精确!
-Superdids