Tải bản đầy đủ (.pdf) (473 trang)

Manning spring in action dec 2004 ISBN 1932394354 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.92 MB, 473 trang )

SPRING
IN ACTION
Craig Walls
Ryan Breidenbach

MANNING



Spring in Action
CRAIG WALLS
RYAN BREIDENBACH

MANNING
Greenwich
(74° w. long.)


For online information and ordering of this and other Manning books, please go to
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact:
Special Sales Department
Manning Publications Co.
209 Bruce Park Avenue
Fax: (203) 661-9018
Greenwich, CT 06830
email:
©2005 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by means electronic, mechanical, photocopying, or otherwise, without
prior written permission of the publisher.


Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial
caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy
to have the books they publish printed on acid-free paper, and we exert our best efforts
to that end.

Manning Publications Co.
Copyeditor: Liz Welch
209 Bruce Park Avenue
Typesetter: Denis Dalinnik
Greenwich, CT 06830
Cover designer: Leslie Haimes

ISBN 1-932394-35-4
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – VHG – 09 08 07 06 05


Maisy Grace, see you soon
—C.W.

For my brother, Lee
—R.B.



brief contents
PART 1 SPRING ESSENTIALS ........................................................ 1

1



A Spring jump start

2



Wiring beans

3



Creating aspects

3

42
91

PART 2 SPRING IN THE BUSINESS LAYER .............................. 131
4



Hitting the database


133

5



Managing transactions

6



Remoting

7



Accessing enterprise services

173

207
240

PART 3 SPRING IN THE WEB LAYER ....................................... 267
8




Building the web layer

9



View layer alternatives 319

10



Working with other web frameworks

11



Securing Spring applications 367

vii

269
346



contents
preface xvii
acknowledgments xx

about this book xxiii

PART 1 SPRING ESSENTIALS ............................................... 1

1

A Spring jump start 3
1.1

Why Spring? 5
A day in the life of a J2EE developer

1.2

5



Spring’s pledge 6

What is Spring? 8
Spring modules

9

1.3

Spring jump start 12

1.4


Understanding inversion of control

15

Injecting dependencies 16 IoC in action
IoC in enterprise applications 23


1.5

16

Applying aspect-oriented programming
Introducing AOP
enterprise 30

25

ix



AOP in action

27

25



AOP in the


x

CONTENTS

1.6

Spring alternatives 33
Comparing Spring to EJB 33 Considering other lightweight
containers 36 Web frameworks 38 Persistence
frameworks 40




1.7

2

Summary



40

Wiring beans 42
2.1


Containing your beans

44

Introducing the BeanFactory 44
context 46 A bean’s life 47



Working with an application



2.2

Basic wiring 50
Wiring with XML 54 Adding a bean 55 Injecting
dependencies via setter methods 58 Injecting dependencies
via constructor 65






2.3

Autowiring

69


Handling ambiguities of autowiring 71 Mixing auto and
explicit wiring 72 Autowiring by default 72 To autowire
or not to autowire 72




2.4



Working with Spring’s special beans

73

Postprocessing beans 74 Postprocessing the bean factory 76
Externalizing the configuration 78 Customizing property
editors 80 Resolving text messages 83 Listening for
events 85 Publishing events 86 Making beans aware 87











2.5

3

Summary



90

Creating aspects 91
3.1

Introducing AOP

92

Defining AOP terminology
implementation 95

3.2

93



Spring’s AOP

Creating advice 97
Before advice 99 After advice 101 Around advice 102

Throws advice 104 Introduction advice 105






3.3

Defining pointcuts

105

Defining a pointcut in Spring 105 Understanding
advisors 107 Using Spring’s static pointcuts 107
Using dynamic pointcuts 111 Pointcut operations 113







xi

CONTENTS

3.4

Creating introductions


115

Implementing IntroductionInterceptor 115 Creating an
IntroductionAdvisor 119 Using introduction advice
carefully 120




3.5

Using ProxyFactoryBean 122

3.6

Autoproxying

124

BeanNameAutoProxyCreator 124 DefaultAdvisorAutoProxyCreator 126 Metadata autoproxying 128




3.7

Summary

128


PART 2 SPRING IN THE BUSINESS LAYER ........................... 131

4

Hitting the database 133
4.1

Learning Spring’s DAO philosophy

134

Understanding Spring’s DataAccessException 135
Working with DataSources 137 Consistent DAO
support 139


4.2

Using JDBC with Spring

141

The problem with JDBC code 142
Creating operations as objects 152
keys 155





Using JdbcTemplate 144
Auto-incrementing

4.3

Introducing Spring’s ORM framework support

4.4

Integrating Hibernate with Spring

156

157

Hibernate overview 157 Managing Hibernate
resources 159 Accessing Hibernate through
HibernateTemplate 162 Subclassing
HibernateDaoSupport 163






4.5

Spring and JDO 164
Configuring JDO


4.6

164



Accessing data with JdoTemplate

Spring and iBATIS 166
Setting up SQL Maps 167
Using SqlMapClientTemplate

4.7

Spring and OJB 169

4.8

Summary

168

Setting up OJB’s PersistenceBroker

171

169

165



xii

CONTENTS

5

Managing transactions 173
5.1

Understanding transactions

174

Explaining transactions in only four
words 176 Understanding Spring’s transaction management
support 177 Introducing Spring’s transaction manager 178




5.2

Programming transactions in Spring

5.3

Declaring transactions 183
Understanding transaction attributes
transaction policy 189


5.4

181

185



Declaring a simple

Declaring transactions by method name 191
Using NameMatchTransactionAttributeSource 191
Shortcutting name-matched transactions 194

5.5

Declaring transactions with metadata 195
Sourcing transaction attributes from metadata 196
Declaring transactions with Commons Attributes 197

5.6

Trimming down transaction declarations

201

Inheriting from a parent TransactionProxyFactoryBean
Autoproxying transactions 203


5.7

6

Summary

202

206

Remoting 207
6.1

Spring remoting overview 208

6.2

Working with RMI
Wiring RMI services

6.3

212
212



Exporting RMI services

Remoting with Hessian and Burlap 218

Accessing Hessian/Burlap services 219
functionality with Hessian/Burlap 220

6.4

Using Http invoker

Working with EJBs
Accessing EJBs

6.6

227

224



Exposing bean

Exposing beans as HTTP

226


Developing Spring-enabled EJBs

231

Using JAX-RPC web services 233

Referencing a web service with JAX-RPC
service in Spring 236

6.7



223

Accessing services via HTTP
Services 225

6.5

214

Summary

238

234



Wiring a web


CONTENTS

7


xiii

Accessing enterprise services 240
7.1

Retrieving objects from JNDI

241

Working with conventional JNDI
objects 243

241

7.2

Sending e-mail

7.3

Scheduling tasks



Proxying JNDI

244
248


Scheduling with Java’s Timer 248 Using the Quartz
scheduler 250 Invoking methods on a schedule 254




7.4

Sending messages with JMS 256
Sending messages with JMS templates 257 Consuming
messages 261 Converting messages 263




7.5

Summary

266

PART 3 SPRING IN THE WEB LAYER .................................. 267

8

Building the web layer 269
8.1

Getting started with Spring MVC 270
A day in the life of a request 271 Configuring

DispatcherServlet 272 Spring MVC in a nutshell




8.2

Mapping requests to controllers

275

279

Mapping URLs to bean names 280 Using
SimpleUrlHandlerMapping 281 Using metadata to map
controllers 281 Working with multiple handler
mappings 282






8.3

Handling requests with controllers 283
Writing a simple controller 285 Processing commands 287
Processing form submissions 289 Processing complex forms
with wizards 294 Handling multiple actions in one
controller 301 Working with Throwaway controllers 305









8.4

Resolving views 307
Using template views 308 Resolving view beans
Choosing a view resolver 313


8.5

Using Spring’s bind tag

8.6

Handling exceptions

8.7

Summary

317

314


317

310


xiv

CONTENTS

9

View layer alternatives 319
9.1

Using Velocity templates

321

Defining the Velocity view 321 Configuring the Velocity
engine 322 Resolving Velocity views 323 Formatting
dates and numbers 324 Exposing request and session
attributes 325 Binding form fields in Velocity 326











9.2

Working with FreeMarker

327

Constructing a FreeMarker view 328 Configuring the
FreeMarker engine 329 Resolving FreeMarker views 330
Binding form fields in FreeMarker 330




9.3

Designing page layout with Tiles 332
Tile views

9.4

332



Tile controllers 335

Generating non-HTML output


337

Producing Excel spreadsheets 338 Generating PDF
documents 340 Generating other non-HTML files 343




9.5

10

Summary

344

Working with other web frameworks 346
10.1

Working with Jakarta Struts

347

Registering the Spring plug-in 348 Implementing
Spring-aware Struts actions 348 Delegating actions 350





10.2

Working with Tapestry 352
Replacing the Tapestry Engine
into Tapestry pages 355

10.3

11

357



Summary

363



Loading Spring beans

357

Publishing request handled

Integrating with WebWork
WebWork 1

10.5




Integrating with JavaServer Faces
Resolving variables
events 361

10.4

353

362

XWork/WebWork2 364

365

Securing Spring applications 367
11.1

Introducing the Acegi Security System

368

Security interceptors 369 Authentication managers 370
Access decisions managers 370 Run-as managers 370






CONTENTS

11.2

Managing authentication

371

Configuring a provider manager 371 Authenticating against
a database 373 Authenticating against an LDAP
repository 382 Enabling Single Sign-On with Acegi and
Yale CAS 384






11.3

Controlling access 389
Voting access decisions 389 Deciding how to vote
Handling voter abstinence 392


11.4

Securing web applications


390

392

Proxying Acegi’s filters 394 Enforcing web security 397
Processing a login 400 Setting up the security context 406
Ensuring a secure channel 407 Using the Acegi tag
library 411






11.5

Securing method invocations
Creating a security aspect
metadata 414

11.6

appendix A:

Summary

412

412



416

Spring setup 417

A.1

Downloading Spring 418

A.2

Choosing a distribution

418

A.3

Setting up your project

419

A.4

Building with Ant 420

appendix B:

Spring-related projects

B.1


AppFuse

B.2

Rich Client Project

B.3

Spring.NET

423

index 427

424

424

422

Securing methods using

xv



preface
Software developers need to have a number of traits in order to practice their
craft well. First, they must be good analytical thinkers and problem solvers. A

developer’s primary role is to create software that solves business problems.
This requires analyzing customer needs and coming up with successful, creative solutions.
They also need to be curious. Developments in the software industry are
moving targets, always evolving. New frameworks, new techniques, new languages, and new methodologies are constantly emerging. Each one is a new
tool that needs to be mastered and added to the toolbox, allowing the developer to do his or her job better and faster.
Then there is the most cherished trait of all, “laziness.” The kind of laziness that motivates developers to work hard to seek out solutions with the
least amount of effort. It was with curiosity, a good dose of “laziness,” and all
the analytical abilities we could muster that the two of us struck out together
four years ago to find new ways to develop software.
This was the time when open source software was reaching critical mass in
the Java community. Tons of open source frameworks were blossoming on the
Java landscape. In order to decide to adopt one, it had to hit the sweet spot of
our needs—it had to do 80% of what we needed right out of the box. And for
any functionality that was not right out of the box, the framework needed to
be easily extendible so that functionality too would be included. Extending

xvii


xviii

PREFACE

didn’t mean kludging in some hack that was so ugly you felt dirty afterwards—it
meant extending in an elegant fashion. That wasn’t too much to ask, right?
The first of these frameworks that gained immediate adoption on our team
was Ant. From the get-go, we could tell that Ant had been created by another
developer who knew our pain in building Java applications. From that moment
on, no more javac. No more CLASSPATH. All this with a straightforward (albeit
sometimes verbose) XML configuration. Huzzah! Life (and builds) just got easier.

As we went along, we began adopting more and more tools. Eclipse became our
IDE of choice. Log4J became our (and everybody else’s) default logging toolkit.
And Lucene supplanted our commercial search solution. Each of these tools met
our criteria of filling a need while being easy to use, understand, and extend.
But something was lacking. These great tools were designed to help develop
software, like Ant and Eclipse, or to serve a very specific application need, like
searching in the case of Lucene and logging for Log4J. None of them addressed
the needs at the heart of enterprise applications: persistence, transactions, and
integration with other enterprise resources.
That all changed in the last year or so when we discovered the remarkable
one-two enterprise punch of Spring and Hibernate. Between these two frameworks nearly all of our middle- and data-tier needs were met.
We first adopted Hibernate. It was the most intuitive and feature-rich object/
relational mapping tool out there. But it was by adopting Spring that we really
got our code to look good. With Spring’s inversion of control, we were able to get
rid of all our custom factories and configurers. In fact, that is the reason we first
integrated Spring into our applications. Its wiring allowed us to streamline our
application configurations and move away from homegrown solutions. (Hey,
every developer likes writing his own framework. But sometimes you just have to
let go!)
We quickly discovered a nice bonus: Spring also provided very easy integration with Hibernate. This allowed us to ditch our custom Hibernate integration
classes and use Spring’s support instead. In turn, this led us directly to Spring’s
support for transparent persistence.
Look closely and you will see a pattern here. The more we used Spring, the
more we discovered new features. And each feature we discovered was a pleasure
to work with. Its web MVC framework worked nicely in a few applications. Its AOP
support has been helpful in several places, primarily security. The JDBC support
was quite nice for some smaller programs. Oh yeah, we also use it for scheduling.
And JNDI access. And email integration. When it comes to hitting development
sweet spots, Spring knocks the ball out of the park.



PREFACE

xix

We liked Spring so much, we decided somebody should write a book about it.
Fortunately, one of us had already written a book for Manning and knew how to
go about doing this sort of thing. Soon that “somebody who should write a book”
became us. In taking on this project we are trying to spread the gospel of Spring.
The Spring framework has been nothing but a joy for us to work with—we predict it will be the same for you. And, we hope this book will be a pleasant vehicle
for you to get to that point.


acknowledgments
The creation of this book was not just a two-man job. In addition to the two
authors, a great number of people were involved in many ways to make this
book possible.
First, we’d like to acknowledge the book’s behind-the-scenes crew at Manning Publications: publisher Marjan Bace, his assistant Susan Capparelle, our
editor Jackie Carter, as well as Denis Dalinnik, Leslie Haimes, Mary Piergies,
Liz Welch, Susan Forsyth, and Helen Trimes. We can’t imagine working with a
better team of professionals. You are all very good at what you do and deserve
commendation for producing the best technical books in the world.
We’d also like to thank each of the reviewers who contributed their time to
provide us with the feedback, criticism, and inspiration we needed to shape
the book: Doug Warren, Muhammad Ashikuzzaman, Ryan Cox, Mojahedul
Hasanat, Jack Herrington, Olivier Jolly, William Lopez, Lester Martin, Dmitri
Maximovich, Daniel Miller, Christian Parker, Matthew Payne, and Norman
Richards. Special thanks to Doug Warren for his technical proofread of the
manuscript shortly before it went to press.
And finally, thanks to Rod Johnson and the rest of the Spring team for creating Spring in the first place. We can honestly say that Spring is a pleasure to

work with. You guys rock!

xx


ACKNOWLEDGMENTS

xxi

CRAIG WALLS
I want to thank my beautiful and loving wife, Raymie. You’re the love of my
life, my best friend, and my sweetest dream. Thanks for supporting me and for
your patience, and for putting up with another book project—I promise that
it’s over now.
To my coauthor, Ryan, for getting me started with Spring and for helping me
put together this book to tell everyone else about it.
To my team at Michaels—Ryan, Marianna, Van, Tonji, Jeff, Jim, Don, Carol,
and Leida—thanks for continuing to demonstrate every day what a world-class
software development team is capable of. Now that this book is done, maybe I
won’t have to decline as many lunch invitations!
To my friends and colleagues whom I’ve met and chatted with this year as I
toured the country with the No-Fluff/Just-Stuff software symposiums: Glenn
Vanderburg, Ted Neward, Bruce Tate, Venkat Subramaniam, Ramnivas Laddad,
Dave Thomas, Erik Hatcher, Howard Lewis Ship, Neal Ford, Rick Hightower,
Ben Galbraith, Stuart Halloway, and Matt Raible. And thanks to Jay Zimmerman
for always putting on a great show and inviting me to be a part of it in 2004.
To my friends and neighbors from the ’hood: John, Jennifer, and Tobey for
providing Raymie and me with frequent pizza/movie/sit-on-the-driveway breaks.
Thanks to Dick Wolf for creating “Law & Order,” the TV show that provided
much of the background noise while I was writing.

And everyone else I thanked in XDoclet in Action.
RYAN BREIDENBACH
First, I want to thank my wife Angi. Your limitless patience and encouragement is
what kept me going in this endeavor. I promise you will see me smiling more and
breathing easier now that this is done.
To my daughter Julia, for helping me keep the pressure of writing a book in
perspective. It was always a pleasure to take some time away from writing to visit
the web sites of Elmo’s World and Jo Jo’s Circus.
To my parents, Mark and Lynda, and my brother Lee, for understanding why
I kept my head buried in my laptop when I came to visit. I will be a lot less
stressed during future visits.
To my in-laws, Stephanie and George, for your pep talks and for occasionally
(okay, frequently) babysitting to give Angi and me some time to ourselves.
To my fellow developers out there, Van, Marianna, Tonji, and Jerry, for letting me bounce ideas off you. Sometimes my brain gets going too fast and a swift
kick is in order to get me back in line.


xxii

ACKNOWLEDGMENTS

To my friends and neighbors, Dave, Javier, Alex, Scott and James for helping
me keep my chin up and, every now and then, providing some much needed
… levity.
To the folks at CVSDude. Cool CVS hosting name. Great CVS hosting service.
Finally, to Craig for being a mentor and showing me the ropes of how to write
a book. There is a lot to know and your help made the process that much easier.


about this book

The Spring framework was created with a very specific goal in mind: to make
developing J2EE applications easier. Along the same lines, Spring in Action was
written to make learning how to use Spring easier. Our goal is not to give you
a blow-by-blow listing of Spring APIs. Instead, we hope to present the Spring
framework in a way that is most relevant to a J2EE developer by providing
practical code examples from real-world experience.
Since Spring is a modular framework, this book was written in the same
way. We recognize that not all developers have the same needs. Some may
want to learn the Spring framework from the ground up, while others may
want to pick and choose different topics and go at their own pace. That way,
the book can act as a tool for learning Spring for the first time as well as a
guide and reference for those wanting to dig deeper into specific features.

Roadmap
Spring in Action is divided into three parts, plus two appendices. Each of the
three parts focuses on a general area of the Spring Framework: the core,
middle-tier, and web layer. While each part builds on the previous section,
each is also able to stand on its own, allowing you to dive right into a certain
topic without starting from the beginning.
In part 1, you’ll explore the two core features of the Spring framework:
inversion of control (IoC) and aspect-oriented programming (AOP). This will

xxiii


xxiv

ABOUT THIS BOOK

give you a good understanding of Spring’s fundamentals that will be utilized

throughout the book.
In chapter 1, you’ll be introduced to IoC and AOP and how Spring uses them
to make developing Java applications easier. You will also see how Spring compares to other frameworks, such as EJB, Struts, and PicoContainer.
Chapter 2 takes a more detailed look at how to configure your application
objects using IoC. You will learn how to write loosely coupled components and
wire their dependencies and properties within the Spring container using XML.
Chapter 3 explores how to use Spring’s AOP to decouple cross-cutting concerns, such as security, from the objects that they service. This chapter also sets
the stage for chapter 5, where you’ll learn how to provide declarative transaction
services with Spring’s AOP.
Part 2 builds on the IoC and AOP features introduced in part 1 and shows you
how to apply these concepts to the middle tier of your application.
Chapter 4 covers Spring’s support for data persistence. You’ll be introduced
to Spring’s JDBC support, which helps you remove much of the boilerplate code
associated with JDBC. You’ll also see how Spring integrates with several popular
object-relational mapping frameworks, such as Hibernate, JDO, OJB, and iBATIS
SQL Maps.
Chapter 5 complements chapter 4, showing you how to ensure integrity in
your database using Spring’s transaction support. You will see how Spring uses
AOP to give you the power of declarative transactions without having to use EJBs.
Chapter 6 explores how to expose your application objects as remote services.
You’ll also learn how to transparently access remote services as though they were
any other in your application. Remoting technologies explored will include RMI,
Hessian/Burlap, EJB, web services, and Spring’s own HttpInvoker.
Since most enterprise applications do not exist in a vacuum, chapter 7 shows
you how to integrate with other enterprise services. In this chapter, you will learn
how Spring makes it easy to integrate with mail services, JMS, and even EJBs.
Part 3 moves out of the middle tier and into the presentation layer used in so
many J2EE applications: the Web.
Chapter 8 introduces you to Spring’s own MVC web framework. You will discover how Spring can transparently bind web parameters to your business
objects and provide validation and error handling at the same time. You will

also see how easy it is to add functionality to your web applications using
Spring’s interceptors.
Building on the foundation of Spring MVC, chapter 9 demonstrates how to
move beyond JavaServer Pages and use other templating languages such as


ABOUT THIS BOOK

xxv

Velocity and FreeMarker. In addition, you’ll see how to use Spring MVC to
dynamically produce binary content, such as PDF and Excel documents.
Chapter 10 shows you how to integrate Spring with other web frameworks.
For those of you who have already made an investment in another framework,
Spring provides support for several of the popular web frameworks, including
Struts, Tapestry, JavaServer Faces, and WebWork.
Finally, in chapter 11 you will learn how to apply security to your web applications using the Acegi Security System to provide authentication. In addition, you
will see how to integrate Acegi with your business objects to apply security at the
method level as well.
Appendix A will get you started with your own Spring application, showing
you how to download the Spring framework and configure your Ant build file.
Appendix B introduces you to several other open source frameworks related
to Spring.

Who should read this book
Spring in Action is for all Java developers, but enterprise Java developers will find
it particularly useful. While we will guide you gently through code examples that
build in complexity throughout each chapter, the true power of Spring lies in its
ability to make enterprise applications easier to develop. As a result, enterprise
developers will most fully appreciate the examples presented in this book.

Because a vast portion of Spring is devoted to providing enterprise services,
many parallels can be drawn between Spring and EJB. Any EJB experience you
have will be useful in making comparisons between these two frameworks. Finally,
while this book is not exclusively focused on web applications, a good portion of
it is dedicated to this topic. In fact, the final four chapters demonstrate how Spring
can support the development of your applications’ web layer. If you are a web
application developer, you will find the last part of this book especially valuable.

Code conventions and downloads
There are many code examples in this book. These examples will always appear
in a code font. If there is a particular part of an example we want you to pay
extra attention to, it will appear in a bolded code font. Any class name, method
name, or XML fragment within the normal text of the book will appear in code
font as well.
Many of Spring’s classes have exceptionally long names. Because of this, linecontinuation markers ( ➥) may be included when necessary.


×