This chapter has covered some of the major issues of session-bean design and implementation. We have seen that:
Stateless session beans are usually the best way to implement business logic when we choose to use EJBs.
We've built on our knowledge of EJB container services by considering:
The EJB container's behavior when an EJB throws an exception. While app exceptions (checked exceptions other than java.rmi.RemoteException) are thrown to the EJB client as in ordinary Java method invocation, without any intervention by the EJB container, system exceptions (java.rmi.RemoteException and unchecked exceptions) cause the EJB container to mark the current transaction for rollback and discard the offending EJB instance. This behavior can be used to simplify error handling, meaning that we don't need to catch fatal runtime exceptions, but can simply leave the EJB container to deal with them. It also means that if we want the current transaction rolled back in the event of an app exception, we must use the setRollbackOnly() method in app code, as the EJB container will take no action.
We've looked at the "Business Methods Interface" pattern, a simple coding technique that can prevent errors by ensuring that an EJB's component interface and implementation class are always in sync. This involves making both component interface and bean implementation class implement a "business methods interface", enabling the compiler to check that method signatures match. We've discussed the following good session bean implementation practices:
Use session beans to delimit transactions.
The following recommendations apply to stateful session beans:
If deploying apps using SFSBs in a clustered environment, read your app server documentation regarding stateful session bean behavior in a cluster closely. Different servers have different behavior that can affect the performance and even the viability of using SFSBs. (For example, is session state replicated after completed transactions, or after each method call? Is there any way of ensuring fine-grained replication, rather than replication of the whole of an SFSB's state every time?)
In the next chapter we'll move on to overall app infrastructure, including some generic EJB superclasses that can simplify development and reduce the likelihood of errors when implementing session beans and message-driven beans.