Simplify EJB development with ejb3.0

Source: Internet
Author: User
Enterprise JavaBeans (EJB) is introduced to build distributed components. Initially, the technology promised to solve all the problems of CORBA and reduce its complexity. As the core of J2EE, EJB has undergone several major revisions and added many features, which has become bloated. From the very beginning, most developers love EJB very much and are even applying it without any meaning. Program Use EJB. Many developers blame EJB when the project cannot be scaled normally and EJB is used.

EJB development has never become easier. On the contrary, with the successive release of EJB specifications, it has become more and more complex. Due to its complexity and its own huge system, EJB is hailed as an elephant. Many developers think that ejbs are like a layer of sugar that is added to the pie. In the age of low-sugar diet and low-carbon water compounds, the EJB expert committee had no choice but to work hard to provide low-sugar ejbs to simplify EJB development. The EJB 3.0 Expert Committee released the first public draft of the EJB 2004 specification during the javaone 3.0 meeting and provided an example of a lightweight model.

The first impression of the new EJB module is that it looks very beautiful. In this article, we will discuss how EJB 3.0 can pack itself more compact and exquisite to attract developers' attention. In the next articleArticleWe will discuss how ejb3.0 simplifies the persistence model.

Complexity of the EJB Model

Before discussing the new features of EJB 3.0, let's take a look at the complexity of the current EJB model.

    • The current EJB model requires creating several component interfaces and implementing several unnecessary callback methods.
    • These component interfaces need to implement EJB object or EJB localobject and handle many unnecessary exceptions.
    • The EJB deployment descriptor is complex and error-prone.
    • The persistence of container management is based on the EJB model, which is also very complex and is not conducive to development and management. Some basic functions are lacking (such as using database sequences to define primary keys in a standard method), and ejbql is very limited.
    • Due to inheritance and polymorphism constraints, the EJB component is not the same as the source object.
    • One of the main disadvantages of EJB is that it is not possible to test the EJB module outside the EJB container, and it is terrible for developers to debug the EJB module in the container.
    • If you have used ejbs, you will know how complicated it is to find and call ejbs. To use EJB in an application, you must understand every detail of JNDI.

Simplified developer View

If you have used the latest specification to develop EJB, you will find it difficult to develop a simple EJB like helloworldejb. You must have at least two interfaces, One Bean class, and one deployment descriptor. Most developers are thinking: What do I do? In Oracle jdeveloper, Eclipse, XDoclet, and other ides, developers can easily complete these things. However, before deploying EJB to the selected container, developers still need to compile these classes and encapsulate deployment descriptors.

EJB 3.0 wants to overcome this complexity using the following methods:

    • Instead of using interfaces and deployment descriptors, containers use metadata annotations to generate them.
    • Use common Java classes as ejbs and common business interfaces as ejbs.

Metadata Annotation

EJB 3.0 is highly dependent on metadata tags. Metadata tags are standardized under JSR 175 and will be included in j2se 5.0. Annotation is an attribute-oriented programming, similar to XDoclet. However, unlike XDoclet that requires pre-compilation, annotation is compiled into the class by the Java compiler during compilation (depending on how to set @ retention ). For developers, tags are similar to public modifiers and can be used in classes, fields, methods, parameters, local variables, constructors, enumerations, and packages. Can be specified for generatingCodeArchive code or provide special services (enhanced business-level security or specific business logic) at runtime, so as to use annotation in Java code. J2EE 1.5 (5.0) aims to simplify development by using annotations, So it provides its own set of annotations. The annotation is marked with @, as shown below:

 
@ Author ("Debu Panda") @ bean public class mysessionbean

The purpose of EJB 3.0 is to simplify development. Therefore, Metadata Annotation is used to generate several artifacts similar to interfaces. Annotations are used instead of deployment descriptors.

Use pojo and poji

According to standardized terms, JavaBeans and interfaces are often called plain old Java objects (pojo) and plain old Java interfaces (poji) respectively ). The current EJB classes and interfaces are similar to pojo and poji. Unnecessary artifacts such as the home interface will no longer be needed.

Developers must either implement an EJB interface (sessionbean, entitybean, or messagedrivenbean) in javax. ejbpackage, or use annotation in the bean implementation class. You can use stateless, stateful, messagedriven, or entity to mark bean classes. For example, if you define a stateless EJB as helloworld, you can define this EJB as follows:

 
@ Remote @ stateless public class helloworldbean {Public String sayhello (string s) {system. Out. println ("Hello:" + S ;}}

Ejbobject or ejblocalobject is not required. The service interface must be provided for the EJB and implemented in the bean class; or the interface must be generated during deployment. For entity beans, the interface is optional; but for sessionbean and messagedrivendriven, the interface is required. If the interface is not implemented for the Session Bean, a bean interface is generated. The generated interface type can be local or remote, depending on the annotation used in the bean class. From the code example above, we can clearly see that @ remote is used to generate a remote interface for helloworld bean. If necessary, you can provide both remote and local interfaces for EJB.

The preceding example clearly shows that developers do not need to perform a large number of common tasks, such as defining interfaces and implementing callback methods.

The generated interface name is derived from the bean implementation class name. The generated interface is indeed good for developers. However, I don't think the generation interface has much advantage, because most IDES (such as Oracle jdeveloper) can dynamically generate these interfaces.

The draft does not clearly describe what is the client requirement for EJB search and how to obtain the interfaces required to call the EJB. We recommend that you do not use the generated interface for the following reasons:

    • The name of the generated interface is derived from the bean name.
    • You may not want to publish some methods in EJB in the generated interface. By default, all methods are published for the generated interface.
    • You need a client interface to call EJB.

Callback method no longer required

Ejb2.1 and earlier versions require that you implement several lifecycle methods for each EJB, such as ejbpassivate, ejbactivate, ejbload, and ejbstore, even if you do not need these methods. For example, the stateless session bean does not require ejbpassivate, but the method still needs to be implemented in the bean class. Because ejb3.0 is similar to a common Java class, it is no longer necessary to implement these lifecycle methods. If the callback method is implemented in EJB, the container will call this method.

The only exception is the EJB Remove Method in the stateful Session Bean. In the stateful Session Bean, you can use the remove annotation to mark the stateful session bean business method. If you use this annotation, it prompts the container to delete the stateful Session Bean instance after the annotation method is completed (normal or abnormal. For example, you can specify the following code to delete the stateful Session Bean instance after the checkout method is executed.

 
@ Stateful public class cart {...... @ remove public void checkout (){...}}

Comparison between annotation and deployment descriptor

As mentioned above, the deployment descriptor is no longer required for EJB, but the annotation is used. The default values of each attribute in the deployment descriptor will be selected. Developers do not need to specify these attributes unless they use values other than the default values. You can use annotations in bean classes to specify these values. The EJB 3.0 specification defines a set of metadata annotations for developers, such as bean type, interface type, resource reference, transaction attribute, and security. For example, if we want to reference resources for a specific EJB, we will define it as follows:

@ Resource (name = "JDBC/oracleds", resourcetype = "javax. SQL. datasource ")

J2EE vendors (such as Oracle, Bea, and IBM) will add attribute tags in the deployment descriptor that is specific to the vendor. Developers will use these tags to avoid using deployment descriptors. This is quite attractive for developers because they do not have their most annoying XML descriptors. However, this also brings about some problems. We need to be cautious before using tags.

    • This hinders the implementation of application portability goals, because if EJB uses vendor-specific deployment descriptors without re-compiling/re-packaging ejbs, the changes will not be expected.
    • You do not need to view ejbs one by one. The deployment descriptor provides a complete view of the EJB module for the assembler/deployer (EJB-jar). They also adjust these views according to the requirements of each deployment. If the descriptor is unavailable or generated until the end of the deployment, the consequences may be unimaginable.
    • Various tools use deployment descriptors to identify ejbs In the EJB module. This can be very useful when migrating between containers.
      The EJB 3.0 specification also proposes a method to rewrite the annotation in the deployment descriptor. However, the specification does not provide details about the rewrite mark.

There is no doubt that the absence of deployment descriptors will make it easier for new developers to do their work, but improper use may lead to management problems.

Simplify the persistence of Container Management

EJB 3.0 comprehensively innovated CMP Entity beans to attract developers' attention. Persistent frameworks (such as oracleas toplink) and open source hibernate) have become the favorites of the Persistence frameworks for developing J2EE applications, and entity beans are no longer popular due to their complexity and complexity. EJB 3.0 adopts a lightweight persistence model similar to toplink and Hibernate to simplify the persistence of container management, which is undoubtedly tempting for developers. Let's take a brief look at this entity bean program. We will discuss more about persistence improvement in another article.

The Entity Bean is being reborn as a pojo, and the component interface is no longer required for the Entity Bean. Now the Entity Bean will be treated as a pure object because it will also support inheritance and polymorphism.

The following are Entity Bean'sSource code:

@ Entity public class employee {private long empno; private string empname; private Address; private hashmap projects = new hashmap (); private double salary; @ ID (generate = sequence) public long getempno () {return empno;} protected void setempno (long empno) {This. empno = empno;} Public String getempname () {return empname;} public void setempname (string empname) {This. empname = empname;} @ dependent public address getaddress () {return address;} public void setaddress (Address) {This. address = address;} public set getprojects () {return projects;} public void setprojects (SET projects) {This. projects = projects;} public double getsalary () {return salary;} public void setsalary (double salary) {This. salary = salary ;}....}

Observe the above Code to find that this bean class is the entity class of the current Entity Bean, rather than the abstract class.

The query function is improved in ejb ql and supports SQL query in entity beans. A new entitymanager API similar to hibernate (a simplified version of toplink 'session API) is proposed to operate entity beans, that is, to create, delete, and find entity beans ..

We will carefully discuss the details of the proposed CMP Entity Bean in the next article.

Simplify the client view of EJB

Using EJB (that is, searching and calling) is very complex, even if EJB has been configured in the application. The J2EE 1.4 and EJB 3.0 specifications simplify the client view of EJB.

If you want to use EJB now, you must define EJB-ref or EJB-local-ref in the deployment descriptor, find the EJB, and then call it. To call helloworld EJB, the following is the simplest method to call EJB in the current implementation.

First, define the EJB reference in the deployment descriptor, as shown below:

 
<EJB-ref> <EJB-ref-Name> helloworldejb </EJB-ref-Name> <EJB-ref-type> session </EJB-ref-type> <Home> hello. helloworldhome </Home> <remote> hello. helloworld </remote> </EJB-ref>

Then, use the following code to find the EJB. You must explicitly process the EJB lookup and creation exceptions of the bean instance.

Try {context = new initialcontext (); helloworldhome hellohome = (helloworld) portableremoteobject. narrow (context. lookup ("Java: COMP/ENV/EJB/helloworldejb"), helloworldhome. class); helloworld Hello = hellohome. create ();....} catch (RemoteException e) {system. err. println ("system/communication error:" + E. getmessage ();} catch (namingexception e) {system. err. println ("communication error:" + E. getmessage ();} catch (createexception e) {system. err. println ("error creating EJB instance:" + E. getmessage ());}

For environment variables, we recommend that you use setter injection to find and call ejbs.

The following code uses setter injection to find helloworldejb in another EJB.

 
@ Inject private void setsessioncontext (sessioncontext CTX) {This. CTX = CTX }... myhello = (helloworld) CTX. lookup ("Java: COMP/ENV/EJB/helloworldejb ");

After carefully studying the above code, we can find that the setsessioncontext method is labeled with @ inject to use dependency injection for this method. The injection method is called by the container to set ejbcontext before calling any business method on the EJB.

Another direct example of injecting helloworld Session Bean is to only use @ ejbpublic helloworld myhello, which causes myhello to be injected through a helloworld bean instance.

You can use dependency injection to find any types of Environment and Resource references, such as datasource, JMS, mail, and Web services.

Testability and availability outside containers

One of the main concerns of current EJB developers is not only the complexity of EJB development, but also the difficulty of testing. The development and testing of ejbs are inseparable from the EJB container. Developers must be familiar with the final deployment platform before testing. This may not be a major problem for many enterprise developers. But for ISVs that provide support for multiple vendors, this is indeed a problem. They must maintain multiple environments to test their ejbs. The EJB 3.0 specification promises to provide capabilities for testing outside the container, but details are not mentioned in the draft Specification.

Conclusion

Despite missing a lot of detailed information about packaging, assembly, and APIs, the proposals in the EJB 3.0 draft are still tempting for Enterprise Java developers. Leaving this work to the container vendor will help reduce the complex problems faced by developers. This depends on how the container vendor implements these tasks and makes EJB 3.0 an inevitable choice for developing enterprise applications. 

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.