Search code examples
javajbossdependency-injectionejbstruts

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

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


Solution

  • Try injecting DataSource in the stateless bean with it's JNDI name like

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