我正在學習Java EE和JSP。我在NetBeans中創建了一個Enterprise Application項目。 我有EJB project
所有的豆和WAR project
所有的網絡/客戶端的東西。 我的問題是註釋@EJB
沒有在WAR應用程序中實例化我的Bean。我可以在EJB應用程序外部使用@EJB
嗎?無法使用@EJB在WAR應用程序中實例化我的對象
在EJB項目中,我有這些文件:
CustomerRemote.java
@Remote
public interface CustomerRemote {
public Customer createCustomer();
public Customer getCustomer(int customerId);
public void removeCustomer();
}
CustomerBean.java
@Stateless
public class CustomerBean implements CustomerRemote {
@PersistenceContext(unitName="testPU")
private EntityManager entityManager;
@Override
public Customer createCustomer() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void removeCustomer() {
}
@Override
public Customer getCustomer(int customerId) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
在戰爭中的項目,我有一個文件,我的JSP頁面使用與EJB的東西進行交流。問題是CustomerRemote對象從未實例化。 @EJB註釋似乎不起作用,因爲customerRemote
總是爲空。但是當用lookup
方法實例化它時,它可以工作!那麼@EJB
爲什麼不工作?
public class CustomerProxyBean {
@EJB
private CustomerRemote customerRemote;
public CustomerProxyBean() {
// try {
// InitialContext context = new InitialContext();
// customerRemote = (CustomerRemote)context.lookup("java:app/SimpleShop-ejb/CustomerBean");
//
// } catch (NamingException ex) {
// Logger.getLogger(CustomerProxyBean.class.getName()).log(Level.SEVERE, null, ex);
// }
}
所以'CustomerProxyBean'不是容器管理的?我試圖在類聲明上面放置@ Stateless註解,但它沒有幫助。 – Rox
'CustomerProxyBean'不是容器管理的,因爲它沒有實現任何接口,也沒有正確註釋。您正在使用哪個Java EE版本?在Java EE 6中,您可以不使用任何接口,但是除了'@ Stateless'之外,還必須添加'@ LocalBean'註釋。否則,像在'CustomerBean' bean中一樣實現Local或Remote接口。 –
編輯:即使沒有'@ LocalBean'註釋(您在兩種情況下都沒有界面視圖)都可以使用,但關鍵是您正在使用的Java EE和EJB版本。對於Java EE 6/EJB 3.1,「@ Stateless」應該足以使您的類成爲無狀態會話Bean,否則您還必須實現本地或遠程接口。 –