@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");
}
在Action中,使用lookup,问题发生在SessionBean
@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) {}
}
}
}
我正在尝试注入(inject)这个。 在我从未注入(inject)的数据源中,我在 Resource 中放了什么?
最佳答案
尝试在无状态 bean 中注入(inject) DataSource
并使用它的 JNDI 名称
@Resource(lookup = "java:jboss/STRUTS-DS")
private DataSource dataSource;
您还需要使用 @EJB
或 @Inject
注释或 JNDI 查找将此无状态注入(inject)客户端,这些是您如何确定的唯一方法该容器将正确地将所有依赖项(在您的情况下为 DataSource
)注入(inject)到 bean 中。
关于java - 如何使用 ejb3 和注释在数据源中注入(inject)依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21738420/