Search code examples
javajakarta-eedependency-injectionejbstateless-session-bean

Can I reuse a session bean with another injected classes?


I have an application which consists of message driven bean and a couple of session beans. One of them has a DAO object, that is responsible for accessing database or FTP server.

I need to have two applications. The only difference between them is the instance of DAO class. Can I specify that instance during the deployment phase?

My purpose is to avoid code duplication.


Solution

  • If the DAO is just a POJO, then I would suggest a Class env-entry if you're using EE6 (or a String env-entry if you're not, and then do the Class.forName yourself):

    <env-entry>
      <env-entry-name>daoClass</env-entry-name>
      <env-entry-type>java.lang.Class</env-entry-type>
      <!-- Specify a default, override at deployment time. -->
      <env-entry-value>com.example.project.DefaultDAO</env-entry-value>
    </env-entry>
    
    @Resource(name="daoClass")
    private void setDAOClass(Class<com.example.project.DAO> daoClass) {
        this.dao = daoClass.newInstance();
    }
    

    Alternatively, if your DAO implementation were an EJB, then you could use @EJB injection, and specify the binding name at deployment time.