Step 2: Coding the EJB
For this exercise we’ll make a simple SLSB, a Calculator Service, to illustrate how the various pieces all fit together. In fact, we’ll spin up two EJBs—one to show the path of least resistance, and another to expose all business, home, and component views. The full source and deployment instructions for this example are available in Appendix A.
The Contract
This is a great starting point, regardless of whether you’re
building EJBs. The contract, implemented as interfaces in Java, defines
what our service will do, and leaves it up to the
implementation classes to decide how it’s done.
Remember that the same interface cannot be used for both @Local and @Remote, so we’ll make some common base that
may be extended.
public interface CalculatorCommonBusiness
{
/**
* Adds all arguments
*
* @return The sum of all arguments
*/
int add(int... arguments);
}
public interface CalculatorRemoteBusiness extends CalculatorCommonBusiness{}As you can see, we’ve created CalculatorRemoteBusiness by extending the
contract of CalculatorCommonBusiness.
This will come in handy later when we want to add more views exposing
the same method (so we don’t have to rewrite its definition). Our remote
business interface meets the requirement that our session bean will have
at least one view, so we may now write the bean implementation
class.
The Bean Implementation Class
Again we’ll make a common base to contain the logic, and extend it to add our metadata that will define the SLSB.
public class ...