Dynamic installation of CDI at run time

My blog post will refer to this question. I wrote a year ago.

Although I use a special CDI identifier for my DAO, I wanted to know if there is an approach to dynamically implementing DAO.

The reason I ask is the following. At the moment, I have 3 CDI qualifiers, @HibernateDAO(for the type Hibernate Session injection DAO), @JPADAO(for JPA specific DAOs) and @JDBCDAO(for pure JDBCDAO). This requires that I have to specify it for each specific implementation and after the injection.

@Inject @JPADAO
private CustomerDAO customerDAO;

Is there a better approach that will allow me to add various DAO variations without the need for code changes, compilation and deployment?

I want to introduce MongoDB in the next release of my project, and I was thinking if I could move away from @MongoDBDAOand inject, for example,

@Inject @MongoDBDAO
private CustomerDAO customerDAO;

I know that CDI Injection can allow standard and alternative injection. I want to be able that other developers can use the default implementation override with another subclass and be able to enter it without changing the existing service code.

Some of this effect:

@Inject @DAO
private CustomerDAO customerDAO;

Where @DAOcan be any DAO of any taste (even from a third-party participant) and somehow display @DAOin order to first find an alternative, if not found, the default implementation used.

Thank.

ABOUT! This solution should work strictly with the latest (as of current writing time) Java EE CDI specification. Used technology:

  • RedHat JBoss Wildfly 8.2.0 Final ( Java EE 7).
  • Java 8.
  • API Java EE 7.

, Spring Framework, Spring.

+4
2

. , xml , , .

Java EE.

+3

Daos , .

@Qualifier
@Retention(RUNTIME)
@Target({TYPE,METHOD,FIELD,PARAMETER})
public @interface DAO{

  String value();
}

//Dont worry, CDI allows this quite often than not ;)
public class DAOImpl extends AnnotationLiteral<DAO> implements DAO {

   private final String name;
   public DAOImpl(final String name) {
     this.name = name;
   }

   @Override
   public String value() {
     return name;
   }
}

.

@ApplicationScoped; //Or Whatever
public class MyDAOConsumer {

   @Inject
   @Any
   private Instance<DAOService> daoServices;

   //Just as an example where you can get the dynamic configurations for selecting daos. 
   //Even from property files, or system property.
   @Inject
   private MyDynamicConfigurationService myDanamicConfigurationService;

   public void doSomethingAtRuntime() {
     final String daoToUse = myDanamicConfigurationService.getCurrentConfiguredDaoName();
     final DAO dao = new DAOImpl(daoToUse);

     //Careful here if the DaoService does not exist, you will get UnsatisfiedException
     final DAOService daoService = daoServices.select(dao).get();
     daoService.service();
   }
}

, , dao . .

+2

All Articles