简体   繁体   English

如何使用ejb3和注释在数据源中注入依赖项

[英]How to inject dependency in datasource with ejb3 and annotations

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

in the Action, works with lookup, problem occurred in SessionBean 在Action中,可以使用查找, 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) {}
                }

        }

    }

I'm trying inject this. 我正在尝试注入。 In my datasource never injected, what I put in Resource ? 在我从未注入的数据源中,我在Resource中添加了什么?

Try injecting DataSource in the stateless bean with it's JNDI name like 尝试使用JNDI名称将DataSource注入无状态Bean中

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

You also need to inject this stateless into the client with @EJB or @Inject annotation or also with JNDI lookup, these are the only ways how can you be sure that container will correctly inject all the dependencies (the DataSource in your case) into the bean. 您还需要使用@EJB@Inject批注或JNDI查找将这种无状态注入客户端,这是确保容器将所有依赖项(在您的情况下为DataSource )正确注入的唯一方法。豆角,扁豆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM