1. Trang chủ
  2. » Khoa Học Tự Nhiên

Professional java development with the spring framework (200

1,2K 285 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.167
Dung lượng 4,61 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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 d

Trang 1

Professional Java Development with the Spring Framework

Trang 3

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

Trang 4

Spring services for accessing and implementing EJBs

Spring’s remoting framework

Trang 5

Professional Java Development with the Spring Framework

Trang 6

Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923,(978) 750-8400, fax (978) 646-8600 Requests to the Publisher for

permission should be addressed to the Legal Department, Wiley

Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317)572-3447, fax (317) 572-4355, or online at

http://www.wiley.com/go/permissions

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER

AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIESWITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THECONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL

WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OFFITNESS FOR A PARTICULAR PURPOSE NO WARRANTY MAY BECREATED OR EXTENDED BY SALES OR PROMOTIONAL

MATERIALS THE ADVICE AND STRATEGIES CONTAINED HEREINMAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK IS

SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOTENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER

PROFESSIONAL SERVICES IF PROFESSIONAL ASSISTANCE ISREQUIRED, THE SERVICES OF A COMPETENT PROFESSIONALPERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NORTHE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING

HEREFROM THE FACT THAT AN ORGANIZATION OR WEBSITE ISREFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIALSOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THEAUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE

Trang 7

RECOMMENDATIONS IT MAY MAKE FURTHER, READERS SHOULD

BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAYHAVE CHANGED OR DISAPPEARED BETWEEN THEN THIS WORKWAS 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) 572-4002

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 UnitedStates 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 Somecontent that appears in print may not be available in electronic books

played a major role in the rise of "agile" J2EE, and the move away fromoverly complex traditional J2EE architecture

Rod is co-lead of the Spring Framework He is a popular conferencespeaker and regularly appears at leading Java events in the US, Europe,

Trang 8

He also has wide consulting experience in banking and finance,

insurance, software, and media He is CEO of Interface21

(www.interface21.com), a consultancy devoted to providing expertJ2EE and Spring Framework services He is actively involved with clientprojects as well as Spring development

For Kerry.

Juergen Hoeller is co-founder of Interface21, the company providing

commercial Spring services from the source He is a key driver of Springdevelopment and has been release manager since Spring's inception.His special interests and responsibilities in the project cover a wide

variety of topics, from the core container to transaction management,data access, and lightweight remoting

Alef Arendsen studied computer sciences at the University of Utrecht.

Later, also in Utrecht, Alef started his first company After this turned out

to be too little a challenge, Alef went to work for SmartHaven, an

Amsterdam-based VC- funded company providing J2EE components forknowledge management applications He was responsible for

Trang 9

implementations Thomas is a reformed COBOL programmer who came

to Java via Xbase, Visual Basic, and PL/SQL He served as an OracleDBA for a couple of years but decided that software development wasreally 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 aSun Certified Java Programmer and J2EE Architect

Thomas joined the Spring Framework development team in early 2003and 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 ownretail software company, other years in the C++ shrinkwrap and

enterprise software space, experience with Java since the early days ofthe language, and a complete focus on enterprise Java since the latenineties

Colin is a currently a principal partner at Interface21, which specializes inSpring training, consulting, and support Prior to joining Interface21, Colinwas Chief Architect at a software incubator / VC

As a core Spring developer and Interface21 principal, Colin spends much

Trang 10

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.

Trang 11

Thanks to Ben Alex, lead developer of Acegi Security for Spring, for

contributing most of the material on Spring security Mark Pollack, Springdeveloper 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

A Arendsen: I thank all my co-workers at JTeam for their support.

Special thanks to Bram Smeets and Arjen Poutsma for providing valuablecontent on various topics I also owe a lot to Joost, the chap I originallystarted JTeam with Without him I couldn't have found the time to

Trang 12

Kerling, who taught me a great deal about programming, how to do it theright 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 theirsupport and the technical editors for thoroughly reviewing the content andfor pointing out that Dutch isn't the most widely used language in theworld

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 pleasureworking with you I'm grateful for the many colleagues over the years who

by being passionate about the art of software development have helpedkeep my own interest high I also thank my technical reviewers, Peterden Haan, Qi Zhang, and Jim Leask, who provided much valuable

feedback

Trang 13

The Spring Framework is a major open source application developmentframework that makes Java/J2EE development easier and more

productive

Spring offers services that you can use in a wide range of environments,from applets and standalone clients through web applications running in

a simple servlet engine to complex enterprise applications running in afull-blown J2EE application server Spring enables a POJO programmingmodel that decouples your code from its environment, protecting yourinvestment in the face of change Spring works on JDK 1.3 and later,taking advantage of JDK 1.4 and 1.5 features if available Spring's J2EEservices run on J2EE 1.2 and later

This book will show you how you can use all the major parts of Spring to

help you develop successful applications You'll learn not just what Spring does, but why You will gain insight into best practices when using the

framework, and you will see a complete sample application

Trang 14

This book is for Java/J2EE architects and developers who want to gain adeep knowledge of the Spring Framework in order to use it effectively inapplications from simple web applications up to complex enterprise

applications

If you're new to Spring, you will still be able to work your way through thisbook However, the coverage of advanced topics will ensure that evenexperienced Spring users will find information to help them use Springeffectively You will probably want to keep this book on your desk forreference as you develop applications using Spring

Trang 15

This book covers all major parts of the Spring framework, explaining theframework's functionality and motivation It aims to equip you to

implement advanced applications using Spring

Trang 16

sophisticated, consistent abstraction over a variety of popular

Trang 17

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-depthinformation about the motivation for Spring's MVC framework,how it compares with other popular web application frameworkssuch as Struts, and how to use it in scenarios from basic to

advanced You will also see how to use Spring MVC to generatecustom content types

Spring services for exposing and accessing remote services.Spring provides a unique remoting framework that works over avariety 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 andother popular open source and commercial products

How Spring can be used in the design and implementation of acomplete application, through our sample application

Effective testing strategies for Spring applications One of themajor advantages of a sophisticated Dependency Injection

Trang 18

OO design and architectural practice

Trang 19

This book assumes a working knowledge of core features such as JDBC.Chapters related to J2EE topics such as EJB and JMS assume a basicgrounding in those areas However, we provide suggestions on furtherreading at appropriate points, so don't worry too much now if you're notsure your knowledge is deep enough

We assume sound knowledge of OO design and Java language featuresincluding reflection, inner classes, and dynamic proxies

Existing Spring Framework knowledge is not required

We assume a basic knowledge of SQL and relational database concepts

An understanding of object relational mapping (ORM) is helpful but notessential

If you've used a MVC web framework such as Struts, you will probablygrasp the web content more quickly However, we begin our coverage ofSpring MVC with a discussion of the concepts behind MVC web

frameworks

Trang 20

Throughout the book we recommend further reading that will help you get

a deeper grasp of concepts important to Spring development, such asAspect-Oriented programming (AOP)

The Spring Home page (www.springframework.org): Portalfor most Spring-related information, including the reference

documentation and downloads

Spring Forums (forum.springframework.org): The place to go toask questions about Spring The Spring community is generallyvery welcoming and helpful

Trang 21

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, availablefrom www.hibernate.org

Various third-party libraries, including Jakarta Commons Logging.The necessary JAR files are included with the full Spring

never need to edit XML content purely by hand.

Trang 22

The sample application for this book is an online ticketing application: aweb application that works against a relational database This applicationuses JSPs to generate web content; Spring's MVC web framework toimplement the web tier; Spring to configure middle tier objects and makethem transactional; and a mix of Hibernate and JDBC to access and

update relational data We use Spring's data access abstraction to

conceal use of Hibernate behind a portable layer of data access

interfaces We have tested with a choice of popular relational databasesincluding MySQL and Oracle

This application can run in either a web container or on an applicationserver, using either local or global transaction management

The requirements for the sample application are discussed in AppendixA; the implementation is discussed in Chapter 15

This problem domain was first used for the sample application in Expert

One-on-One J2EE Design and Development It has been rewritten for

this book to bring it up to date with the current Spring feature set andcurrent views on best practice for J2EE applications using Spring If youhave the earlier book, you should find the comparison interesting Thepast two to three years have seen many developments in the Java

framework space, so best practice has moved on significantly (not merelyconcerning Spring itself)

Trang 24

As you work through the examples in this book, you may choose either totype 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 availablefor 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 titlelists) and click the Download Code link on the book's detail page to

Trang 25

We make every effort to ensure that there are no errors in the text or inthe 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 ofcode, we would be very grateful for your feedback By sending in errata,you may save another reader hours of frustration and at the same timehelp us provide even higher quality information

To find the errata page for this book, go to www.wrox.com and locatethe title using the Search box or one of the title lists Then, on the bookdetails page, click the Book Errata link On this page you can view allerrata 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

If you don't spot "your" error on the Book Errata page, go to

www.wrox.com/contact/techsupport.shtml and complete theform there to send us the error you have found We'll check the

information and, if appropriate, post a message to the book's errata pageand fix the problem in subsequent editions of the book

Trang 26

For author and peer discussion, join the P2P forums at p2p.wrox.com.The forums are a Web-based system for you to post messages relating

to Wrox books and related technologies and interact with other readersand technology users The forums offer a subscription feature to emailyou topics of interest of your choosing when new posts are made to theforums Wrox authors, editors, other industry experts, and your fellowreaders are present on these forums

At http://p2p.wrox.com you will find a number of different forumsthat will help you not only as you read this book but also as you developyour own applications To join the forums, just follow these steps:

1 Go to p2p.wrox.com and click the Register link

2 Read the terms of use and click Agree

3 Complete the required information to join as well as any

optional information you wish to provide and click Submit

4 You will receive an email with information describing how toverify your account and complete the joining process

You can read messages in the forums without joining P2P, but in

order to post your own messages, you must join.

Once you join, you can post new messages and respond to messagesother users post You can read messages at any time on the Web If youwould like to have new messages from a particular forum emailed to you,click the Subscribe to this Forum icon by the forum name in the forumlisting

For more information about how to use the Wrox P2P, be sure to read theP2P FAQs for answers to questions about how the forum software works

as well as many common questions specific to P2P and Wrox books Toread the FAQs, click the FAQ link on any P2P

Trang 27

Chapter 1: Introducing the Spring Framework

Trang 28

The Spring Framework is an open source application framework thataims to make J2EE development easier In this chapter we'll look at themotivation for Spring, its goals, and how Spring can help you develophigh-quality applications quickly

Important Spring is an application framework Unlike single-tier

frameworks such as Struts or Hibernate, Spring aims tohelp structure whole applications in a consistent,

tier frameworks to create a coherent architecture

productive manner, pulling together best-of-breed single-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 over- complex, take excessive effort to develop, and exhibit

disappointing performance While Spring is applicable in a wide range ofenvironments — not just server-side J2EE applications — the originalmotivation for Spring was the J2EE environment, and Spring offers manyvaluable 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 areunique to J2EE!) In particular:

Trang 29

without a compelling reason

The EJB component model is unduly complex EJB was

conceived as a way of reducing complexity when implementingbusiness logic in J2EE applications; it has not succeeded in thisaim in practice

EJB is overused EJB was essentially designed for internally

distributed, transactional applications While nearly all non-trivialapplications are transactional, distribution should not be built intothe basic component model

Many "J2EE design patterns" are not, in fact, design

patterns, but workarounds for technology limitations.

Overuse of distribution, and use of complex APIs such as EJB,have generated many questionable design patterns; it's important

to examine these critically and look for simpler, more productive,approaches

J2EE applications are hard to unit test The J2EE APIs, and

especially, the EJB component model, were defined before theagile movement took off Thus their design does not take intoaccount ease of unit testing Through both APIs and implicit

contracts, it is surprisingly difficult to test applications based onEJB and many other J2EE APIs outside an application server Yetunit testing outside an application server is essential to achievehigh test coverage and to reproduce many failure scenarios, such

Trang 30

maintenance process, minimizing unproductive time waiting forredeployment

Certain J2EE technologies have simply failed The main

offender here is entity beans, which have proven little short ofdisastrous for productivity and in their constraints on object

In general, experience has shown that frameworks are better than tool-enabled code generation A good framework is usually much more

flexible at runtime than generated code; it should be possible to configurethe behavior of one piece of code in the framework, rather than changemany 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 wholeproject lifecycle (Often complexities will re-emerge damagingly duringmaintenance and troubleshooting.)

A framework-based approach recognizes the fact that there is a missingpiece in the J2EE jigsaw: the application developer's view Much of whatJ2EE provides, such as JNDI, is simply too low level to be a daily part ofprogrammer's activities In fact, the J2EE specifications and APIs can bejudged as far more successful, if one takes the view that they do not offerthe developer a programming model so much as provide a solid basis onwhich that programming model should sit Good frameworks supply thismissing piece and give application developers a simple, productive,

abstraction, without sacrificing the core capability of the platform

Trang 31

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, theframeworks achieved their desired goals and significantly cut costs andimproved productivity In most cases, however, the cost of developingand maintaining a framework itself became an issue, and frameworkdesign 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 thatmay be adopted (Of course it's possible to contribute suggestions tocommercial products, but it's typically harder to influence successfulcommercial products, and without the source code it's difficult to makeequally useful contributions.) Thus, increasingly, generic frameworkssuch as Struts and Hibernate have come to replace in-house frameworks

in specific areas

The Spring Framework grew out of this experience of using J2EE withoutframeworks, or with a mix of in-house frameworks However, unlike

Struts, Hibernate, and most other frameworks, Spring offers services foruse throughout an application, not merely in a single architectural tier.Spring aims to take away much of the pain resulting from the issues inthe list we've seen, by simplifying the programming model, rather thanconcealing complexity behind a complex layer of tools

Trang 32

while minimizing the complexity encountered byapplication code

The essence of Spring is in providing enterprise services

to Plain Old Java Objects (POJOs) This is particularlyvaluable in a J2EE environment, but application codedelivered as POJOs is naturally reusable in a variety ofruntime environments

Lightweight Frameworks

Some parts of J2EE can properly be termed frameworks themselves.Among them, EJB amounts to a framework because it provides a

structure for application code, and defines a consistent way of accessingservices from the application server However, the EJB framework iscumbersome to use and restrictive The work involved in implementing

an EJB is excessive, given that the architects of J2EE expected that allbusiness logic in J2EE applications would be implemented in EJBs

Developers must cope with three to four Java classes for each EJB; twoverbose deployment descriptors for each EJB JAR file; and excessiveamounts of code for client access to EJBs and EJB access to their

environment The EJB component model, up to and including EJB 2.1,fails to deliver on many of its goals, and fails to deliver a workable

structure for business logic in J2EE applications The EJB Expert Grouphas finally realized this and is attempting an overhaul of the EJB model inEJB 3.0, but we need a solution, right now, and Spring already

demonstrates a far superior one in most cases

Not merely EJB, but the majority of frameworks in the early years of

J2EE, proved to have problems of their own For example, Apache

Avalon offered powerful configuration management and other services,but never achieved widespread adoption, partly because of the learningcurve it required, and because application code needed to be aware ofAvalon APIs

Important A framework can only be as good as the programming

model it provides If a framework imposes too many

Trang 33

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 thekey 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 thebox" J2EE in a simpler, more manageable manner They aim to do theirbest to make the framework itself invisible, while encouraging good

practice Above all, they aim to enable developers to work primarily withPOJOs, rather than special objects such as EJBs

As the name implies, lightweight frameworks not only aim to reducecomplexity in application code, but avoid unnecessary complexity in theirown functioning So a lightweight framework won't have a high startuptime, 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 ofquestionable "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 ofwhether 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 isJ2EE-specific A lightweight container can be used in avariety of environments: even in applets

For example, the Spring Rich Client project demonstrates

the value of the Spring model outside the serverenvironment, in rich client applications

Trang 34

Spring is both the most popular and most ambitious of the lightweightframeworks It is the only one to address all architectural tiers of a typicalJ2EE application, and the only one to offer a comprehensive range ofservices, as well as a lightweight container We'll look at Spring's

modules in more detail later, but the following are the key Spring

modules:

Inversion of Control container: The core "container" Spring

provides, enabling sophisticated configuration management forPOJOs The Spring IoC container can manage fine or coarse-grained POJOs (object granularity is a matter for developers, notthe framework), and work with other parts of Spring to offer

Data access abstraction: Spring encourages a consistent

architectural approach to data access, and provides a unique andpowerful abstraction to implement it Spring provides a rich

hierarchy of data access exceptions, independent of any

particular persistence product It also provides a range of helperservices for leading persistence APIs, enabling developers towrite persistence framework–agnostic data access interfaces andimplement them with the tool of their choice

JDBC simplification: Spring provides an abstraction layer over

JDBC that is significantly simpler and less error-prone to use thanJDBC when you need to use SQL-based access to relationaldatabases

Trang 35

abstraction that can sit over JTA "global" transactions (managed

by an application server) or "local" transactions using the JDBC,Hibernate, JDO, or another data access API This abstractionprovides a consistent programming model in a wide range ofenvironments and is the basis for Spring's declarative and

programmatic transaction management

MVC web framework: Spring provides a request-based MVC

web framework Its use of shared instances of multithreaded

"controllers" is similar to the approach of Struts, but Spring's webframework is more flexible, and integrates seamlessly with theSpring IoC container All other Spring features can also be usedwith 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 cancontinue to use JNDI or EJB, if you want, but you'll never need towrite another JNDI lookup Instead, simple configuration canresult in Spring performing the lookup on your behalf,

guaranteeing that resources such as JNDI contexts are closedeven 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, andHessian, Burlap, and other web services protocols

JMS support: Spring provides support for sending and receiving

JMS messages in a much simpler way than provided throughstandard 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,

Trang 36

allowing effective unit testing, but provides a comprehensivesolution for integration testing outside an application server.

Trang 37

To make the most effective use of Spring, it's important to understand themotivation behind it Spring partly owes its success to its being based on

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 thatdon't import Spring APIs; it can even be used to configure manylegacy classes that were written without any knowledge of Spring.This has many benefits For example:

Application code written as part of a Spring applicationcan be run without Spring or any other container

Lock-in to Spring is minimized For example, you couldmigrate to another lightweight container, or possibly evenreuse application objects in an EJB 3.0 EJB container,which supports a subset of Spring's Dependency

Injection capability

Migration to future versions of Spring is easier The lessyour code depends on the framework, the greater thedecoupling between the implementation of your

application and that of the framework Thus theimplementation of Spring can change significantlywithout breaking your code, allowing the framework to beimproved while preserving backward compatibility

Of course in some areas, such as the web framework,

Trang 38

is concerned

Spring provides a consistent programming model, usable in any environment Many web applications simply don't need to

run on expensive, high-end, application servers, but are better offrunning on a web container such as Tomcat or Jetty It's alsoimportant to remember that not all applications are server-sideapplications Spring provides a programming model that insulatesapplication code from environment details such as JNDI, makingcode less dependent on its runtime context

of throughput and scalability

Spring aims to facilitate Object Oriented design in J2EE

applications You might be asking "How can a J2EE application,

written in Java — an OO language — not be OO?" In reality,many J2EE applications do not deserve the name of OO

applications Spring aims to remove some of the impediments inplace of OO in traditional designs As one of the reviewers on thisbook commented, "The code I've seen from my team in the yearsince we adopted Spring has consistently been better factored,more coherent, loosely coupled and reusable."

Spring aims to facilitate good programming practice, such

as programming to interfaces, rather than classes Use of an

IoC container such as Spring greatly reduces the complexity ofcoding to interfaces, rather than classes, by elegantly concealing

Trang 39

satisfying its configuration requirements Callers using the objectthrough its interface are shielded from this detail, which may

change as the application evolves

Spring promotes pluggability Spring encourages you to think

of application objects as named services Ideally, the

dependencies between such services are expressed in terms ofinterfaces Thus you can swap one service for another withoutimpacting the rest of your application The way in which eachservice is configured is concealed from the client view of thatservice

Spring facilitates the extraction of configuration values from Java code into XML or properties files While some

configuration values may be validly coded in Java, all nontrivialapplications need some configuration externalized from Javasource code, to allow its management without recompilation orJava coding skills (For example, if there is a timeout property on

a particular object, it should be possible to alter its value withoutbeing a Java programmer.) Spring encourages developers toexternalize configuration that might otherwise have been

Trang 40

an architectural backbone, Spring aims to facilitate replaceability

of each layer For example, with a Spring middle tier, you should

be able to switch from one O/R mapping framework to anotherwith minimal impact on business logic code, or switch from, say,Struts to Spring MVC or WebWork with no impact on the middletier

Spring does not reinvent the wheel Despite its broad scope,

Spring does not introduce its own solution in areas such as O/Rmapping where there are already good solutions Similarly, itdoes not implement its own logging abstraction, connection pool,distributed transaction coordinator, remoting protocols, or othersystem services that are already well-served in other products orapplication servers However, Spring does make these existingsolutions significantly easier to use, and places them in a

consistent architectural approach

We'll examine these values later in this chapter and throughout this book.Many of these values are also followed by other lightweight frameworks.What makes Spring unique is that it provides such a consistent approach

to delivering on them, and provides a wide enough range of services to

be helpful throughout typical applications

Ngày đăng: 25/03/2019, 17:09