What are the advantages of using EJB compared to POJO?

user1883212 picture user1883212 · Mar 24, 2013 · Viewed 8.7k times · Source

Why should I ever use EJB? What can I get from it that I can't get in other ways?

What are the advantages of using EJB compared to POJO?

Answer

A4L picture A4L · Mar 25, 2013

EJBs are managed and monitored by the Java EE application server, it takes care of creating and providing them to the clients via dependency injection and managing their lifecycles. EJBs are kept by the app-server in pools. Each time a client acquires an EJB, the app-server picks one from the pool and assign it to the client. After the client is done with it (there is no reference to it left on the client side) it is returned to the pool and is ready for assigning to other clients.

Pooling is very significant for scalability of the application. You do not have to change anything to a deployed application to handle growing load and your application will not take the app-server on the knees if gets too high load since the amount of resources is limited. Everything is done by configuring the app server.

EJBs can - if accordingly annotated - handle transactions and asynchronous execution and can be exposed to remote clients.

There are four types of EJBs:

Session beans

  1. Stateless EJBs: Lets the client perform some operation and return, cannot be used to hold a state since the server may assign it to other clients (you may use this as kind of communication between client, for example if you have an instance variable there an set it to a value, then this value may be seen by other clients). You can think of using Stateless EJB method just as functional programing or static methods of a class.
  2. Statefull EJBs: Lets the client maintain a state across multiple requests (the client must hold a reference to it otherwise the app server may assign it to another client)
  3. Singleton EJBs: as the name says the server guarantees that this Instance is unique for the whole application.

Message driven beans

  1. Message driven EJBs: Is also stateless and used to send and receive messages usually in combination with JMS. Message handler function executes asynchronously.

While EBJs offer all that and may other things, POJOs are just POJOs nothing less and nothing more.