java - 如何使用 ejb3 和注释在数据源中注入(inject)依赖项

标签 java jboss dependency-injection ejb struts

@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/

相关文章:

c# - 如何在 .net core 1.0 中获取接口(interface)的所有实例

java - 我是否需要创建工厂的测试版本以进行单元测试?

java - 是否可以使用推送通知来终止使用运行同一应用程序的另一台设备的 Activity

java - HTML ASCII 不区分大小写的 ICU 整理器

java - JBoss 7 将 jar 添加到类路径

java - 访问部署在远程 JBoss AS 上的 JBoss Cache (4.2.2)

java - Jboss 7,如何迁移到infinispan 6

java - JBoss EAP 6.4 -> 7.1 使用 hibernate 4 而不是默认的 hibernate 5

java - Java 中非强制 bean

typescript - 使用注入(inject)对 NestJS Controller 进行单元测试