ServiceFacade In Greater Detail - and Some EJB 3 Code 📎
What is a ServiceFacade exactly? Yesterday we covered the difference between a ServiceFacade and a Service. ServiceFacade represents the boundary or an external component contract. Some aspects can be already derived from this fact:
- It is the boundary between the (external) client and the realization of a component - so it is the only possible artifact with a remote interface.
- ServiceFacade is stateless (only in exceptional cases stateful - why you would need state in procedures?)
- Every method has to start a new transaction to be executed consistently
- ServiceFacade is the single entry point into a component, so it can be easily decorated with aspects.
So in general case it is a:
- @Stateless Session Bean
- @Remote interface is optional, for web clients you should always use @Local interfaces
- All methods are transactional - you will need @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) - it is more explicit
- From the conceptual point of view - a ServiceFacade should only coordinate Services and should not implement any business logic.
- A ServiceFacade should be deployed with a business interface - its easier to mock. No-interface view would work with frameworks like mockito - but is not worth the optimization.
- If it is needed, you can implement cross-cutting aspects - if you are doing so, provide the interceptors on class and not the method level - is more consistent. I try to avoid the usage of @Interceptors - the less magic, the better. James Gosling said once: "(AOP) It's like giving them a chainsaw without any safety instructions." :-)
@Stateless @Local(BookOrderingService.class) @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @Interceptors(PreconditionInterceptor.class) //optional public class BookOrderingServiceBean implements BookOrderingService { @EJB DeliveryService deliveryService; }The business interface is just a POJI. It is not dependent on the EJB API at all.
The code above (with several strategies, interceptors and ideas) was checked in (actually pushed :-)) into: http://kenai.com/projects/javaee-patterns