EJB

From Wiki RB4
(Redirected from JavaJEEEJB)

Enterprise Java Beans (EJB)[edit]

EJB sind das Komponentenmodell von Java für Enterprise Anwendungen. Written in the Java programming language, an enterprise bean is a server-side component that encapsulates the business logic of an application. The business logic is the code that fulfills the purpose of the application. Die Ablaufumgebung ist der EJB Container, der folgende Dienste zur Verfügung stellt:

  • Security Handling (authorized access)
  • Concurrency Handling (concurrend access)
  • Transaction Handling
  • load balancing and distribution

The developer should see as less as possible of the infrastructure.

You should consider using enterprise beans if your application has any of the following requirements:

  • The application must be scalable. To accommodate a growing number of users, you may need to distribute an application’s components across multiple machines. Not only can the enterprise beans of an application run on different machines, but also their location will remain transparent to the clients.
  • Transactions must ensure data integrity. Enterprise beans support transactions, the mechanisms that manage the concurrent access of shared objects.
  • The application will have a variety of clients. With only a few lines of code, remote clients can easily locate enterprise beans. These clients can be thin, various, and numerous.


There are three types of enterprise beans:

Die ursprünglichen JavaBeans (java.beans.*) sind ebenfalls ein Komponentenmodell, aber kein serverseitiges wie EJB. Sie haben aber nichts miteinander zutun. Außer das es beides Komponentenmodelle sind und sie den gleichen Namen haben, dienen die beiden APIs unterschiedlichen Zwecken. EJB erweitern das ursprüngliche Modell nicht und verwenden es auch nicht. Die ursprünglichen Beans sind dafür gedacht in einem Prozeß eingesetzt zu werden z.B. für GUI-Elemente.

Versionen und Inhalte[edit]

EJB 1.0[edit]

  • 1998

EJB 2.1[edit]

  • EJB2.1 belongs to J2EE 1.4
  • Persistance is managed by the EJB container by Container-Managed Persistance (CMP) and Bean-Managed Persistance (BMP)
Disadvantages[edit]
  • complex, not lightweight
    • content and numbers of deployment descriptors
    • some methods have to be implemented, although they were not in an interface and couldn't be checked at compile time
    • neccessity to implement artifacts
  • functional range for persistence was not enough to model established O/R mappings
    • container-managed persistance for an entity with a multi-table-mapping

EJB 3.0[edit]

  • 05/2006
  • belongs to JEE 5

Version 3.0 vereinfacht die Implementierung. Getrieben wurde dies durch konkurrierende lightweight frameworks wie Spring oder Hibernate, durch neue Java 5 Erweiterungen oder neue Design-Prinzipien wie Aspect Oriented Programming (AOP). EJB 3.0 is based on:

  • annotations, that means one source and compile time checking (eleminates the xml deployment descriptors in 80%, but it can still be there. Descriptor overwrites annotations)
  • container managed POJOs (no framework specific implementations like interfaces (javax.ejb.SessionBean, javax.ejb.EntityBean, javax.ejb.MessageDrivenBean), throws ; no home interface) with arbitrary inheritance structures
  • dependency injection (Holywood principle: don't call us, we call you; EJB isn't lookup up anymore, but specified by annotation and the container manages the rest, also cault inversion of control (IOC))
  • business interface as POJI (no inheritance from javax.ejb.EJBObject or javax.ejb.EJBLocalObject, no technical exceptions)
  • configuration by exceptions (only the special case has be described)
  • improvement of testability (no container for test necessary)
  • improvement of database queries (JPA instead of native SQL)
  • cross-cutting concern (Auslagerung von zentralen Funktionalitäten in interceptors z.B. zum Logging oder zentraler fachlicher Funktionalitäten)
  • shorter development cycles (because less errors, which are detected after build and deploy)
  • internal: change from RMI/IIOP to RMI

Architektur[edit]

Concurrency situations are:

  • Stateful session beans are exclusive instances for a client.
  • Stateless and message-driven beans are exclusive for a client for a method call, and the EJB container makes sure, that there is no concurrent access in the mehtod.
  • Persistence entities are managed by the persistence provider, not by the EJB container.

Session Beans[edit]

Session beans are typically used to model business processes or tasks. A session bean might model a set of e-mailing services or credit card validation service. Session beans are non persistent, can if neccessary be transactional, but that has to be implemented. Es gibt zwei Formen von session beans: stateful und stateless. An EJB 3.0 session bean is a POJO managed by the EJB container, which are annotated with @stateless or @stateful. Additionally the the business methods have to be specified in a Plain Old Java Interface (POJI). By design, the EJB specification disallows the same Business interface to be marked as @Local as well as @Remote (this restriction has been added in a revision to the PFD). The reason for this is that remote interfaces have different semantics to local interfaces, and it is usually inappropriate for the same method to be exposed as a remote interface as well as local interface. The problems are two-fold:

  1. Remote interfaces must typically be designed to be coarse-grained.
  2. Remote interfaces do not support the pass-by-reference semantics of parameter passing as in local interfaces.

Having separate Remote and Local interfaces forces designers to think about how the interfaces will be used and ensure that the design is optimised for the use case. It also reduces the chances of errors caused by incorrect semantics, such as clients relying upon ability to pass parameters by reference. Local Interfaces can only be uses in the same application (ear-file), not on the same server.

Stateless Session Beans[edit]

In a stateless session bean (SLSB), the client-side stub object can route your method call to any bean instance that happens to be available in the container-managed object pool. Hence, you should not have any field variables to store the bean state in the bean class. To define a session bean, you first need to define the local and remote service interface containing all its business methods. The session bean interface is just plain old Java interface without any annotation e.g.

public interface Calculator {
  public double calculate (int start, int end, double growthrate, double saving);
}
public interface RemoteCalculator {
  public double calculate (int start, int end, double growthrate, double saving);
  public String getServerInfo ();
}

and the implementation class:

import javax.ejb.*  // for annotations

@javax.ejb.Stateless                                                     
@javax.ejb.Local ({Calculator.class})                                    // specification of the local interface or direct at the interface
@LocalBinding (jndiBinding="EJB3Trail/LocalCalculator")                  // optional
@javax.ejb.Remote ({RemoteCalculator.class})                             // specification of the remote interface or direct at the interface
@RemoteBinding (jndiBinding="EJB3Trail/RemoteCalculator")                // optional
public class StatelessCalculator 
  implements Calculator, RemoteCalculator {
  public double calculate (int start, int end, double growthrate, double saving) {
    double tmp = Math.pow(1. + growthrate / 12., 12. * (end - start) + 1);
    return saving * 12. * (tmp - 1) / growthrate;
  }
}

The default naming binding is <EAR-FILE-BASE-NAME>/<EJB-CLASS-NAME>/(local|remote).

Features[edit]
  • not bound to a client, can be pooled
  • multi-method transactions by client or within one method
  • methods can be published as web service

Stateful Session Beans[edit]

If the client invokes method calls against the same bean stub, the calls are always tunneled to the same bean instance in the container. So, all field variables in the bean instance retain their values as long as the client application retains the bean stub (or reference for a local client). In a web application, the servlet (or JSP page) caches the bean stub as an attribute in the HttpSession object. It is very important to note that the stateful session bean class must implement the Serializable interface so that the container can serialize them and store them to preserve the state information when the bean instances are not in use.

Features[edit]
  • bound to a client with a client specific state (conversational state)
  • can be passivated, if not in transaction
  • methods cannot be published as web service

Message-Driven Beans[edit]

They are used for implementing asynchronous communications. You can't call methods directly. A MDB is the endpoint of a communication. It can be called by JMS or a web service. MDBs can be transactional, but not persistent. They are useful for long-lasting use cases or services to non-block the client.


Interceptors[edit]

There five different interceptor types.

interceptors for business methods[edit]

In the interceptor class use annotation @javax.interceptor.AroundInvoke or <around-invoke> in the deployment descriptor. In the bean class use @javax.interceptor.Interceptors(<INTERCEPTOR_CLASSES>) or <interceptor-binding> im deployment descriptor.

interceptors for lifecycle events[edit]

default interceptors[edit]

entity listener[edit]

default entity listener[edit]

Deployment Descriptor[edit]

The deployment descriptor is called ejb-jar.xml. The contents override annotations.

<ejb-jar> <!-- root -->
  <interceptors> <!-- see Interceptors -->
    <interceptor>
      <interceptor-class>
        <CLASSNAME>
      </interceptor-class>
    </interceptor>
  </interceptors>

  <assembly-descriptor>
    <interceptor-binding>
      <ejb-name>(*|<bean class>) <!-- default or special interceptor -->
      </ejb-name>
      <interceptor-class><CLASSNAME>
      </interceptor-class>
      <method-name>
      </method-name>
    </interceptor-binding>
  </assembly-descriptor>

</ejb-jar>

Resources[edit]