Demonstrating Spring's Finess

zhaozj2021-02-16  98

PET Store: a counter-esample

The J2EE Pet Store application is an infamous programming example gone bad. It taught thousands of J2EE developers to build poorly designed, poor-performing code. It was also the center of a benchmarking controversy. A respected consulting company called The Middleware Company worked on a benchmark comparing J2EE with Microsoft's .NET platform. As a foundation for the benchmark, they chose the J2EE version of Pet Store. Though they worked hard to tune it, the J2EE version lost badly to the Microsoft .NET version and many criticized the design. I do not intend to lay any blame for this fiasco. Instead, I offer a different interpretation. It's my firm opinion that J2EE, especially EJB, makes it hard to develop clean, high-performance code. Put another way, the Pet Store Benchmark Was A Symptom of A Larger Problem.

After the benchmarking uproar, a number of people showed how to implement Pet Store with easier, simpler technologies. One of the strongest and simplest implementations, by Clinton Begin, used a DAO framework called iBatis instead of full entity beans. Rod Johnson's team converted that Application to Spring, and Now Distributes it with the spring framework. Here all some of the details:

The Spring jPetStore application comes with Spring Versions M4 and beyond. It's a data-driven application with a JDBC DAO layer. It provides alternative frontends for Struts, and the Spring MVC framework. It provides two different models. The simplest uses a single database and Simple JDBC Transactions. The Other Uses JTA Transaction Management Across Multiple Data Stores.

In the following sections, I'll work through the version of the application with the MVC web frontend and simple transactions across one database. I'll focus on the domain model, the single-database DAO layer, simple transactions, and the Spring MVC Frontend. Outstanding Resources Are Available At The Spring Web Site for Those Who Want To Dive Deeper.The Configuration

When learning a Spring application, start with the configuration file;. It shows you the major beans and how the application fits together A Spring configuration file defines the beans in an application context Think of the context as a convenient collection of named resources for an. Application.

. Many J2EE applications keep track of application resources such as connections and the like with singletons When you think about it, a singleton used in this way is not much different from a global variable;. Many Java developers lean on this crutch too often J2EE's alternative is a directory service called JNDI, but it's overkill for many common uses. Spring, instead, uses an application context. Initially, you specify it in a simple XML file, although you can extend Spring to accept other kinds of configuration as well. Here Area's of the things that might go into an Application Context:

Data Sources

A Java Class That Manages Connections, USUALLY IN A Pool.

Dao Layers

IF Your Applications Use a Database, You Probably Want To Isolate The Database Access To One Layer, The Dao. You CAN Access This Layer Through The Application Context.

Persistence managers

Every persistence framework has an object or factory that the application uses to access its features. With Hibernate, it's the session and the session factory. With JDO, it's the persistence manager factory and persistence manager.Transaction policies

You can explicitly Declare The Methods That You Want To Particles In Transactions And The Transaction Manager That You Want To Use to Enforce That Strategy.

Transaction managers

There are many different transaction management strategies within J2EE. For single database applications, Spring lets you use the database's transaction management. For multiple databases or transaction sources, Spring allows JTA instead. You can keep the transaction manager in the application context.

Validation logic

The Spring Framework Uses a Validation Framework Similar To Struts. Spring Lets You Configure Validation Logic Like Any Other Business Component.

Views and controllers

....................

The jPetStore application uses the Spring application context for a data source, the DAO layer, and a transaction strategy. You define what goes into a context within an XML document that lists a series of beans. Each XML configuration file will have a Heading, Followed by a series of Components, and a Footer, Like this:

These are the beans that make up an application context. They represent the top-level beans of an application. (They may create other objects or beans that do not appear in the configuration file.) In this case, you create two beans named MyFirstBean and MySecondBean. Then, you wire them together by specifying MySecondBean as the value for the field myField. When Spring starts, it creates both objects and sets the value of myField. you have access to both of these objects by name whenever you need them through the application context.Let's look at a more concrete example. The jPetStore application has three configuration files for the business logic, the data layer, and the user interface, as in Figure 8-2. A separate Spring configuration file describes each one.

Figure 8-2. The JpetStore Application Has Spring Application Contexts To Match ITS Three Distinct Layers

These configuration files specify the context for the domain model, the data layer, and the presentation layer. Example 8-1 shows part of the application context for the business logic of the jPetStore application. Note that I've shortened the package name from org .springframework.samples.jpetstore ... to jpetstore for simplicity.

EXAMPLE 8-1. ApplicationContext.xml

[1] [2] 3] [4] [5] PROPAGATION_REQUIRED PROPAGATION_REQUIRED PROPAGATION_REQUIRED, read Only here's an expedition of the annotated lines:

[1] Business logic. This section (which includes all bold code) has the core business logic. Validation and the domain model are both considered business components. [2] Validators. This is the validator for Order. Spring calls it whenever a user Submits the Order form and routes to the error page, as required.

[3] Core Business Implementation. This Class Contains The Core Implementation for The Persistent Domain Model. It Contains All of the Dao Objects That You'll See Below.

[4] Properties. Each of your beans has individual properties that may refer to beans you define elsewhere. In this case, the bean properties are individual DAO. Each of these beans is defined in another Spring configuration file.

[5] Transaction declarations. This bean specifies the transaction strategy for the application. In this case, the application uses a transaction manager specified in another Spring configuration file. It declares the methods that should be propagated as transactions. For example, all methods beginning WITH INSERT SHOULD BE PROPAGATED AS Transactions.

In short, this configuration file serves as the glue that holds the business logic of the application together. In the file, you see some references to beans that are not in the configuration file itself, such as the DAO objects. Later on, you ' ll see two other configuration files that define some of the missing beans. One specifies the data access objects with the transaction manager. The other specifies the beans needed by the user interface. It's often better to break configuration files into separate layers, allowing you to configure individual layers as needed. for example, you may want to change strategies for your user interface (say, from Spring MVC web to Struts) or for data access (say, from DAO with one database to DAO spanning two databases with JTA transactions) .If you want to instantiate a bean from your XML context file, it's easy For example, in order to access a bean called myCustomer of type Customer from a file called context.xml, take the following three steps.:

Get an input stream for the XML file with your configuration: InputStream stream = getClass () .getResourceAsStream ( "context.xml"); Create a new Spring bean factory using the input stream: XmlBeanFactory beanFactory = new XmlBeanFactory (stream); Use the Factory to create one of the objects defined in Your .xml file: Customer Cust = (Customer) Beanfactory.getBean (MyCustomer);

Or, if you want Spring to Initialize A Context and the Grab, For Example, Your session fa? Ade, you'd Use code Like this:

protected static final String CONTEXT_FILE = "WEB-INF / applicationContext.xml"; Biz biz; // session fa ade FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext (CONTEXT_FILE);? biz = (Biz) ctx.getBean ( "biz"); It's often better to let go of that control. Usually, you will not have to access the application context directly. The framework does that for you. for example, if you're using servlets, the Spring framework provides a context for each servlet and a catch-all context for servlets. From there, you can usually get the appropriate context information, as you'll see later. Now that you've seen a configuration file representing the jPetStore application, it's time to see how to build the individual elements .

The Domain Model

In keeping with the principles in the book, the foundation of the application is the transparent domain model in Figure 8-3. The domain model contains the business relationships of objects that represent the real world. Pet Store is made up of carts and orders that Contain items.

Figure 8-3. The center of an application is the domain model

The application represents a simple pet store. It consists of a shopping cart containing cart items, which feeds an order containing line items. Items consist of products organized into categories. Each object is a transparent business object implemented as a Java bean with some properties and Some Business Methods. EXAMPLE 8-2 Shows A Cartitem. I've Eliminated The Imports and Package Detail, for BREVITY.

EXAMPLE 8-2. Cartitem.java

[1] public class CartItem implements Serializable {/ * Private Fields * / private Item item; private int quantity; private boolean inStock; / * JavaBeans Properties * / [2] public boolean isInStock () {return inStock;} public void setInStock ( boolean inStock) {this.inStock = inStock;} public Item getItem () {return item;} public void setItem (Item item) {this.item = item;} public int getQuantity () {return quantity;} public void setQuantity ( INT Quantity) {this.quantity = quantity;} [3] public double gettotalprice () {if (item! = null) {Return item.getlistprice () * quantity;}}} / * public methods * / public void incrementQuantity () {Quantity ;}} here's what the annotations mean:

[1] The Spring framework does not force components to inherit from a Spring class. They are fully transparent, and can live outside of the container for testing purposes, or if Spring would some day prove inadequate.

[2] Each Field IS Wrapped with Get and Set Methods, So That Spring Can Configure The THROUGH JAVA REFLECTILE.

[3] Unlike Many EJB Applications, It's Offen Logic Within The Domain Model.

I call this model passive. It's invoked entirely by objects outside of its domain and has coupling only to other objects within the domain. Notice that it is not merely a value object, although it does have private properties and public fields It has business methods to calculate the total price and increment the quantity. This design makes this business object easy to understand and reuse, even though the overall design may evolve. As we move into persistence, you'll see other parts of the model as well.Next week in the conclusion to this two-part series on Spring, excerpted from Better, Faster, Lighter Java, the authors will take you through adding persistence to their Pet Store example, and take a look at the area of ​​presentation logic in the Spring framework.

Bruce A. Tate is a kayaker, mountain biker, and father of two. In his spare time, he is an independent consultant in Austin, Texas. He is the author of four books, including the bestselling Bitter Java, and the recently released Better , Faster, Lighter Java, from o'reilly.

Justin Gehtland Is a Programmer, Author, Mentor and Instructor, Focusing On Real-World SoftWare Applications.

转载请注明原文地址:https://www.9cbs.com/read-11916.html

New Post(0)