replacing env-entry with CanDI @Named
Since the JavaEE 6 Web Profile is our main focus for the next few months, I’m going through the JavaEE resource and environment configuration and injection, including the new JavaEE 6 JNDI system. In many cases, though, using CanDI as a registration blackboard is a cleaner, simpler and more type-safe system than using JNDI. Since we believe spending the effort on clean code pays off, the new type-safe capabilities are worth a look.
For example, JavaEE has an <env-entry> tag, which configures literals like Strings and integers. We can replace those with a
MyServlet injecting a config var
import javax.servlet.*;
import java.io.*;
public class MyServlet extends GenericServlet {
@Inject @Named("my-var")
private String _myValue;
public void service(ServletRequest req, ServletResponse res)
throws IOException, ServletException
{
PrintWriter out = res.getWriter();
out.println("custom value: " + _myValue);
}
}
The configuration using CanDI in the resin-web.xml looks like the following:
resin-web.xml configuring the var
<web-app xmlns="http://caucho.com/ns/resin"
xmlns:lang="urn:java:java.lang"
xmlns:ee="urn:java:ee">
<lang:String>
<new>my-value</new>
<ee:Named>my-var</ee:Named>
</lang:String>
</web-app>
The String is instantiated with <lang:String> with a <new> tag for the constructor. The xmlns:lang tells CanDI the package for java.lang.
The old <env-entry> still works (and the old @Resource works too, but you should start migrating to @Inject). For reference, the env-entry looks like the following:
resin-web.xml configuring the var
<web-app xmlns="http://caucho.com/ns/resin">
<env-entry>
<env-entry-name>my-var</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>my-value</env-entry-value>
</env-entry>
</web-app>
