2014-02-12 31 views
1
@Override 
protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { 

    DataSource dataSource = (DataSource) new InitialContext().lookup("java:jboss/STRUTS-DS"); 

    dataSource.getConnection(); 

    SessionBean sessionBean = new SessionBean(); 
    sessionBean.testConnection(); 
    return mapping.findForward("list"); 
} 
在行動

,可與查詢,發生在SessionBean如何注入依賴於數據源與EJB3和註釋

@Stateless 
    public class SessionBean { 

     @PersistenceContext(???) 
     EntityManager entityManager; 

     @Resource(???) 
     DataSource dataSource; 

     public void testConnection() { 
       PreparedStatement preparedStatement = null; 
       Connection connection = null; 

       try { 
         connection = dataSource.getConnection(); 
         preparedStatement = connection.prepareStatement("drop table test"); 
         preparedStatement.execute(); 

         preparedStatement = connection.prepareStatement("CREATE TABLE example (id INT,data VARCHAR(100));"); 
         preparedStatement.execute(); 

         System.out.println("Done"); 

       } catch (SQLException sqlE) { 
         throw new EJBException(sqlE); 
       } finally { 
         try { 
           if (preparedStatement != null) { 
             preparedStatement.close(); 
           } 
         } catch (Exception e) {} 
         try { 
           if (connection != null) { 
             connection.close(); 
           } 
         } catch (Exception e) {} 
       } 

     } 

    } 

我試圖注入了這個問題。 在我的數據源從未注入,我放在資源?

遺憾的是:Lorem存有悲坐阿梅德,consectetuer adipiscing ELIT,sed的直徑nonummy NIBH euismod tincidunt UT laoreet dolore麥格納aliquam ERAT volutpat。

+0

如果你正在實例化你的'SessionBean',你不能使用任何注入 - 爲此,它必須由EJB容器創建。 – andersschuller

+0

你說得對,問題是我不能使用註釋EJB和Inject in Action [錯誤:註釋EJB不允許用於此位置] – arr90rj

回答

0

嘗試在它的無狀態的bean注入DataSource的JNDI名稱,比如

@Resource(lookup = "java:jboss/STRUTS-DS") 
private DataSource dataSource; 

您還需要使用JNDI查找注入這個無國籍到客戶端@EJB@Inject註解或還,這些都是唯一途徑你怎麼能確定容器將正確地注入所有依賴項(在你的情況下爲DataSource)到bean中。

+0

我無法在Action中使用註釋'@ EJB'和'@Inject',並且@andersschuller說不能實例化我的'SessionBean'並使用依賴注入。我需要另一個解決方案。 – arr90rj