Wrox professional java development with the spring framework jul 2005 ISBN 0764574833 - Pdf 53


Professional Java Development with the Spring Framework
byRod Johnsonet al.
John Wiley & Sons 2005 (672 pages)
ISBN:0764574833

Written by the lead developers of the Spring Framework, this authoritative guide shows you not only what
spring can do but why, explaining its functionality and motivation to help you use all parts of the
framework to develop successful applications.

Table of Contents
Professional Java Development with the Spring Framework
Introduction
Chapter 1

- Introducing the Spring Framework

Chapter 2

- The Bean Factory and Application Context

Chapter 3

- Advanced Container Concepts

Chapter 4

- Spring and AOP

Chapter 5



Back Cover
The Spring Framework is a major open source application development framework that makes Java/J2EE
development easier and more productive. This book shows you not only what spring can do but why, explaining its
functionality and motivation to help you use all parts of the framework to develop successful applications.
You will be guided through all the Spring features and see how they form a coherent whole. In turn, this will help
you understand the rationale for Spring’s approach, when to use Spring, and how to follow best practices. All this
is illustrated with a complete sample application. When you finish the book, you will be well equipped to use
Spring effectively in everything from simple Web applications to complex enterprise applications.
What you will learn from this book
The core Inversion of Control container and the concept of Dependency Injection
Spring’s Aspect Oriented Programming (AOP) framework and why AOP is important in J2EE development
How to use Spring’s programmatic and declarative transaction management services effectively
Ways to access data using Spring’s JDBC functionality, iBATIS SQL Maps, Hibernate, and other O/R mapping
frameworks
Spring services for accessing and implementing EJBs
Spring’s remoting framework


Professional Java Development with the Spring
Framework
Rod Johnson
Juergen Hoeller
Alef Arendsen
Thomas Risberg
Colin Sampaleanu
Professional Java™ Development with the Spring Framework
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard

WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY
MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND
STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK
IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING


LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE
IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE
SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES
ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN
THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES
NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE
ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER,
READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE
CHANGED OR DISAPPEARED BETWEEN THEN THIS WORK WAS WRITTEN AND WHEN IT IS
READ.
For general information on our other products and services please contact our Customer Care Department
within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 5724002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade
dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United
States and other countries, and may not be used without written permission. Java is a trademark of Sun
Microsystems, Inc. All other trademarks are the property of their respective owners. Wiley Publishing, Inc.,
is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic books.
About the Authors
Rod Johnson is the founder of the Spring Framework and a well-known expert on Java and J2EE.
Rod holds a Ph.D. from Sydney University. Originally from a C/C++ background, he has been involved with
Java and J2EE since their releases as a developer, architect, and consultant.
He is the author of two of the most popular and influential books on J2EE: Expert One-on-One J2EE

.
To Mas, my nephew, who frequently cheered me up and reminded me of things other than work.
Thomas Risberg is a database developer working for TargetrRx, a pharmaceutical market research
company located in Horsham, Pennsylvania. He has many years of experience working with both large and
small organizations on various database-related projects ranging from simple data entry programs to large
data warehousing implementations. Thomas is a reformed COBOL programmer who came to Java via
Xbase, Visual Basic, and PL/SQL. He served as an Oracle DBA for a couple of years but decided that
software development was really where his heart was.
Thomas has a B.A. degree in information processing from the University of Stockhom, Sweden. He is a
certified Oracle Professional DBA and a Sun Certified Java Programmer and J2EE Architect.
Thomas joined the Spring Framework development team in early 2003 and is mostly involved in evolving
the JDBC layer. His non-computer–related interests are soccer, photography, and travel.
Colin Sampaleanu has had a long and varied career spanning almost two decades—after a childhood
spent tinkering with computers and software—including experience developing for and managing his own
retail software company, other years in the C++ shrinkwrap and enterprise software space, experience with
Java since the early days of the language, and a complete focus on enterprise Java since the late nineties.
Colin is a currently a principal partner at Interface21, which specializes in Spring training, consulting, and
support. Prior to joining Interface21, Colin was Chief Architect at a software incubator / VC.
As a core Spring developer and Interface21 principal, Colin spends much of his time talking and writing
about the benefits of Spring, and promoting agile software development architectures and methodologies
in general.
To Nina, for her continued love and support, and for understanding that despite our best intentions,
in this field 9–5 is often just the first half of the workday. To Alec and Maia, for their simple
innocence and joy, and for reminding me that there are other things in life besides computers.
Credits
Executive Editor
Robert Elliott
Development Editor
Adaobi Obi Tulton
Technical Editors

Thanks to Ben Alex, lead developer of Acegi Security for Spring, for contributing most of the material on
Spring security. Mark Pollack, Spring developer and lead of Spring.NET, also kindly contributed valuable
material relating to
Spring's services for JMS. Dmitriy Kopylenko, also a Spring developer, helped with UML diagrams and
examples for the AOP chapter.
Finally, thanks to the reviewers—especially Peter den Haan and Aleksander Seovic—for their attention to
detail and many valuable suggestions.
Juergen Hoeller: I thank my co-authors, our reviewers, and our editor; it has been a pleasure working with
you. A special thank you goes to Peter den Haan for his extraordinarily thorough chapter reviews. Last but
not least, I express my gratitude to the entire Spring community: Without your active participation, the
Spring project would not be what it is today.
A. Arendsen: I thank all my co-workers at JTeam for their support. Special thanks to Bram Smeets and
Arjen Poutsma for providing valuable content on various topics. I also owe a lot to Joost, the chap I
originally started JTeam with. Without him I couldn't have found the time to contribute to this book. I also
want to express my gratitude to Goof Kerling, who taught me a great deal about programming, how to do it
the right way, and life in general. Thanks to Lars for cooking once every month, providing me with a place
to stay until my house was finished, and joining me for the occasional beer. Also, thanks to my family for
their support and the technical editors for thoroughly reviewing the content and for pointing out that Dutch
isn't the most widely used language in the world.
Thomas Risberg: I thank the entire Spring community—without you, neither the project nor this book
would be what it is today.
Colin Sampaleanu: I thank my co-authors, my partners at Interface21, and the Spring team for setting the
bar so high. It's always a pleasure working with you. I'm grateful for the many colleagues over the years
who by being passionate about the art of software development have helped keep my own interest high. I
also thank my technical reviewers, Peter den Haan, Qi Zhang, and Jim Leask, who provided much
valuable feedback.


Introduction
The Spring Framework is a major open source application development framework that makes Java/J2EE

they form a coherent whole.
Why Spring does what it does. We discuss the motivation behind many Spring features and the
rationale for Spring's approach.
When to use Spring features, and about best practices when using Spring.
We cover the following areas of Spring, with the background discussion necessary to put the Spring
functionality in context:
The core Inversion of Control container and the concept of Dependency Injection that underpins it.
Spring's lightweight container provides sophisticated configuration management, and a flexible
backbone within which other services can be used.
Spring's Aspect-Oriented Programming (AOP) framework and why AOP is important in J2EE
development. Together with Spring's Dependency Injection capabilities, Spring AOP enables a POJO
programming model, in which application code has minimal dependencies on Spring APIs, even when
it enjoys Spring services.
Spring's approach to service abstraction, and the goals it achieves.
Transaction management: Core concepts, Spring's programmatic and declarative transaction
management services, and how to use them effectively.
Data access using Spring: You'll see how Spring provides a sophisticated, consistent abstraction over
a variety of popular data access technologies. We'll look in detail at how to access data using Spring's
JDBC functionality, iBATIS SQL Maps, and the Hibernate O/R mapping framework. You will gain a
solid conceptual understanding of Spring data access that is applicable to other supported
persistence APIs such as TopLink.
Spring's MVC web framework. Three chapters provide in-depth information about the motivation for
Spring's MVC framework, how it compares with other popular web application frameworks such as
Struts, and how to use it in scenarios from basic to advanced. You will also see how to use Spring
MVC to generate custom content types.
Spring services for exposing and accessing remote services. Spring provides a unique remoting
framework that works over a variety of protocols, but is entirely POJO-based.
Spring services for accessing and implementing EJBs.
Spring services relating to JMS.
Spring's integration with the open source Quartz scheduler and other popular open source and

Recommended Reading
Throughout the book we recommend further reading that will help you get a deeper grasp of concepts
important to Spring development, such as Aspect-Oriented programming (AOP).
You may find it helpful to read J2EE without EJB (Johnson/Hoeller, Wrox, 2004), which provides a detailed
discussion of the architectural rationale for lightweight containers such as Spring. However, this book is not
purely a sequel to that book and can be understood entirely on its own.
There are many Spring Framework resources online. You should find the following particularly helpful:
The Spring Home page (www.springframework.org): Portal for most Spring-related information,
including the reference documentation and downloads.
Spring Forums (forum.springframework.org): The place to go to ask questions about Spring. The
Spring community is generally very welcoming and helpful.


What You Need to Use This Book
To run the sample application and examples, you will need:
The Spring Framework version 1.2 or later.
A J2EE web container or/and application server. We used Tomcat 5 where only a web container was
required, and WebLogic 8.1 where an application server was required. However, Spring is designed
for portability between application servers, and we also tested our code on other products. Thus you
do not need to use any particular server product; you can use whatever product you are most familiar
and comfortable with.
A relational database and appropriate JDBC drivers. You should be able to modify our DDL fairly
easily to work with the database of your choice.
The Hibernate O/R mapping framework, version 3.0, available from www.hibernate.org.
Various third-party libraries, including Jakarta Commons Logging. The necessary JAR files are
included with the full Spring distribution; see documentation with Spring for details.
The JUnit testing tool, ideally integrated with your IDE.
The popular Jakarta Ant build tool.
All this software is open source or free for developer use.
We recommend a good Java IDE with refactoring support, such as Eclipse or IntelliJ IDEA. Such tools

We show keyboard strokes like this: Ctrl+A.
We show filenames, URLs, and code within the text like so: persistence.properties
We present code in two different ways:
In code examples we highlight new and important code with a gray background.
The gray highlighting is not used for code that's less important in the present
context, or has been shown before.


Source Code
As you work through the examples in this book, you may choose either to type in all the code manually or
to use the source code files that accompany the book. All of the source code used in this book is available
for download at www.wrox.com. Once at the site, simply locate the book's title (either by using the Search
box or by using one of the title lists) and click the Download Code link on the book's detail page to obtain
all the source code for the book.
Because many books have similar titles, you may find it easiest to search by ISBN; this book's ISBN
is 0-7645-7483-3.
Once you download the code, just decompress it with your favorite compression tool. Alternatively, go to
the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the
code available for this book and all other Wrox books.


Errata
We make every effort to ensure that there are no errors in the text or in the code. However, no one is
perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty
piece of code, we would be very grateful for your feedback. By sending in errata, you may save another
reader hours of frustration and at the same time help us provide even higher quality information.
To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or
one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view
all errata that has been submitted for this book and posted by Wrox editors. A complete book list including
links to each book's errata is also available at www.wrox.com/misc-pages/booklist.shtml.

Chapter 1: Introducing the Spring Framework
Why Spring?
The Spring Framework is an open source application framework that aims to make J2EE development
easier. In this chapter we'll look at the motivation for Spring, its goals, and how Spring can help you
develop high-quality applications quickly.
Important

Spring is an application framework. Unlike single-tier frameworks such as Struts or
Hibernate, Spring aims to help structure whole applications in a consistent, productive
manner, pulling together best-of-breed single-tier frameworks to create a coherent
architecture.

Problems with the Traditional Approach to J2EE
Since the widespread implementation of J2EE applications in 1999/2000, J2EE has not been an
unqualified success in practice. While it has brought a welcome standardization to core middle- tier
concepts such as transaction management, many — perhaps most — J2EE applications are overcomplex, take excessive effort to develop, and exhibit disappointing performance. While Spring is
applicable in a wide range of environments — not just server-side J2EE applications — the original
motivation for Spring was the J2EE environment, and Spring offers many valuable services for use in J2EE
applications.
Experience has highlighted specific causes of complexity and other problems in J2EE applications. (Of
course, not all of these problems are unique to J2EE!) In particular:
J2EE applications tend to contain excessive amounts of "plumbing" code. In the many code
reviews we've done as consultants, time and time again we see a high proportion of code that doesn't
do anything: JNDI lookup code, Transfer Objects, try/catch blocks to acquire and release JDBC
resources. . . . Writing and maintaining such plumbing code proves a major drain on resources that
should be focused on the application's business domain.
Many J2EE applications use a distributed object model where this is inappropriate. This is one
of the major causes of excessive code and code duplication. It's also conceptually wrong in many
cases; internally distributed applications are more complex than co-located applications, and often
much less performant. Of course, if your business requirements dictate a distributed architecture, you

framework is usually much more flexible at runtime than generated code; it should be possible to configure
the behavior of one piece of code in the framework, rather than change many generated classes. Code
generation also poses problems for round-tripping in many cases. A well-conceived framework can also
offer a coherent abstraction, whereas code generation is typically just a shortcut that fails to conceal
underlying complexities during the whole project lifecycle. (Often complexities will re-emerge damagingly
during maintenance and troubleshooting.)
A framework-based approach recognizes the fact that there is a missing piece in the J2EE jigsaw: the
application developer's view. Much of what J2EE provides, such as JNDI, is simply too low level to be a
daily part of programmer's activities. In fact, the J2EE specifications and APIs can be judged as far more
successful, if one takes the view that they do not offer the developer a programming model so much as
provide a solid basis on which that programming model should sit. Good frameworks supply this missing
piece and give application developers a simple, productive, abstraction, without sacrificing the core
capability of the platform.
Important Using J2EE "out of the box" is not an attractive option. Many J2EE APIs and services are
cumbersome to use. J2EE does a great job of standardizing low-level infrastructure,
solving such problems as how can Java code access transaction management without
dealing with the details of XA transactions. But J2EE does not provide an easily usable
view for application code.
That is the role of an application framework, such as Spring.
Recognizing the importance of frameworks to successful J2EE projects, many developers and companies
have attempted to write their own frameworks, with varying degrees of success. In a minority of cases, the
frameworks achieved their desired goals and significantly cut costs and improved productivity. In most
cases, however, the cost of developing and maintaining a framework itself became an issue, and
framework design flaws emerged. As the core problems are generic, it's much preferable to work with a
single, widely used (and tested) framework, rather than implement one in house. No matter how large an
organization, it will be impossible to achieve a degree of experience matching that available for a product
that is widely used in many companies. If the framework is open source, there's an added advantage in
that it's possible to contribute new features and enhancements that may be adopted. (Of course it's
possible to contribute suggestions to commercial products, but it's typically harder to influence successful
commercial products, and without the source code it's difficult to make equally useful contributions.) Thus,

application code needed to be aware of Avalon APIs.
Important A framework can only be as good as the programming model it provides. If a framework
imposes too many requirements on code using it, it creates lock-in and — even more
important — constrains developers in ways that may not be appropriate. The application
developer, rather than framework designer, often has a better understanding of how code
should be written.
Yet a framework should provide guidance with respect to good practice: It should make the
right thing easy to do. Getting the right mixture of constraint and freedom is the key
challenge of framework design, which is as much art as science.
Given this history, the emergence of a number of lightweight frameworks was inevitable. These aim to
provide many of the services of "out of the box" J2EE in a simpler, more manageable manner. They aim to
do their best to make the framework itself invisible, while encouraging good practice. Above all, they aim to
enable developers to work primarily with POJOs, rather than special objects such as EJBs.
As the name implies, lightweight frameworks not only aim to reduce complexity in application code, but
avoid unnecessary complexity in their own functioning. So a lightweight framework won't have a high
startup time, won't involve huge binary dependencies, will run in any environment, and won't place
obstacles in the way of testing.
While "old J2EE" was characterized by high complexity and a welter of questionable "design patterns" to
give it intellectual respectability, lightweight J2EE is about trying to find the "simplest thing that can possibly
work": wise advice from the XP methodology, regardless of whether you embrace XP practices overall.
Important

While all the lightweight frameworks grew out of J2EE experience, it's important to note
that none of them is J2EE-specific. A lightweight container can be used in a variety of
environments: even in applets.
For example, the Spring Rich Client project demonstrates the value of the Spring model
outside the server environment, in rich client applications.

Enter Spring
Spring is both the most popular and most ambitious of the lightweight frameworks. It is the only one to

features can also be used with other web frameworks such as Struts or JSF.
Simplification for working with JNDI, JTA, and other J2EE APIs: Spring can help remove the
need for much of the verbose, boilerplate code that "doesn't do anything." With Spring, you can
continue to use JNDI or EJB, if you want, but you'll never need to write another JNDI lookup. Instead,
simple configuration can result in Spring performing the lookup on your behalf, guaranteeing that
resources such as JNDI contexts are closed even in the event of an exception. The dividend is that
you get to focus on writing code that you need to write because it relates to your business domain.
Lightweight remoting: Spring provides support for POJO-based remoting over a range of protocols,
including RMI, IIOP, and Hessian, Burlap, and other web services protocols.
JMS support: Spring provides support for sending and receiving JMS messages in a much simpler
way than provided through standard J2EE.
JMX support: Spring supports JMX management of application objects it configures.
Support for a comprehensive testing strategy for application developers: Spring not only helps
to facilitate good design, allowing effective unit testing, but provides a comprehensive solution for
integration testing outside an application server.


Spring's Values
To make the most effective use of Spring, it's important to understand the motivation behind it. Spring
partly owes its success to its being based on a clear vision, and remaining true to that vision as its scope
has expanded.
The key Spring values can be summarized as follows:
Spring is a non-invasive framework. This is the key departure from most previous frameworks.
Whereas traditional frameworks such as EJB or Apache Avalon force application code to be aware of
the framework, implementing framework-specific interfaces or extending framework- specific classes,
Spring aims to minimize the dependence of application code on the framework. Thus Spring can
configure application objects that don't import Spring APIs; it can even be used to configure many
legacy classes that were written without any knowledge of Spring. This has many benefits. For
example:
Application code written as part of a Spring application can be run without Spring or any other


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status