Simplify enterprise-level Java Development with ejb3.0

Source: Internet
Author: User
Tags jboss application server
Java Enterprise version, or Java EE (formerly known as J2EE), is a powerful but overly complex platform for developing server applications. Since its birth, being too complex has always been an important factor in indecisive use of Java ee. In the previous article "The Road to simplification" in javaworld, I pointed out the factors that complicate Java EE applications, many of which are related to the current EJB 2.1 specification.
  
Over the past three years, Java open source community, Java Community progress (JCP), and major Java EE vendors have been committed to making Java EE simpler. For example, a new design example, such as the pojo service, service interceptor, and dependency injection, can be used to simplify Java EE development in practical applications. Also, new tools and frameworks, such as Hibernate, AOP (Aspect-Oriented Programming, Aspect-Oriented Programming), struts, XDoclet, and spring, have been widely used for the same purpose.
  
   Simplification is not a function reduction
  
Simplifying a programming model does not reduce its functionality. Simplification only hides the complex logic from the Framework Code or reusable components. Basically, it transfers complicated things from the point where they need to be directly managed by application developers to the places that most developers cannot see.
  
The templates and tools mentioned above make it easier for beginners to get started and increase the productivity of experienced Java developers. Now they are being merged into the next-generation Java EE standards by JCP (for example: ejbs 3.0 ). A recent study by Java developers Raghu kodali showed that transferring the sample program rosterapp of Java EE from EJB 2.1 to EJB 3.0 can reduce code by more than 50%.
  
Java annotation is the key behind ejb3.0. It binds pojo services, pojo persistence, and dependency injection together into a complete enterprise-level middleware solution. In this article, I used a sample application: JBoss EJB 3.0 trailblzer to demonstrate how to develop a lightweight EJB 3.0 pojo application using annotations. Trailblzer's application uses different tools and APIs in EJB 3.0 to implement a repeated investment calculator. The sample program can run in JBoss Application Server 4.0.3 and is fully compatible with the latest EJB 3.0 standard (when completed ).
  
Let's get started with the benefits of the annotation-driven programming model.
  
   Annotation-driven programming model of EJB 3.0
  
From the developer's point of view, EJB 3.0 widely uses Java annotations. Annotations have two key advantages: they replace too many xml configuration files and eliminate strict component model requirements.
  
   Comment vs XML
  
XML-based Deployment descriptions and annotations can be used together to configure service-related attributes in Java EE applications. The difference is that XML documents are processed separately from the Code, especially at runtime, while annotations are compiled together with the code and checked by the compiler. For developers, this has some important meanings, as listed below:
  
O lengthy: The xml configuration file is named long. To configure the code, the XML file must copy a lot of information, such as the class name and method name in the code. Java annotations are different. They are part of the code. configuration information can be specified without additional references.
O Robustness: repeated code information in XML files introduces the possibility of multiple errors. For example, if you write the wrong method name, the application will not crash until the runtime. That is to say, the robustness of the XML configuration file is not as good as that of the annotation. The annotation is checked by the compiler and processed together with other code.
O flexibility: Since XML files are processed independently outside the code, the configuration information based on XML is not hard-coded and can be modified later. Deployment flexibility is a very important feature for system administrators.
  
Annotations are easy to use and prove sufficient for most applications. XML files are more complex, but can be used to handle more advanced problems. EJB 3.0 allows you to configure most applications through annotations. EJB 3.0 also supports the use of XML files to overwrite default annotations and configure external resources such as database connections.
  
In addition to replacing and simplifying XML descriptors, annotations also allow us to abolish rigorous component models that plague EJB 1.xand EJB 2.x.
  
   Pojo vs strict Components
  
The EJB component is the container-managed object. The container operates the bean status and behavior at runtime. To make behavior happen, the EJB 2.1 Specification defines a strict component model that bean must comply. Each EJB class must inherit from a certain abstract class and provide a callback hook for the container. Since Java only supports single inheritance, strict component model limits the ability of developers to use EJB components to create a complex object structure. When you map complex application data to the Entity Bean, as we can see in the second part, this will become a big problem.
  
In EJB 3.0, all container services can be configured and delivered by using the annotated pojo application. In most cases, special component classes are not required. Let's use the example of JBoss EJB 3.0 trailblzer to see how to use annotations in EJB 3.0.
  
   Development and Integration of loose service objects
  
One of the most important advantages of enterprise-level middleware such as Java EE is that developers can use loosely coupled components to develop applications. These components are integrated only through their own commercial interfaces. Therefore, the implementation of these components can be changed without changing the rest of the application. This will make the application stronger, easier to test, and easier to transplant. EJB 3.0 makes it easier to create loose commercial components in pojo.
  
   Session Bean
  
In EJB 3.0 applications, Session Bean is a typical application that combines loose service components. A session bean has at least one interface (that is, a commercial interface) through which other application components obtain services. The following code provides a commercial interface for our investment calculator service. There is only one way to calculate the total investment based on the given starting age, ending age, growth rate, and monthly deposit amount.
  
Public interface calculator {public double calculate (INT start, int end, double growthrate, double saving );}
  
The Session Bean class simply implements commercial interfaces. You must use the stateless or stateful annotation to tell the EJB 3.0 container that the pojo class is a session bean. Stateful session beans maintain the customer's status among different service requests. On the contrary, for stateless session beans, each request is processed by a randomly selected Session Bean instance. These behaviors are consistent with the definitions of stateful and stateless session beans in the EJB 2.1 specification. The EJB 3.0 container calculates when to instantiate the bean object and makes it available through commercial interfaces. The following is the code of the Session Bean implementation class:
  
@ Statelesspublic class calculatorbean implements calculator {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 ;}}
  
You can also specify multiple interfaces for a session bean-one serving the local customer and the other serving the remote customer. You only need to use @ local and @ remote annotations to differentiate them. The following code snippet shows calculatorbean that implements both local and remote interfaces. If you do not have @ local and @ remote annotations, the session bean interface is a local interface by default.
  
@ Stateless @ local ({calculator. class}) @ remote ({remotecalculator. class}) public class calculatorbean 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;} Public String getserverinfo () {return "this is the JBoss EJB 3.0 trailblzer ";}}
  
The Session Bean user obtains a stub (stub) object of the bean through JNDI. The stub object provided by the container implements the commercial interface of the Session Bean. All calls to the stub are directed to the container, and the container calls the interface in the corresponding implementation class. For stateful session beans, you must cache the stub object on the client, so that the container knows to provide the same bean instance for each subsequent call. The following snippet shows how to call the Session Bean. Later, you will learn a simpler way to get the stub object.
  
Initialcontext CTX = new initialcontext (); Cal = (calculator) CTX. lookup (calculator. class. getname (); double res = Cal. calculate (START, end, growthrate, saving );
  
   Session Bean lifecycle management
  
To achieve loose coupling, the application submits the creation, cache, and destruction of Session Bean instances to the EJB 3.0 container (that is, the reverse control design mode ). Applications only deal with bean business interfaces.
  
But what if the application needs better control over the session object? For example, an application may need to initialize database connections when creating session beans, and disable external connections when destroying beans. All of the above may be implemented by defining the lifecycle callback method in the bean class. These methods will be called by the container at different stages of the lifecycle (such as creation or destruction ). With the annotations listed below, EJB 3.0 allows you to specify any method as a callback method. This is different from EJB 2.1. in EJB 2.1, all callback methods must be implemented, even if this is empty. In EJB 3.0, beans can have any number of callback methods with any name.
  
O @ postconstruct: After the bean object is instantiated, the method using this annotation will be called immediately. This annotation applies to stateful and stateless session beans at the same time.
O @ predestroy: This annotation method is called before the container destroys a useless or expired bean instance from its object pool. Applicable to stateful and stateless session beans.
O @ prepassivate: When a stateful Session Bean instance is idle for a long time, the container will deactivate it and save its status. The method for using this annotation is called before the container inactivates the bean instance. Applicable to stateful session beans.
O @ postactivate: when the client uses a deactivated session bean again, a new instance is created and its status is restored. The session bean that uses this annotation is called when bean activation is complete.
O @ init: This annotation specifies the method for initializing stateful session beans. It differs from @ postconstruct in that multiple @ init annotation methods can exist in stateful session bean at the same time, but each be

Note: I am not liable for any of the above content from the Internet.
Article transferred from: http://java.ok6.org/ejb/200610/750.html

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.