CanDI for database integration
In the large projects that most of us work with, it’s not feasible to rewrite the entire project around a new technology like CDI, even though a redesigned project around CDI would be a better crafted solution. But what you can do is add CDI incrementally and improve your project’s quality piece by piece as time goes on. For example, in an agile-style short release cycle, you’d want to break up the CDI migration task into something small enough to fit in your 2-3 week cycle.
If you’re using JDBC directly, the quickest benefit for CDI is replacing your current DataSource injection (or JNDI) with CDI, since Resin’s database configuration integrates with the CDI injection.
First, you need to decide on the qualifiers for the database, a tiny set of adjectives describing each DataSource that you use by its functionality. If you have only one DataSource, you can use the builtin @Default qualifier. If you have two or more, you’ll create your own qualifiers. For example, you might have a @Login database separate from your @Account database. When you inject them, it’ll look like:
import javax.sql.DataSource;
public class MyServlet extends GenericServlet {
@Inject @Account DataSource _accountDataSource;
…
}
The @Account qualifier is simple boilerplate code, which looks like the following:
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Target({TYPE,FIELD,METHOD,PARAMETER})
@Retention(RUNTIME)
@Qualifier
public @interface Account {
}
We’re almost done. The only thing left is to modify the <database> configuration in the resin-web.xml to attach the @Account qualifier to the <database>.
xmlns:mypkg=”urn:java:com.mycom.mypkg”>
<database jndi-name=”jdbc/account”>
<mypkg:Account/>
<driver type=”com.mysql.jdbc.Driver”>
<url>jdbc:mysql://localhost:3306/account</url>
<user>myuser</user>
<password>mypassword</password>
</driver>
</database>
</web-app>
The <mypkg:Account/> adds the @Account qualifier to the Resin <database> configuration, making it available for the CanDI injection in your code.
So with a simple change to your code and configuration, your DataSource injection is now type-safe, validated at application startup time by Resin, and self-documenting the source of the injection at the injection point with @Inject @Account DataSource.
