Starting a new project and would like to know the pros and cons of packaging EJB in a WAR vs EAR.
Will JNDI still works when EJBs are in the WAR? efficiency? etc.?
Thanks.
An important motivation for having EJB beans in a separate JAR is for the age old separation of business logic and view logic.
Since EJBs are supposed to concentrate solely on business logic, it makes sense to put them into a separate module.
This is exactly what the traditional Java Enterprise Archive facilitates. The EJB beans go into a JAR file which represents the EJB module
, while the web related artifacts (Facelets, backing beans, utility code) go into a Web Archive (WAR) file which represents the Web module
. Note that a WAR doesn't actually have to be a file. In the so-called exploded format they are merely directories.
A key aspect of this separation is that those two modules are isolated via a class loader hierarchy. The Web module
has access to resources (typically beans) from the EJB module
, and the EJB module
can reference resources (typically libraries) defined in the overall EAR umbrella. The other direction is not possible. Specifically, the EJB module
cannot access any resources defined in the Web module
.
This enforcement is deliberate.
Business logic should be completely independent of any view technology. Enforcing this isolation prevents developers from accidentally or when under pressure mixing those concerns anyway. The benefits of this separation is that business logic can trivially be used by among others Java SE clients, Web module clients, JAX-RS clients, etc. If the business logic accidentally had JSF or Servlet dependencies, it would be very hard to use it from Java SE clients.
Compare this with Facelets not allowing scriptlets to be used. This keeps the Facelets clean and let them focus on component layout and markup exclusively. Another analogy is with coding to interfaces, which separates the contract from the implementation.
So having a separate EJB module is actually a best practice. However...
For smaller projects it might be unnecessary to have this separation and for beginning programmers it might be difficult to wrap their heads around the structure of what needs to go where. Removing the mandatory separation thus makes it easier for inexperienced developers to start with Java EE. It gives them a gentle introduction into Java EE and later once they get the idea of layering, they can then opt to introduce an EJB module
anyway.