JSF Service Layer

The service layer (the business model) should be designed around the main entity (the data model). E.g. UserService for User, ProductService for Product, OrderService for Order, etc. You should absolutely not have one huge service class or so. That’s extreme tight coupling.

As to the service layer API itself, Java EE 6 offers EJB 3.1 as service layer API. In the dark J2EE ages, long time ago when EJB 2.0 was terrible to develop with, Spring was more often been used as service layer API. Some still use it nowadays, but since Java EE 6 has incorporated all the nice lessons learnt from Spring, it has become superfluous. Note that EJB (and JPA) is not available in barebones servletcontainers such as Tomcat. You’d need to install for example OpenEJB on top of it (or just upgrade to TomEE).

Regardless of the service layer API choice, best would be to keep your JSF backing bean (action)listener methods as slick as possible by performing the business job entirely in the service layer. Note that the service layer should by itself not have any JSF dependencies. So any (in)direct imports of javax.faces.* in the service layer code indicates bad design. You should keep the particular code lines in the backing bean (it’s usually code which adds a faces message depending on the service call result). This way the service layer is reuseable for other front ends, such as JAX-RS or even plain servlets.

You should understand that the main advantage of the service layer in a Java EE application is the availability of container managed transactions. One service method call on a @Stateless EJB counts effectively as a single DB transaction. So if an exception occurs during one of any DAO operations using @PersistenceContext EntityManager which is invoked by the service method call, then a complete rollback will be triggered. This way you end up with a clean DB state instead of a dirty DB state because for example the first DB manipulation query succeeded, but the second not.

See also:

Leave a Comment