Developing an enterprise-class bean component with EJB 3.0 initial experience

Source: Internet
Author: User
Tags abstract aop object functions new features version jboss jboss application server
   Read the summaryThe final draft of the EJB 3.0 specification has been submitted to JCP, and EJB3.0 will be officially released in 2006 if not unexpectedly. This article, the first in the common draft three series of EJB 3.0, explains the basic concepts of EJB 3.0 and enterprise bean components, and you learn how to use JBoss and MAVEN to develop enterprise-class bean components based on EJB 3.0.

Although the EJB 3.0 specification has not yet been officially released, it has drawn wide interest in the Java Development Community-both for its advocates and for its competitors. Everyone acknowledges the urgent need to find more productive software development methodologies; Today, their debate is focused on EJB 3.0.

Despite the controversy, the release of the EJB 3.0 specification draft and initial support at JBoss mean that it is time to explore this powerful technology. In fact, reports on the application of EJB 3.0 in production systems have already surfaced.

This article is the first in the public draft three series on EJB 3.0. This article will introduce you to some of the special concepts in the draft and will work with you to implement these specific techniques with jboss. In addition, this article covers some basic concepts of EJB 3.0 and enterprise bean components.

To do this, you need to prepare as follows:

· Java 2 SDK 1.5
· Maven 2.0
· JBoss Application Server 4.0.3
· JBoss AOP 1.3.4

   First, EJB 3.0 introduction

Enterprise applications are a class of applications that implement business functions and contain large amounts of data. These applications typically do not perform tasks in isolated environments, and each of these programs often becomes a small part of a large IT system and must interact with people and other systems. In short, developing an enterprise-class application is a pretty hard thing to do. In almost all enterprise applications, in order to successfully perform their functions in the enterprise, it is important to emphasize a range of issues such as performance, scalability, concurrency, and security.

In response to these challenges, the EJB specification was produced in March 1998 to make it easier to develop distributed object-oriented business systems. This specification and the application server that implements it have already achieved this goal to a large extent. However, over the past few years, the lack of ejbs and the advent of simpler implementations have raised a number of questions-whether EJB can provide the best solution for productivity development for enterprise-class applications?

The disadvantages that EJB often mentions include the following:

• Use a large number of EJB APIs if you want to take advantage of the components provided by the Enterprise Services.

• It is an all-or-nothing proposition. Even if you want to use an EJB service, you must also use all the other content that accompanies the EJB.

· The EJB component requires a corresponding container and is proven to be difficult to test.

• Require each EJB to implement several content (interfaces, classes, and descriptors).

• Traditional EJB architectures rarely involve object-oriented and introduce "fake objects" with only state and no behavior.

Some of the popular choices about EJBS are:

• Aspect-oriented programming (AOP)

• Lightweight containers, such as Spring,pico container and Hivemind

• Object-relational mapping (ORM) tools, such as Hibernate,jdo and Ibatis

·. NET Serviced Components

EJB 3.0 Specification Public draft the main purpose is to make development easier and to make balancing enterprise services simpler. These improvements have, to some extent, benefited from the successful application of the above mentioned content. Some aspects of the above tools still have their traces in EJB 3.0:

• A Pojo (normal Java object) programming model

• A lightweight ORM persistence framework

• Dependency Injection

• Meta data annotations

In the EJB 3.0 specification, some other important components include:

• Configuration through exceptions

• Eliminates component interfaces

• Eliminate Home interface

• Check for reduced use of exceptions

This article assumes that you are familiar with the EJB 2.x and will focus on the new changes introduced in the 3.0 specification public draft. The remainder of this article will analyze these improvements in the process of building an EJB 3.0 application by using the MAVEN and JBoss application servers.

   Second, application example-an online music store

All of the techniques discussed in this article are now attached to the sample application-an online music store. This store allows users to browse and buy music, video and audio books. Figure 1 shows a screenshot of this interface; you can download the source code at the end of this article.


Fig. 1. Music Store: The music store allows browsing of products that can be added to a shopping cart and eventually purchased.
This sample program shows the use of all three types of enterprise bean components, stateless session beans, stateful session beans, and message-driven beans. Note that in the EJB 3.0 specification, Entity beans is no longer treated as an enterprise bean component as the session beans and message-driven beans. Instead, they are considered persistent entities (this will be covered in my next article on EJB 3.0 persistence). The class diagram in Figure 2 is a high-level display of how to implement the music store application using EJB.


Figure 2. Music Shop design: In this Web application, the request is handled with a struts behavior-this behavior uses two ejbs (a stateless, stateful) to implement the request. At the checkout desk, the customer's shopping cart is passed through JMS to an order processor implemented in an MDB form.


The design and testing tools for the instance application that accompanies this article are: JBoss Application Server 4.0.3 and JBoss AOP 1.3.4, and build this application using Maven 2.0来. The attached source code provides guidance for setting up JBoss, building source files using Maven, and publishing the application.

  Third, stateless session beans

Like some of the other enterprise bean components in the EJB 3.0 spec, stateless session beans is a pojo that implements a business interface. Take our music Store as an example: the music Store implements query capabilities for various types of audio and video when users browse. For this music store, a simple interface implementation of this function can be written as follows:

public interface imusicstore{
Public list<genre> listgenres ();
Public genre Findgenrebyid (int id);
Public Artist Findartistbyid (int id);
Public Product Findproductbyid (int id);
public void CheckOut (Ishoppingcart cart);
}


And here's a simple implementation of this situation:

public class Musicstore implements imusicstore{
Public list<genre> Listgenres ()
{return musicstoredao.getinstance (). Listgenres ();}
Public genre Findgenrebyid (int id)
{return musicstoredao.getinstance (). Findgenrebyid (ID);}
Public Artist Findartistbyid (int id)
{return musicstoredao.getinstance (). Findartistbyid (ID);}
Public Product Findproductbyid (int id)
{return musicstoredao.getinstance (). Findproductbyid (ID);}
public void CheckOut (Ishoppingcart cart)
{ ... }
}


In EJB 2.x, if you want to take advantage of the benefits of enterprise services, such as declarative transaction management or object distribution, Then you have to modify the music store to implement the Javax.ejb.SessionBean interface and the methods defined in this interface, and create local and remote beans and home interfaces.

In EJB 3.0, a class is extended to a stateless session bean must meet the following two basic requirements:

1. Achieve at least one commercial interface.

2. Annotated with the @javax.ejb.stateless annotation.

A commercial interface is only a common Java interface. The java.io.Serializable and java.io.Externalizable interfaces are automatically ignored because they are interfaces in the JAVAX.EJB package. If only one interface is specified, it is assumed to be a local interface. This is the only example in the configuration of the specification. If the bean has more than one commercial interface, then each interface must be explicitly defined as local or remote-by annotating the Bean class or by annotating the interfaces themselves.

Therefore, in order to make the Musicstore Class A stateless session bean, only one change is required. You must annotate it with @stateless annotations.

@Stateless
public class Musicstore implements imusicstore{...}


Another major change associated with EJB 3.0 is actually a change-dependency injection in the Java EE 1.5 specification. Java EE 1.5 specification requirements, Java EE application customers, enterprise beans and Web Components can access a JNDI naming environment. The naming environment can be accessed, either by explicit Jndi lookup calls or by specifying a container that automatically injects dependency annotations. This means that you can now declare a dependency on an EJB or other resource managed by the container by using a simple annotation like this:

Import Com.devx.musicstore.IMusicStore;
Public abstract class Abstractstoreaction extends action{
@EJB
protected Imusicstore Store;
...
}


That's it! The container injects an implementation of the interface Imusicstore into that behavior, which can use the stored object as if it were a simple pojo.

   Author Note:

Resource injection functionality for Web Components has not yet been implemented in the JBoss4.0.3 version, although this support is about to occur (http://jira.jboss.com/jira/browse/EJBTHREE-212). The instance code contains an aspect-written in JBoss AOP, which implements dependency injection.


What really goes on behind this is that this annotation specifies that an EJB reference to the type imusicstore be injected into the store field. The target for this dependency is not specified, so it must be provided by the publisher-just like using a traditional resource reference. If you do not specify a dependency name (as shown in the previous example), you assume that you use the name of the full limit of the class. In the above example, this will be java:comp/env/com.devx.musicstore.imusicstore.

   The author notes that in the default use of the EJB reference name, there are ambiguities in the EJB 3.0 and Java EE 1.5 specifications regarding whether to use an open-ended or fully restricted class naming problem. EJB 3.0 Public Draft specifies an unrestricted bean class name, while the draft Java 1.5 shows a fully restricted naming example. The JBoss implementation uses a fully restricted naming.

As a choice, you can further practice the declaration of this dependency in the following ways:

Public abstract class Abstractstoreaction extends action{
@EJB (
Name = "Ejb/musicstore",
Beanname = "Store1",
Businessinterface = Com.devx.musicstore.IMusicStore.class
)
protected Imusicstore Store;
...
}


Here, access to the EJB reference is implemented through Jndi in Java:comp/env/ejb/musicstore.

  Four, remote interface

To remotely access a session bean, you only need to annotate it with the following @remote annotation:

@Stateless
@Remote
public class Musicstore implements Imusicstore
{ ...}


In the above example, the Musicstore bean only implements a commercial interface; Since this class is specified as remote, we assume it is remote. Otherwise, if Musicstore implements two commercial interfaces, you will be asked to specify which interface is local and which interface is remote. To do this, you can use one of the following two methods: On the class or on the interface. Changing the Musicstore class to use a remote interface is as follows:

@Stateless
@Local ({imusicstore.class})
@Remote ({imusicstoreremote.class})
public class Musicstore implements Imusicstore, Imusicstoreremote
{ ...}


You can compare the above method with the method specified on an interface:

@Remote
public interface Imusicstoreremote
{ ...}


Note that the remote interface did not throw a remoteexceptions exception. If an exception appears at the protocol level, a ejbexception exception that wraps the RemoteException will be thrown by the container. As a runtimeexception exception, Ejbexception does not need to be signed on the remote interface's method or declared in its implementation bean class.

   v. Stateful session Beans

Stateful session beans have very similar requirements to stateless session beans. Like stateless session beans, they must have at least one commercial interface. However, they are annotated with the @stateful annotation. So in the music store example, the user's shopping cart has been modeled as a stateful session bean-since it describes a stateful session between the user and the server:

@Stateful
public class ShoppingCart implements Ishoppingcart
{ ...}


As in EJB 2.x, a reference to the same stateful session Bean is also handled by the same EJB instance; So it is important to store this reference in a location that can be read by the customer continuously. In the case of a music store, this reference is stored in the user's httpsession.

   vi. message-driven beans

The message-driven beans (MDB) also implements a commercial interface and is annotated to indicate their bean type. In this case, however, the business interface is not from the domain but from a suitable listener interface for the type of message system used. In the case of JMS, this is Javax.jms.MessageListener. This music store's order processor provides an example:

@MessageDriven
public class Orderprocessor implements messagelistener{
public void OnMessage (message message) {
ObjectMessage objectmessage = (objectmessage) message;
try{
Order order = (order) objectmessage.getobject ();
SYSTEM.OUT.PRINTLN ("Products Ordered:");
For (Product p:order.getproducts ())
{System.out.println (P.gettitle ());}
}
catch (JMSException e) {e.printstacktrace ();}
}
}


As with EJB 2.x, you can give publishers additional information about how to configure the MDB. This information can now be provided through the activationconfig element of the @messagedriven annotation. For example, to define orderprocessor only when the JMS message arrives at the order queue, you can annotate the class as follows:

@MessageDriven (Activateconfig = {
@ActivationConfigProperty (propertyname = "destinationtype", PropertyValue = "Javax.jms.Queue"),
@ActivationConfigProperty (propertyname = "Destination", PropertyValue = "Queue/orders")
})
public class Orderprocessor implements MessageListener
{ ...}


But as in the previous version of the EJB, the publisher is responsible for associating an MDB with a target or terminal.

   vii. Packaging and publishing

Packaging in EJB 3.0 is similar to packaging in the previous version of EJB. As in the previous release, the enterprise Bean class must be packaged into one. Jar file. The biggest difference is that in the EJB 3.0 release, the release descriptor becomes optional. However, if you provide a publishing descriptor, it must exist in its usual location (Meta-inf/ejb-jar.xml).

The sample application demonstrates building a EJB3.0 ejb-jar and binding the jar to a Web application (WAR) in the form of an enterprise file (EAR). The build uses Maven 2.0; Please refer to the attached source code for more information.

   Author Note: In JBoss, the EJB 3.0 jar file has an extension of. ejb3-This is an JBoss convention and not a requirement in the specification.

To publish the sample application, just put the results. The ear file is copied to a publishing directory of an JBoss 4.0.3 server configured with the JBoss AOP 1.3.4 Publisher. Installation instructions are also included in the attached source code.

   viii. use of a simplified model

The EJB 3.0 Public draft shows a fairly simplified model for creating enterprise-class components. The purpose of this new paradigm is to simplify development, but to introduce fewer new features beyond the scope of the previous discussion. However, this simplification provided by EJB 3.0 should greatly enhance the productivity of your team's development, and you will be interesting to see how this new lightweight implementation competes with other lightweight frameworks such as spring and hibernate.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.