Java Reference
In-Depth Information
Context ctx = ec.getContext();
BidServiceLocal bsl = ctx.lookup("java:global/bidservice/BidServiceEjb");
Of course, for EJBs managed by the embedded container, use the
@EJB
and
@Resource
annotations and have the embedded container perform the DI.
Closing
When your application is finished with the embedded container, use
ec.close()
to
close it and release its resources. Closing the embedded container doesn't mean the SE ap-
plication is closing as well. The SE application may decide to close the embedded container
for any number of reasons. Once closed, the standalone application is free to bootstrap a
new one if needed.
The embedded container has also been updated to implement the
AutoCloseable
inter-
face. Because of this, you can use the
try-with-resource
statement and have the em-
bedded container closed for you automatically. Using the
try-with-resource
state-
ment looks like this:
try (EJBContainer ec = EJBContainer.createEJBContainer())
{
// do what you want with the embedded container
} catch (Throwable t) {
t.printStackTrace();
}
5.2.13. Using EJB injection and lookup effectively
Using the
@EJB
annotation to inject bean instances into your code is the quickest, easiest,
and safest way for you to wire your application together. For the majority of cases, the EJB
container will be able to determine what bean to create and inject by either the bean's inter-
face or the bean class itself. But a lookup becomes necessary for
@EJB
injection if multiple
beans implement the same interface and you're referencing the bean by that interface. CDI
injection has a more elegant solution, which we'll look at next.