Java Reference
In-Depth Information
As useful as @Resource is, it can't solve every problem. There are some cases where you
must programmatically look up resources from a JNDI registry yourself. We'll talk about
some of these cases next, as well as show you how to perform programmatic lookups.
Field injection versus setter injection
In the vast majority of cases, resources and EJBs are injected into fields. In DI parlance this
is called field injection. But besides field injection, EJB also supports setter injection (on
the other hand, EJB doesn't support constructor injection, whereas CDI does). To see how
it works, transform the data source example to use setter injection:
@Stateless
public class DefaultBidService implements BidService {
...
private DataSource dataSource;
...
@Resource(lookup="java:global/jdbc/ActionBazaarDB")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
Just as in field injection, the container inspects the @Resource annotation on the
setDataSource method before a bean instance becomes usable, looks up the data
source from JNDI using the lookup element value, and calls the setDataSource
method using the retrieved data source as the parameter.
Whether or not to use setter injection is largely a matter of taste. Although setter injection
might seem like a little more work, it provides a couple of distinct advantages. First, it's
easier to unit test by invoking the public setter method from a testing framework like JUnit.
Second, it's easier to put initialization code in the setter if you need it.
In this case, you can open a database connection in the setDataSource method as soon
as injection happens, as follows:
private Connection connection;
...
@Resource(lookup="java:global/jdbc/ActionBazaarDB")
public void setDataSource(DataSource dataSource) {
this.connection = dataSource.getConnection();
}
Search WWH ::




Custom Search