[英]Statefull Ejb and Session scoped Managed bean Inject null pointer
有人可以幫我嗎? 有一個SessionScoped托管Bean,一個無狀態Ejb和一個其他有狀態Ejb。
MB中的serachCustomer()方法調用注入的DaoEjbTst searcCustomer()方法,該方法返回BCus實體對象的實例。 我將另一個有狀態的CustomerSession EJB注入到Stateless DaoEjbTst Ejb中,當在DaoEjbTst EJB中准備好實體實例時,我調用CustomerSession EJB setActualCustomer方法,並為該方法提供實體實例作為參數,然后嘗試存儲它...然后當我嘗試在ManagedBean中使用另一個showTstDate()方法獲取此“存儲的”實體實例時,將引發NullPointer異常。而且我不知道為什么。為什么在有狀態ejb中不存在公共BCus實際客戶參數? 我試圖在有狀態Ejb中創建@PreDestroy和@PrePassivate和@Remove方法,以檢查容器是否將其刪除,但此方法從未由容器調用。。因此,我確定ejb存在。 't訪問它:(我不使用接口。
這是我的托管bean:
@EJB
private DaoEjbTst daoEjb;
@EJB
private CustomerSession customerSession;
public void serachCustomer() throws IOException {
FacesContext ctx = FacesContext.getCurrentInstance();
if (daoEjb.searcCustomer(custNo)) {
ctx.getExternalContext().redirect("showCustomer.xhtml");
}
else {
ctx.getExternalContext().redirect("test.xhtml");
}
}
public String showTstDate() {
log.info("MB EJB EXIST: " + customerSession);
return "Test: " + customerSession.getActualCustomer().getCustName();
}
這是我的DaoEjbTst:
@Stateless
public class DaoEjbTst {
private final Logger log = Logger.getLogger("DaoEjbTst.class");
@EJB
private CustomerSession customerSession;
public CustomerSession getCustomerSession() {
return customerSession;
}
public void setCustomerSession(CustomerSession customerSession) {
this.customerSession = customerSession;
}
@PersistenceContext(unitName = "TestAppPU")
private EntityManager em;
public boolean searcCustomer(String custNo) {
try {
BCus cus = (BCus) em.createNamedQuery("BCus.findByCustomerno").setParameter("customerno", custNo).getSingleResult();
log.info("DAOEJB: " + cus);
customerSession.setActualCustomer(cus);
return true;
}
catch (NoResultException e) {
log.info(e.getMessage());
return false;
}
}
這是我的CustomerSession EJb:
@Stateful
public class CustomerSession {
public BCus actualCustomer;
private final Logger log = Logger.getLogger("CustomerSession.class");
public BCus getActualCustomer() {
return actualCustomer;
}
public void setActualCustomer(BCus actualCustomer) {
this.actualCustomer = actualCustomer;
checkTst();
}
public CustomerSession() {
}
}
我認為,注入ManagedBean的CustomerSession bean與注入DaoEjbTst的bean實例不同。 因此,調用:
customerSession.getActualCustomer()
因為未為此特定的bean實例設置ActualCustomer字段,所以ManagedBean中的ins只是返回null。 它是在DaoEjbTest中設置的,但這是CustomerSession的不同實例。 所以:
DaoEjbTst.getCustomerSession().equals(ManagedBean.getCustomerSession())
給出錯誤。
當您查看EJB 3.1規范(第3.4.7.1節)時,您會看到:
有狀態會話對象具有唯一的標識,該標識在創建對象時由容器分配。
基本上,您應該使用在DAO的searcCustomer()方法中找到的值,為ManagedBean中的CustomerSession bean實例設置setActualCustomer。 但是,將有狀態會話Bean存儲在無狀態Bean中是一個非常糟糕的主意,我建議您重新考慮您的體系結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.