EJB references

The EJB container is able to inject references of session beans into an application. It turns out that the CDI container can achieve the same effect. Most of the time, developers can rely on @Inject from CDI to add a dependency, since this annotation is designed to work with managed beans, and the fact is an EJB is a type of managed beans.

Tip

First inject EJB references with @javax.inject.Inject to ensure your application's longevity and if that fails to work because of, say, a circular reference or strange behavior, revert to @javax.ejb.EJB.

CDI managed beans may be injected into an EJB. However, there are restrictions on the scope. A stateless session or singleton EJB normally is injectable into a CDI bean, because the lifetime of EJB generally exceeds the CDI managed bean.

There is one other tried and tested way to get a reference to an EJB, and that is to use the JNDI. But going down this track leads you to dependency lookup and far away from dependency injection.

This is the JNDI way:

public void someWorkMustBeDone() {
    PostTradeProcessor processor = null;
    try {
        Context context = (Context)
            new InitialContext();
        processor = (PostTradeProcessor)
            context.lookup(
                "java:comp/PostTradeProcessor");
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }

    hangTen(processor); // ...
}

This code is only useful in tight corners of development.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.135.249