Why CDI Won’t Replace Spring
Join the DZone community and get the full member experience.Join For Free
CDI is part of JavaEE 6 and that’s a great move forward. Now, there’s a standard telling vendors and developers how to do DI. It can be refined, but it’s here nonetheless. Norms and standards are IMHO a good thing in any industry. Yet, I don’t subscribe to some people’s points of view that this means the end of Spring. There are multiple DI frameworks around here and Spring is number one.
Why is that? Because it was the first? It wasn’t (look at Avalon). My opinion is that it’s because Spring’s DI mechanism is only a part of its features. Sure, it’s great but Guice and now CDI offers the same. What really sets Spring apart is its integration of JavaEE API and of the best components available on the market that are built on top of DI.
A good example of this added value is JMS: if you ever tried to post to a queue before, you know what I mean. This is the kind of code you would need to write:
Context context = new InitialContext();
QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) context.lookup("myQConnectionFactory");
Queue queue = (Queue) context.lookup("myQueue");
QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
QueueSender queueSender = queueSession.createSender(queue);
TextMessage message = queueSession.createTextMessage();
Now in Spring, this is configured like so:
<jee:jndi-lookup id="queueConnectionFactory" jndi-name="myQConnectionFactory" />
<jee:jndi-lookup id="q" jndi-name="myQueue" />
<property name="connectionFactory" ref="jmsQueueConnectionFactory" />
<property name="defaultDestination" ref="q" />
I don’t care it’s shorter event though it is (but it lacks the code to send the text). I don’t care it’s XML either. My real interest is that I code less: less errors, less bugs, less code to test. I don’t have to write the boilerplate code because it’s taken care of by Spring. Sure, I have to configure, but it’s a breeze compared to the code.
This is true for JMS, but equally for Hibernate, EclipseLink, iBatis, JPA, JDO, Quartz, Groovy, JRuby, JUnit, TestNG, JasperReports, Velocity, FreeMarker, JSF, what have you that is the best of breed (or at least on top) of its category. Morevover, if nothing exists to fit the bill, Spring provides it: look at Spring Batch for a very good example of a framework that handles the boring and repetitive code and let you focus on your business code.
Do Guice or other frameworks have such integration features included in them? No, they are pure, “untainted” DI frameworks. As such, they can easily be replaced by CDI, Spring not so much.
Opinions expressed by DZone contributors are their own.