Bean Adapters

One of the most awkward aspects of the EJB bean interface types is that, in some cases, the callback methods are never used or are not relevant to the bean at all. A simple container-managed entity bean might have empty implementations for its ejbLoad(), ejbStore(), ejbActivate(), ejbPassivate(), or even its setEntity-Context() methods. Stateless session beans provide an even better example of unnecessary callback methods: they must implement the ejbActivate() and ejbPassivate() methods even though these methods are never invoked!

To simplify the appearance of the bean class definitions, we can introduce adapter classes that hide callback methods that are never used or have only minimal implementations. Here is an adapter for the entity bean that provides empty implementations of all the EntityBean methods:

public class EntityAdapter implements javax.ejb.EntityBean {
    public EntityContext ejbContext;

    public void ejbActivate() {}
    public void ejbPassivate() {}
    public void ejbLoad() {}
    public void ejbStore() {}
    public void ejbRemove() {}

    public void setEntityContext(EntityContext ctx) {
        ejbContext = ctx;
    }
    public void unsetEntityContext() {
        ejbContext = null;
    }
    public EntityContext getEJBContext() {
        return ejbContext;
    }
}

We took care of capturing the EntityContext for use by the subclass. We can do this because most entity beans implement the context methods in exactly this way. We simply leverage the adapter class to manage this logic for our subclasses.

If a callback method is deemed necessary, we can just override it with a method in the bean class.

We can create a similar Adapter class for stateless session beans:

public class SessionAdapter implements javax.ejb.SessionBean {
    public SessionContext ejbContext;

    public void ejbActivate() {}
    public void ejbPassivate() {}
    public void ejbRemove() {}

    public void setSessionContext(SessionContext ctx) {
        ejbContext = ctx;
    }
    public SessionContext getEJBContext() {
        return ejbContext;
    }
}

Do not use these adapter classes when you need to override more than one or two of their methods. If you need to implement several of the callback methods, your code will be clearer if you do not use the adapter class. The adapter class also impacts the inheritance hierarchy of the bean class. If you need to implement a different superclass later, one that captures business logic, you will have to modify the class inheritance.

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

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