CDI migration: module inside a framework
For people who want to use CDI, the most difficult problem is a large legacy of existing code. Rewriting an entire codebase is not possible (and not wise) and evolutionary change has proven itself as more effective and manageable, even if it doesn’t sounds as impressive as a full rewrite. So the trick to migrating to CDI is finding ways to change one piece of the project.
If you have a service-oriented architecture (when used a legitimate design pattern, not the web services buzzword), you can explore CDI with one service, and transition between the styles using JNDI to enter the CDI environment. A module inside a framework also fits this pattern, like an application within wicket. Essentially, any case where the framework is non-CDI but you want to write a module using CDI. The key is getting access to CDI’s programmatic interface BeanManager using JNDI.
The code to load a CDI-enabled service inside a framework with JNDI is boilerplate. You’ll want to put it in a utility class. The class you load with the utility will be your main service entry, or a root node in a component graph. You’ll use the code like the following, where “myBean” is a fully CDI-enabled bean with injection, interception, XA annotations, events, etc:
MyCdiBean myBean = candi.getReference(MyCdiBean.class);
The utility class is boilerplate code. The BeanManager code is an SPI interface and it’s a bit more verbose than API code, but the added flexibility for framework integration is worth the added complexity. This integration code is only needed at the boundary of CDI and inside a foreign web framework; it’s not needed within a CDI module.
import javax.naming.*;
import javax.enterprise.context.spi.*;
import javax.enterprise.inject.spi.*;
import java.util.*;
public class CandiUtil {
private BeanManager _cdiManager;
public <T> T getReference(Class<T> beanClass)
{
BeanManager cdiManager = getBeanManager();
Bean<T> bean = (Bean<T>) cdiManager.resolve(cdi.getBeans(beanClass));
CreationalContext<T> env = cdiManager.createCreationalContext(bean);
return cdiManager.getReference(bean, beanClass, env);
}
private BeanManger getBeanManager()
{
if (_cdiManager == null) {
try {
InitialContext ic = new InitialContext();
_cdiManager = (BeanManager) ic.lookup("java:comp/BeanManager");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return _cdiManager;
}
}
Once you have this utility code, you can migrate your service to CDI without asking permission from the rest of the framework. Use this CandiUtil.getReference method to create your main service instance once, and all of its dependencies will be CDI-enabled. In an agile-style short release cycle, you can easily add this CandiUtil in one cycle and migrate the service itself bit-by-bit in following cycles.
