EJB vs. The World — Why Bother with EJB At All?

I’ve been slogging my way through some testing frameworks for EJB: The Grinder, Cactus and JMeter — trying to find that quick Soap UI style entry into testing EJB.  No such luck.  This will take some work.

So, I decided to remind myself just why we ere doing EJB in this application.   I bolded the main points.  Maybe we can make an acronym . . . .

A simple explanation from DevGuru:

Some of the things that EJBs enable you to do that servlets/JSPs do not are:

  • Declaritively manage transactions. In EJB, you merely specify whether a bean’s methods require, disallow, or can be used in the context of a transaction. The EJB container will manage your transaction boundaries appropriately. In a purely servlet architecture, you’ll have to write code to manage the transaction, which is difficult if a logical transaction must access multiple datasources.
  • Declaritively manage security. The EJB model allows you to indicate a security role that the user must be assigned to in order to invoke a method on a bean. In Servlets/JSPs you must write code to do this. Note, however that the security model in EJB is sufficient for only 90% to 95% of application code – there are always security scenarios that require reference to values of an entity, etc.

A very thorough answer from Stack Overflow:

  1. using/Sharing Logic across multiple applications/clients with Loose Coupling.
    EJBs can be packaged in their own jars, deployed, and invoked from lots of places. They are common components. True, POJOs can be (carefully!) designed as libraries and packaged as jars. But EJBs support both local and remote network access – including via local java interface, transparent RMI, JMS async message and SOAP/REST web service, saving from cut-and-paste jar dependencies with multiple (inconsistent?) deployments.
    They are very useful for creating SOA services. When used for local access they are POJOs (with free container services added). The act of designing a separate EJB layer promotes extra care for maximising encapsulation, loose coupling and cohesion, and promotes a clean interface (Facade), shielding callers from complex processing & data models.
  2. Scalability and Reliability If you apply a massive number of requests from various calling messages/processes /threads, they are distributed across the available EJB instances in the pool first and then queued. This means that if the number of incoming requests per second is greater than the server can handle, we degrade gracefully – there are always some requests being processed efficiently and the excess requests are made to wait. We don’t reach server “meltdown” – where ALL requests experience terrible response time simultaneously, plus the server tries to access more resources than the hardware & OS can handle & hence crashes. EJBs can be deployed on separate tier that can be clustered – this gives reliability via failover from one server to another, plus hardware can be added to scale linearly.
  3. Concurrency Management. The container ensures that EJB instances are automatically accessed safely (serially) by multiple clients. The container manages the EJB pool, the thread pool, the invocation queue, and automatically carries out method-level write locking (default) or read locking (through @Lock(READ)). This protects data from corruption through concurrent write-write clashes, and helps data to be read consistently by preventing read-write clashes.
    This is mainly useful for @Singleton session beans, where the bean is manipulating and sharing common state across client callers. This can be easily over-ridden to manually configure or programatically control advanced scenarios for concurrent code execution and data access.
  4. Automated transaction handling.
    Do nothing at all and all your EJB methods are run in a JTA transaction. If you access a database using JPA or JDBC it is automatically enlisted in the transaction. Same for JMS and JCA invocations. Specify @TransactionAttribute(someTransactionMode) before a method to specify if/how that particular method partakes in the JTA transaction, overriding default mode: “Required”.
  5. Very simple resource/dependency access via injection.
    The container will lookup resources and set resource references as instance fields in the EJB: such as JNDI stored JDBC connections, JMS connections/topics/queues, other EJBs, JTA Transactions, JPA entity manager persistence contexts, JPA entity manager factory persistence units, and JCA adaptor resources. e.g. to setup a reference to another EJB & a JTA Transaction & a JPA entity Manager & a JMS connection factory and queue:

    @Stateless
    public class MyAccountsBean {
    
        @EJB SomeOtherBeanClass someOtherBean;
        @Resource UserTransaction jtaTx;
        @PersistenceContext(unitName="AccountsPU") EntityManager em;
        @Resource QueueConnectionFactory accountsJMSfactory;
        @Resource Queue accountPaymentDestinationQueue;
    
        public List<Account> processAccounts(DepartmentId id) {
            // Use all of above instance variables with no additional setup.
            // They automatically partake in a (server coordinated) JTA transaction
        }
    }

    A Servlet can call this bean locally, by simply declaring an instance variable:

    @EJB MyAccountsBean accountsBean;    

    and then just calling its’ methods as desired.

  6. Smart interaction with JPA. By default, the EntityManager injected as above uses a transaction-scoped persistence context. This is perfect for stateless session beans. When a (stateless) EJB method is called, a new persistence context is created within the new transaction, all entity object instances retrieved/written to the DB are visible only within that method call and are isolated from other methods. But if other stateless EJBs are called by the method, the container propagates and shares the same PC to them, so same entities are automatically shared in a consistent way through the PC in the same transaction.
    If a @Stateful session bean is declared, equal smart affinity with JPA is achieved by declaring the entityManager to be an extended scope one: @PersistentContent(unitName=”AccountsPU, type=EXTENDED). This exists for the life of the bean session, across multiple bean calls and transactions, caching in-memory copies of DB entities previously retrieved/written so they do not need to be re-retrieved.
  7. Life-Cycle Management. The lifecycle of EJBs is container managed. As required, it creates EJB instances, clears and initialises stateful session bean state, passivates & activates, and calls lifecycle callback methods, so EJB code can participate in lifecycle operations to acquire and release resources, or perform other initialization and shutdown behavior. It also captures all exceptions, logs them, rolls back transactions as required, and throws new EJB exceptions or @ApplicationExceptions as required.
  8. Security Management. Role-based access control to EJBs can be configured via a simple annotation or XML setting. The server automatically passes the authenticed user details along with each call as security context (the calling principal and role). It ensures that all RBAC rules are automatically enforced so that methods cannot be illegally called by the wrong role. It allows EJBs to easily access user/role details for extra programmatic checking. It allows plugging in extra security processing (or even IAM tools) to the container in a standard way.
  9. Standardisation & Portability. EJB implementations conform to Java EE standards and coding conventions, promoting quality and ease of understanding and maintenance. It also promotes portability of code to new vendor app servers, by ensuring they all support the same standard features and behaviours, and by discouraging developers from accidentally adopting proprietary
    non-portable vendor features.
  10. The Real Kicker: Simplicity. All of the above can be done with very streamlined code – either using default settings for EJBs within Java EE 6, or adding a few annotations. Coding enterprise/industrial strength features in your own POJOs would be way more volumous, complex and error-prone. Once you start coding with EJBs, they are rather easy to develop and give a great set of “free ride” benefits.

OK not so sure about “simplicity.”


Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>