簡體   English   中英

無法使用@EJB在WAR應用程序中實例化我的對象

[英]Cannot use @EJB to instantiate my object in the WAR application

我正在學習Java EE和JSP。 我已經在NetBeans中創建了一個企業應用程序項目。 我有所有豆都在其中的EJB project和所有Web /客戶端內容都在其中的WAR project 我的問題是,注釋@EJB不會在WAR應用程序中實例化我的Bean。 我可以在EJB應用程序之外使用@EJB嗎?

在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.");
    }
}

在WAR項目中,我有一個文件,我的JSP頁面用於與EJB通訊。 問題是CustomerRemote對象從不實例化。 @EJB注釋似乎不起作用,因為customerRemote始終為null。 但是,當使用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);
//    }
}

@EJB注釋僅在您的類是容器管理的情況下才有效,即EJB,Servlet,JSP ...在您的情況下,您將其放入普通的舊Java對象(PO​​JO)中,因此注入將無法正常工作,就像您經歷過的那樣。 將CustomerProxyBean編寫為無狀態會話Bean,您將看到更改。

另外,如果出於某種原因要避免使用JNDI,則可以使用CDI和@Inject批注來注入EJB並實現期望的行為,即使在POJO中也是如此:

@Inject
private CustomerRemote customerRemote;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM