Getting Started With Spring Framework, Second Edition J Sharma Ashish Sarin Framework A Hands On Guide To Begin Developing Ap

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 517 [warning: Documents this large are best viewed by clicking the View PDF Link!]

GettingstartedwithSpringFramework
SecondEdition
AshishSarin,JSharma
Tableofcontents
Preface
Howtousethisbook
Conventionsusedinthisbook
Feedbackandquestions
Abouttheauthors
Chapter1IntroductiontoSpringFramework
1-1Introduction
1-2SpringFrameworkmodules
1-3SpringIoCcontainer
1-4BenefitsofusingSpringFramework
Consistentapproachtomanaginglocalandglobaltransactions
Declarativetransactionmanagement
Security
JMX(JavaManagementExtensions)
JMS(JavaMessageService)
Caching
1-5AsimpleSpringapplication
Identifyingapplicationobjectsandtheirdependencies
CreatingPOJOclassescorrespondingtoidentifiedapplicationobjects
Creatingtheconfigurationmetadata
CreatinganinstanceofSpringcontainer
AccessbeansfromtheSpringcontainer
1-6FrameworksbuiltontopofSpring
1-7Summary
Chapter2SpringFrameworkbasics
2-1Introduction
2-2Programmingtointerfacesdesignprinciple
Scenario:Dependentclasscontainsreferencetotheconcreteclassofdependency
Scenario:Dependentclasscontainsreferencetotheinterfaceimplementedbythe
dependency
Spring’ssupportforprogrammingtointerfaces’designapproach
2-3DifferentapproachestoinstantiatingSpringbeans
Instantiatingbeansviastaticfactorymethods
Instantiatingbeansviainstancefactorymethods
2-4Dependencyinjectiontechniques
Setter-basedDI
Constructor-basedDI
2-5Beanscopes
Singleton
Prototype
Choosingtherightscopeforyourbeans
2-6Summary
Chapter3-Configuringbeans
3-1Introduction
3-2Beandefinitioninheritance
MyBank–Beandefinitioninheritanceexample
Whatgetsinherited?
3-3Constructorargumentmatching
Passingsimplevaluesandbeanreferencesusing<constructor-arg>element
Constructorargumentmatchingbasedontype
Constructorargumentmatchingbasedonname
3-4Configuringdifferenttypesofbeanpropertiesandconstructorarguments
Built-inpropertyeditorsinSpring
Specifyingvaluesfordifferentcollectiontypes
Specifyingvaluesforarrays
Defaultcollectionimplementationfor<list>,<set>and<map>elements
3-5Built-inpropertyeditors
CustomCollectionEditor
CustomMapEditor
CustomDateEditor
3-6RegisteringpropertyeditorswiththeSpringcontainer
CreatingaPropertyEditorRegistrarimplementation
ConfiguringtheCustomEditorConfigurerclass
3-7Concisebeandefinitionswithpandcnamespaces
p-namespace
c-namespace
3-8Springsutilschema
<list>
<map>
<set>
<properties>
<constant>
<property-path>
3-9FactoryBeaninterface
MyBankapplicationStoringeventsinthedatabase
MyBank–FactoryBeanexample
AccessingtheFactoryBeaninstance
3-10Summary
Chapter4-Dependencyinjection
4-1Introduction
4-2Innerbeans
4-3Explicitlycontrollingthebeaninitializationorderwithdepends-onattribute
MyBank–implieddependenciesbetweenbeans
Implicitdependencyproblem
4-4Singleton-andprototype-scopedbeansdependencies
Singleton-scopedbeansdependencies
Prototype-scopedbean’sdependencies
4-5Obtainingnewinstancesofprototypebeansinsidesingletonbeans
ApplicationContextAwareinterface
<lookup-method>element
<replaced-method>element
4-6Autowiringdependencies
byType
constructor
byName
default/no
Makingbeansunavailableforautowiring
Autowiringlimitations
4-7Summary
Chapter5-Customizingbeansandbeandefinitions
5-1Introduction
5-2Customizingbeansinitializationanddestructionlogic
MakingSpringinvokecleanupmethodspecifiedbythedestory-methodattribute
Cleanupmethodsandprototype-scopedbeans
Specifyingdefaultbeaninitializationanddestructionmethodsforallbeans
InitializingBeanandDisposableBeanlifecycleinterfaces
JSR250s@PostConstructand@PreDestroyannotations
5-3InteractingwithnewlycreatedbeaninstancesusingBeanPostProcessor
BeanPostProcessorexample–Validatingbeaninstances
BeanPostProcessorexample–Resolvingbeandependencies
BeanPostProcessorbehaviorforFactoryBeans
RequiredAnnotationBeanPostProcessor
DestructionAwareBeanPostProcessor
5-4ModifyingbeandefinitionsusingBeanFactoryPostProcessor
BeanFactoryPostProcessorexample
PropertySourcesPlaceholderConfigurer
PropertyOverrideConfigurer
5-5Summary
Chapter6-Annotation-drivendevelopmentwithSpring
6-1Introduction
6-2IdentifyingSpringcomponentswith@Component
6-3@Autowired-autowiringdependenciesbytype
6-4@Qualifierautowiringdependenciesbyname
6-5JSR330s@Injectand@Namedannotations
6-6JSR250s@Resourceannotation
6-7@Scope,@Lazy,@DependsOnand@Primaryannotations
6-8Simplifyingcomponentconfigurationusing@Valueannotation
6-9ValidatingobjectsusingSpringsValidatorinterface
6-10SpecifyingconstraintsusingJSR303annotations
JSR303supportinSpring
6-11ProgrammaticallyconfiguringSpringbeansusing@Configurationand@Bean
annotations
6-12Summary
Chapter7-DatabaseinteractionusingSpring
7-1Introduction
7-2MyBankapplicationsrequirements
7-3DevelopingtheMyBankapplicationusingSpringsJDBCmodule
Configuringadatasource
CreatingDAOsthatuseSpring’sJDBCmoduleclasses
7-4DevelopingtheMyBankapplicationusingHibernate
ConfiguringSessionFactoryinstance
CreatingDAOsthatuseHibernateAPIfordatabaseinteraction
7-5TransactionmanagementusingSpring
MyBankstransactionmanagementrequirements
Programmatictransactionmanagement
Declarativetransactionmanagement
Spring’ssupportforJTA
7-6Summary
Chapter8-Messaging,emailing,asynchronousmethodexecution,andcachingusing
Spring
8-1Introduction
8-2MyBankapplicationsrequirements
8-3SendingJMSmessages
ConfiguringActiveMQbrokertoruninembeddedmode
ConfiguringaJMSConnectionFactory
SendingJMSmessagesusingJmsTemplate
SendingJMSmessageswithinatransaction
DynamicJMSdestinationsandJmsTemplateconfiguration
JmsTemplateandmessageconversion
8-4ReceivingJMSmessages
SynchronouslyreceivingJMSmessagesusingJmsTemplate
AsynchronouslyreceivingJMSmessagesusingmessagelistenercontainers
8-5Sendingemails
8-6Taskschedulingandasynchronousexecution
TaskExecutorinterface
TaskSchedulerinterface
@Asyncand@Scheduledannotations
8-7Caching
ConfiguringaCacheManager
Cachingannotations-@Cacheable,@CacheEvictand@CachePut
8-8RunningtheMyBankapplication
8-9Summary
Chapter9-Aspect-orientedprogramming
9-1Introduction
9-2AsimpleAOPexample
9-3SpringAOPframework
Proxycreation
expose-proxyattribute
9-4Pointcutexpressions
@Pointcutannotation
executionandargspointcutdesignators
beanpointcutdesignator
Annotations-basedpointcutdesignators
9-5Advicetypes
Beforeadvice
Afterreturningadvice
Afterthrowingadvice
Afteradvice
Aroundadvice
9-6SpringAOP-XMLschema-style
ConfiguringanAOPaspect
Configuringanadvice
Associatingapointcutexpressionwithanadvice
9-7Summary
Chapter10–SpringWebMVCbasics
10-1Introduction
10-2Directorystructureofsamplewebprojects
10-3Understandingthe‘HelloWorldwebapplication
HelloWorldController.java–HelloWorldwebapplicationscontrollerclass
helloworld.jsp–JSPpagethatshowstheHelloWorld!!message
myapp-config.xmlWebapplicationcontextXMLfile
web.xmlWebapplicationdeploymentdescriptor
10-4DispatcherServletthefrontcontroller
AccessingServletContextandServletConfigobjects
10-5Developingcontrollersusing@Controllerand@RequestMappingannotations
Developinga‘HelloWorld’webapplicationusinganannotatedcontroller
10-6MyBankwebapplicationsrequirements
10-7SpringWebMVCannotations-@RequestMappingand@RequestParam
Mappingrequeststocontrollersorcontrollermethodsusing@RequestMapping
@RequestMappingannotatedmethodsarguments
@RequestMappingannotatedmethodsreturntypes
Passingrequestparameterstocontrollermethodsusing@RequestParam
10-8Validation
10-9Handlingexceptionsusing@ExceptionHandlerannotation
10-11LoadingrootwebapplicationcontextXMLfile(s)
10-12Summary
Chapter11–ValidationanddatabindinginSpringWebMVC
11-1Introduction
11-2Addingandretrievingmodelattributesusing@ModelAttributeannotation
Addingmodelattributesusingmethod-level@ModelAttributeannotation
Retrievingmodelattributesusing@ModelAttributeannotation
Requestprocessingand@ModelAttributeannotatedmethods
Behaviorof@ModelAttributeannotatedmethodarguments
RequestToViewNameTranslator
11-3Cachingmodelattributesusing@SessionAttributesannotation
11-4DatabindingsupportinSpring
WebDataBinderdatabinderforwebrequestparameters
ConfiguringaWebDataBinderinstance
Allowingordisallowingfieldsfromdatabindingprocess
InspectingdatabindingandvalidationerrorsusingBindingResultobject
11-5ValidationsupportinSpring
ValidatingmodelattributesusingSpringsValidatorinterface
SpecifyingconstraintsusingJSR303annotations
ValidatingobjectsthatuseJSR303annotations
11-6Springsformtaglibrary
HTML5supportinSpringsformtaglibrary
11-7Summary
Chapter12–DevelopingRESTfulwebservicesusingSpringWebMVC
12-1Introduction
12-2Fixeddepositwebservice
12-3ImplementingaRESTfulwebserviceusingSpringWebMVC
JSON(JavaScriptObjectNotation)
FixedDepositWSwebserviceimplementation
12-4AccessingRESTfulwebservicesusingRestTemplate
12-5ConvertingJavaobjectstoHTTPrequestsandresponsesandviceversausing
HttpMessageConverter
12-6@PathVariableand@MatrixVariableannotations
12-7Summary
Chapter13–MoreSpringWebMVCinternationalization,fileuploadand
asynchronousrequestprocessing
13-1Introduction
13-2Pre-andpost-processingrequestsusinghandlerinterceptors
Implementingandconfiguringahandlerinterceptor
13-3Internationalizingusingresourcebundles
MyBankwebapplicationsrequirements
InternationalizingandlocalizingMyBankwebapplication
13-4Asynchronouslyprocessingrequests
Asynchronousrequestprocessingconfiguration
ReturningCallablefrom@RequestMappingmethods
ReturningDeferredResultfrom@RequestMappingmethods
Settingdefaulttimeoutvalue
Interceptingasynchronousrequests
13-5TypeconversionandformattingsupportinSpring
CreatingacustomConverter
ConfiguringandusingacustomConverter
CreatingacustomFormatter
ConfiguringacustomFormatter
CreatingAnnotationFormatterFactorytoformatonly@AmountFormatannotated
fields
ConfiguringAnnotationFormatterFactoryimplementation
13-6FileuploadsupportinSpringWebMVC
UploadingfilesusingCommonsMultipartResolver
UploadingfilesusingStandardServletMultipartResolver
13-7Summary
Chapter14–SecuringapplicationsusingSpringSecurity
14-1Introduction
14-2SecurityrequirementsoftheMyBankwebapplication
14-3SecuringMyBankwebapplicationusingSpringSecurity
Webrequestsecurityconfiguration
Authenticationconfiguration
SecuringJSPcontentusingSpringSecuritysJSPtablibrary
Securingmethods
14-4MyBankwebapplication-securingFixedDepositDetailsinstancesusingSpring
Security’sACLmodule
Deployingandusingch14-bankapp-db-securityproject
DatabasetablestostoreACLanduserinformation
Userauthentication
Webrequestsecurity
JdbcMutableAclServiceconfiguration
Method-levelsecurityconfiguration
Domainobjectinstancesecurity
ManagingACLentriesprogrammatically
MutableAclandsecurity
14-5Summary
AppendixAImportinganddeployingsampleprojectsinEclipseIDE(orIntelliJ
IDEA)
A-1Settingupthedevelopmentenvironment
A-2ImportingasampleprojectintoEclipseIDE(orIntelliJIDEA)
Importingasampleproject
ConfiguringtheM2_REPOclasspathvariableintheEclipseIDE
A-3ConfiguringEclipseIDEwithTomcat7server
A-4DeployingawebprojectonTomcat7server
RunningtheTomcat7serverinembeddedmode
Preface
Howtousethisbook
Downloadsampleprojects
This book comes with many sample projects that you can download from the following Google Code
project:http://code.google.com/p/getting-started-with-spring-framework-2edition/.Youcandownloadthe
sampleprojectsasasingleZIPfileoryoucancheckoutthesampleprojectsusingSVN.Formoredetails,
refertotheaboveURL.
ImportsampleprojectsintoyourEclipseorIntelliJIDEAIDE
IfyouseeIMPORTchapter<chapter-number>/<projectname>at anypoint while reading the book,
youshouldimportthespecifiedprojectintoyourEclipseorIntelliJIDEAIDE(oranyotherIDEthatyou
areusing).ThesampleprojectsuseMaven3.xbuildtoolforbuildingtheproject;therefore,youllfinda
pom.xmlfileinsideeachoftheprojects.Apom.xmlfileisalsoprovidedattherootofthesourcecode
distribution,whichbuildsalltheprojects.
ReferappendixAtoseethestepsrequiredforimportingandrunningthesampleprojects.
Refertocodeexamples
Each example listing specifies the sample project name (usingProject label) and the location of the
sourcefile(usingSourcelocationlabel).IftheProjectandSourcelocationlabelsarenotspecified,you
canassumethatthecodeshownintheexamplelistingisnotbeingusedanywhereinthesampleprojects,
andithasbeenshownpurelytosimplifyunderstanding.
Conventionsusedinthisbook
Italicshasbeenusedforemphasizingterms
Comic Sans MS has been used for example listings, Java code, configuration details in XML and
propertiesfiles
Comic Sans MS has been used in example listings to highlight important parts of the code or
configuration
ANOTEhighlightsanimportaintpoint.
Feedbackandquestions
You can post your feedback and questions to the authors in the following Google Groups forum:
https://groups.google.com/forum/#!forum/getting-started-with-spring-framework
Abouttheauthors
AshishSarinisaSunCertifiedEnterpriseArchitectwithmorethan14yearsofexperienceinarchitecting
applications.HeistheauthorofSpringRoo1.1Cookbook(byPacktPublishing)andPortletsinAction
(byManningPublications)
JSharmaisafreelanceJavadeveloperwithextensiveexperienceindevelopingSpringapplications.
Chapter1IntroductiontoSpringFramework
1-1Introduction
InthetraditionalJavaenterpriseapplicationdevelopmentefforts,itwasadevelopersresponsibilityto
createwell-structured,maintainableandeasilytestableapplications.Thedevelopersusedmyriaddesign
patternstoaddressthesenon-businessrequirementsofanapplication.Thisnotonlyledtolowdeveloper
productivity,butalsoadverselyaffectedthequalityofdevelopedapplications.
Spring Framework (or ‘Spring in short) is an open source application framework from SpringSource
(http://www.springsource.org) that simplifies developing Java enterprise applications. It provides the
infrastructurefordevelopingwell-structured,maintainableandeasilytestableapplications.Whenusing
Spring Framework, a developer only needs to focus on writing the business logic of the application,
resultinginimproveddeveloperproductivity.YoucanuseSpringFrameworktodevelopstandaloneJava
applications,webapplications,applets,oranyothertypeofJavaapplication.
ThischapterstartsoffwithanintroductiontoSpringFrameworkmodulesanditsbenefits.Attheheartof
SpringFrameworkisitsInversionofControl(IoC)container,whichprovidesdependencyinjection(DI)
feature.  This chapter introduces SpringsDIfeature and IoC container, and shows how to develop a
standalone Java application using Spring. Towards the end of this chapter, we’ll look at some of the
SpringSource’sprojectsthatuseSpringFrameworkastheirfoundation.Thischapterwillsetthestagefor
theremainingchaptersthatdelvedeeperintotheSpringFramework.
NOTEInthisbook,we’lluseanexampleInternetBankingapplication,MyBank,tointroduceSpring
Frameworkfeatures.
1-2SpringFrameworkmodules
SpringFrameworkconsistsofmultiplemodulesthataregroupedbasedontheapplicationdevelopment
featurestheyaddress.ThefollowingtabledescribesthedifferentmodulegroupsinSpringFramework:
Modulegroup Description
Corecontainer
ContainsmodulesthatformthefoundationofSpringFramework.Themodulesinthisgroup
provideSpringsDIfeatureandIoCcontainerimplementation.
AOPand
instrumentation
Contains modules that support AOP (Aspect-oriented Programming) and class
instrumentation.
DataAccess/Integration
Contains modules that simplify interaction with databases and messaging providers. This
modulegroupalsocontainsmodulesthatsupportprogrammaticanddeclarativetransaction
management,andobject/XM Lmappingimplementations,likeJAXBandCastor.
Web Containsmodulesthatsimplifydevelopingwebandportletapplications.
Test Containsasinglemodulethatsimplifiescreatingunitandintegrationtests.
TheabovetableshowsthatSpringcoverseveryaspectofenterpriseapplicationdevelopment;youcan
useSpringfordevelopingwebapplications,accessingdatabases,managingtransactions,creatingunitand
integration tests, and so on. The Spring Framework modules are designed in such a way that youonly
needtoincludethemodulesthatyourapplicationneeds.Forinstance,touseSpringsDIfeatureinyour
application,youonlyneedtoincludethemodulesgroupedunderCorecontainer.Asyouprogressthrough
thisbook,you’llfinddetailsofsomeofthemodulesthatarepartofSpring,andexamplesthatshowhow
theyareusedindevelopingapplications.
Thefollowingfigureshowstheinter-dependenciesofdifferentmodulesofSpring:
Figure1-1Springmodulesinter-dependencies
YoucaninferfromtheabovefigurethatthemodulescontainedintheCorecontainergrouparecentralto
theSpringFramework,andothermodulesdependonit.Equallyimportantarethemodulescontainedin
theAOPandinstrumentationgroupbecausetheyprovideAOPfeaturestoothermodulesintheSpring
Framework.
Now,thatyouhavesomebasicideaabouttheareasofapplicationdevelopmentcoveredbySpring,let’s
lookattheSpringIoCcontainer.
1-3SpringIoCcontainer
AJavaapplicationconsistsofobjectsthatinteractwitheachothertoprovideapplicationbehavior.The
objectswithwhichanobjectinteractsarereferredtoasitsdependencies.Forinstance,ifanobjectX
interactswithobjectsYandZ,thenYandZaredependenciesofobjectX.DIisadesignpatterninwhich
thedependenciesofanobjectaretypicallyspecifiedasargumentstoitsconstructorandsettermethods.
And,thesedependenciesareinjectedintotheobjectwhenitscreated.
In a Spring application, Spring IoC container (also referred to as Spring container) is responsible for
creating application objects and injecting their dependencies. The application objects that the Spring
containercreatesandmanagesarereferredasbeans.AstheSpringcontainerisresponsibleforputting
togetherapplicationobjects,youdon’tneedtoimplementdesignpatterns,likeFactory,ServiceLocator,
andsoon,tocomposeyourapplication.DIisalsoreferredtoasInversionofControl(IoC)becausethe
responsibilityofcreatingandinjectingdependenciesisnotwiththeapplicationobjectbutwiththeSpring
container.
LetssaythattheMyBankapplication(whichisthenameofoursampleapplication)containstwoobjects,
FixedDepositController and FixedDepositService. The following example listing shows that the
FixedDepositControllerobjectdependsonFixedDepositServiceobject:
Examplelisting1-1:FixedDepositControllerclass
publicclassFixedDepositController{
privateFixedDepositServicefixedDepositService;
publicFixedDepositController(){
fixedDepositService=newFixedDepositService();
}

publicbooleansubmit(){
//--savethefixeddepositdetails
fixedDepositService.save(.....);
}
}
In the above example listing, FixedDepositControllers constructor creates an instance of
FixedDepositService which is later used in FixedDepositControllers submit method. As
FixedDepositController interacts with FixedDepositService, FixedDepositService represents a
dependencyofFixedDepositController.
To configure FixedDepositController as a Spring bean, you first need to modify the
FixedDepositControllerclassofexamplelisting1-1suchthatitacceptsFixedDepositServicedependency
as a constructor argument or as a setter method argument. The following example listing shows the
modifiedFixedDepositControllerclass:
Example listing 1-2: FixedDepositController class – FixedDepositService is passed as a constructor
argument
publicclassFixedDepositController{
privateFixedDepositServicefixedDepositService;
publicFixedDepositController(FixedDepositServicefixedDepositService){
this.fixedDepositService=fixedDepositService;
}

publicbooleansubmit(){
//--savethefixeddepositdetails
fixedDepositService.save(.....);
}
}
TheaboveexamplelistingshowsthattheFixedDepositServiceinstanceisnowpassedasaconstructor
argumenttotheFixedDepositControllerinstance.Now,theFixedDepositServiceclasscanbeconfigured
as a Spring bean. Notice that the FixedDepositController class doesnt implement or extend from any
Springinterfaceorclass.
Foragivenapplication,informationaboutapplicationobjectsandtheirdependenciesisspecifiedusing
configurationmetadata. Spring IoC container reads applications configuration metadata to instantiate
applicationobjectsandinjecttheirdependencies.Thefollowingexamplelistingshowstheconfiguration
metadata(inXMLformat)foranapplicationthatconsistsofMyControllerandMyServiceclasses:
Examplelisting1-3:Configurationmetadata
<beans.....>
<beanid="myController"class="sample.spring.controller.MyController">
<constructor-argindex="0"ref="myService"/>
</bean>
<beanid="myService"class="sample.spring.service.MyService"/>
</beans>
Intheaboveexamplelisting,each<bean>elementdefinesanapplicationobjectthatismanagedbythe
Springcontainer,andthe<constructor-arg>elementspecifiesthataninstanceofMyServiceispassedas
anargumenttoMyControllersconstructor.The<bean>elementisdiscussedindetaillaterinthischapter,
andthe<constructor-arg>elementisdiscussedinchapter2.
Spring container reads the configuration metadata (like the one shown in example listing 1-3) of an
application and creates the application objects defined by <bean> elements and injects their
dependencies. Spring container makes use ofJava Reflection API
(http://docs.oracle.com/javase/tutorial/reflect/index.html) to create application objects and inject their
dependencies.ThefollowingfiguresummarizeshowtheSpringcontainerworks:
Figure 1-2 Spring container reads applications configuration metadata and creates a fully-configured
application
TheconfigurationmetadatacanbesuppliedtotheSpringcontainerviaXML(asshowninexamplelisting
1-3),Javaannotations(referchapter6)andalsothroughtheJavacode(referchapter6).
AstheSpringcontainerisresponsibleforcreatingandmanagingapplicationobjects,enterpriseservices
(like transaction management, security, remote access, and so on) can be transparently applied to the
objectsbytheSpringcontainer.TheabilityoftheSpringcontainertoenhancetheapplicationobjectswith
additional functionality makes it possible for you to model your application objects as simple Java
objects(alsoreferredtoasPOJOsorPlainOldJavaObjects).JavaclassescorrespondingtoPOJOs
are referred to as POJO classes, which are nothing but Java classes that dont implement or extend
framework-specificinterfacesorclasses.Theenterpriseservices,liketransactionmanagement,security,
remoteaccess,andsoon,requiredbythesePOJOsaretransparentlyprovidedbytheSpringcontainer.
Now,thatweknowhowSpringcontainerworks,letslookatsomeexamplesthatdemonstratebenefitsof
developingapplicationsusingSpring.
1-4BenefitsofusingSpringFramework
Intheprevioussection,wediscussedthefollowingbenefitsofusingSpring:
§Springsimplifiescomposing Javaapplications bytakingcare ofcreating applicationobjects and
injectingtheirdependencies
§SpringpromotesdevelopingapplicationsasPOJOs
SpringalsosimplifiesinteractionwithJMSproviders,JNDI,MBeanservers,emailservers,databases,
andsoon,byprovidingalayerofabstractionthattakescareoftheboilerplatecode.
Lets take a quick look at a few examples to better understand the benefits of developing applications
usingSpring.
Consistentapproachtomanaginglocalandglobaltransactions
If you are using Spring for developingtransactional applications, you can use Springs declarative
transactionmanagementsupporttomanagetransactions.
ThefollowingexamplelistingshowstheFixedDepositServiceclassofMyBankapplication:
Examplelisting1-4–FixedDepositServiceclass
publicclassFixedDepositService{
publicFixedDepositDetailsgetFixedDepositDetails(.....){.....}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){.....}
}
TheFixedDepositService class is a POJO class that defines methods to create and retrieve details of
fixeddeposits.Thefollowingfigureshowstheformforcreatinganewfixeddeposit:
Figure1-3HTMLformforcreatinganewfixeddeposit
Acustomerentersthefixeddepositamount,tenureandemailidinformationintheaboveformandclicks
theSave button to create a new fixed deposit. The FixedDepositServices createFixedDeposit method
(referexamplelisting1-1)isinvokedtocreatethefixeddeposit.ThecreateFixedDepositmethoddebits
theamountenteredbythecustomerfromhisbankaccount,andcreatesafixeddepositofthesameamount.
LetssaythatinformationaboutthebankbalanceofcustomersisstoredinBANK_ACCOUNT_DETAILS
databasetable,andthefixeddepositdetailsarestoredinFIXED_DEPOSIT_DETAILSdatabasetable.If
a customer creates a fixed deposit of amount x, amount x is subtracted from the
BANK_ACCOUNT_DETAILStable,andanewrecordisinsertedinFIXED_DEPOSIT_DETAILStable
toreflectthenewlycreatedfixeddeposit.IfBANK_ACCOUNT_DETAILStableisnotupdatedoranew
recordisnotinsertedinFIXED_DEPOSIT_DETAILStable,it’llleavethesysteminaninconsistentstate.
ThismeansthecreateFixedDepositmethodmustbeexecutedwithinatransaction.
The database used by the MyBank application represents a transactional resource. In the traditional
approachtoperforma setof databasemodificationsasasingleunitof work,youllfirstdisableauto-
commit mode of JDBC connection, then execute SQL statements, and finally commit (or rollback) the
transaction. The following example listing shows how to manage database transactions in the
createFixedDepositmethodusingthetraditionalapproach:
Examplelisting1-5–ProgrammaticallymanagingdatabasetransactionusingJDBCConnectionobject
importjava.sql.Connection;
importjava.sql.SQLException;
publicclassFixedDepositService{
publicFixedDepositDetailsgetFixedDepositDetails(.....){.....}

publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
Connectioncon=.....;
try{
con.setAutoCommit(false);
//--executeSQLstatementsthatmodifydatabasetables
con.commit();
}catch(SQLExceptionsqle){
if(con!=null){
con.rollback();
}
}
.....
}
}
TheaboveexamplelistingshowsthatthecreateFixedDepositmethodprogrammaticallymanagesdatabase
transactionusingJDBCConnectionobject.Thisapproachissuitableforapplicationscenariosinwhicha
singledatabaseisinvolved.Transactionsthatareresource-specific,likethetransactionassociatedwitha
JDBCConnection,arereferredtoaslocaltransactions.
When multiple transactional resources are involved, JTA (Java Transaction API) is used for managing
transactions.Forinstance,ifyouwanttosendaJMSmessagetoamessagingmiddleware(atransactional
resource)andupdateadatabase(anothertransactionalresource)inthesametransaction,youmustusea
JTA transaction manager to manage transactions. JTA transactions are also referred to asglobal (or
distributed)transactions.TouseJTA,youfetchUserTransactionobject(whichispartofJTAAPI)from
JNDIandprogrammaticallystartandcommit(orrollback)transactions.
As you can see, you can either useJDBC Connection (for local transactions) or UserTransaction (for
globaltransactions)objecttoprogrammaticallymanage transactions.Itisimportanttonotethatalocal
transactioncannot run within a global transaction. This means that if you want database updates in
createFixedDepositmethod(referexamplelisting1-5)tobepartofaJTAtransaction,youneedtomodify
thecreateFixedDepositmethodtousetheUserTransactionobjectfortransactionmanagement.
Spring simplifies transaction management by providing a layer of abstraction that gives aconsistent
approach to managing both local and global transactions.  This means that if you write the
createFixedDepositmethod(referexamplelisting1-5)usingSpringstransactionabstraction,youdont
needtomodifythemethodwhenyouswitchfromlocaltoglobaltransactionmanagement,orviceversa.
Springstransactionabstractionisexplainedinchapter7.
Declarativetransactionmanagement
Springgivesyoutheoptiontousedeclarativetransactionmanagement.Youcanannotateamethodwith
Springs@TransactionalannotationandletSpringhandletransactions,asshownhere:
Examplelisting1-6–@Transactionalannotationusage
importorg.springframework.transaction.annotation.Transactional;
publicclassFixedDepositService{
publicFixedDepositDetailsgetFixedDepositDetails(.....){.....}

@Transactional
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){.....}
}
TheaboveexamplelistingshowsthattheFixedDepositServiceclassdoesntimplementorextendfrom
any Spring-specific interface or class to use Springs transaction management facility. The Spring
Framework transparently provides transaction management feature to @Transactional annotated
createFixedDeposit method. This shows that Spring is a non-invasive framework because it doesnt
require your application objects to be dependent upon Spring-specific classes or interfaces. Also, you
dontneedtodirectlyworkwithtransactionmanagementAPIstomanagetransactions.
Security
Security is an important aspect of any Java application. Spring Security
(http://static.springsource.org/spring-security/site/) is a SpringSources project that is built on top of
SpringFramework.SpringSecurityprovidesauthenticationandauthorizationfeaturesthatyoucanusefor
securingJavaapplications.
Lets say that the following 3 user roles have been identified for the MyBank application:
LOAN_CUSTOMER, SAVINGS_ACCOUNT_CUSTOMER and APPLICATION_ADMIN. A customer
mustbeassociatedwiththeSAVINGS_ACCOUNT_CUSTOMERortheAPPLICATION_ADMINroleto
invokethecreateFixedDepositmethod of FixedDepositService class (refer example listing 1-6). Using
Spring Security youcan easily address this requirementby annotating createFixedDeposit method with
SpringSecuritys@Securedannotation,asshowninthefollowingexamplelisting:
Examplelisting1-7–SecuredcreateFixedDepositmethod
importorg.springframework.transaction.annotation.Transactional;
importorg.springframework.security.access.annotation.Secured;
publicclassFixedDepositService{
publicFixedDepositDetailsgetFixedDepositDetails(.....){.....}
@Transactional
@Secured({"SAVINGS_ACCOUNT_CUSTOMER","APPLICATION_ADMIN"})
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){.....}
}
If you annotate a method with Spring Securitys @Secured annotation, security feature is transparently
applied to the method by the Spring Security framework. The above example listing shows that for
implementingmethod-levelsecurityyoudontneedtoextendorimplementanySpring-specificclassesor
interfaces.Also,youdontneedtowritesecurity-relatedcodeinyourbusinessmethods.
SpringSecurityframeworkisdiscussedindetailinchapter14.
JMX(JavaManagementExtensions)
SpringsJMXsupportsimplifiesincorporatingJMXtechnologyinyourapplications.
LetssaythatthefixeddepositfacilityofMyBankapplicationshouldonlybeavailabletocustomersfrom
9:00 AM to 6:00 PM everyday. To address this requirement, a variable is added to the
FixedDepositServiceclass,whichactsasaflagindicatingwhetherthefixeddepositserviceisactiveor
inactive.ThefollowingexamplelistingshowstheFixedDepositServiceclassthatusessuchaflag:
Examplelisting1-8–FixedDepositServicewithactivevariable
publicclassFixedDepositService{
privatebooleanactive;

publicFixedDepositDetailsgetFixedDepositDetails(.....){
if(active){.....}
}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
if(active){.....}
}
publicvoidactivateService(){
active=true;
}
publicvoiddeactivateService(){
active=false;
}
}
TheaboveexamplelistingshowsthatavariablenamedactiveisaddedtotheFixedDepositServiceclass.
If the value of the active variable is true, the getFixedDepositDetails and createFixedDeposit methods
work as expected. If the value of the active variable is false, the getFixedDepositDetails and
createFixedDeposit methods throw an exception indicating that the fixed deposit service is currently
inactive.TheactivateServiceanddeactivateServicemethodssetthevalueofactivevariabletotrueand
false,respectively.
Now, who calls the activateService and deactivateService methods? Let’s say a separate scheduler
application, Bank App Scheduler, runs at 9:00 AM and 6:00 PM to execute activateService and
deactivateService methods, respectively. The Bank App Scheduler application uses JMX (Java
ManagementExtensions)APItoremotelyinteractwithFixedDepositServiceinstance.
NOTE Refer to the following article to learn more about JMX:
http://docs.oracle.com/javase/tutorial/jmx/index.html.
AsBankAppSchedulerusesJMXtochangethevalueoftheactivevariableoftheFixedDepositService
instance,youneedtoregistertheFixedDepositServiceinstanceasamanagedbean(orMBean)withan
MBean server, and expose FixedDepositService’s activateService and deactivateService methods as
JMXoperations.InSpring,youregisterinstancesofaclasswiththeMBeanserverbyannotatingtheclass
withSprings @ManagedResource annotation, and expose the methods of the class as JMX operations
usingSprings@ManagedOperationannotation.
Thefollowingexamplelistingshowsusageof@ManagedResourceand@ManagedOperationannotations
to register instances of the FixedDepositService class with the MBean server, and to expose its
activateServiceanddeactivateServicemethodsasJMXoperations:
Examplelisting1-9–FixedDepositServiceclassthatusesSpringsJMXsupport
importorg.springframework.jmx.export.annotation.ManagedOperation;
importorg.springframework.jmx.export.annotation.ManagedResource;
@ManagedResource(objectName="fixed_deposit_service:name=FixedDepositService")
publicclassFixedDepositService{
privatebooleanactive;
publicFixedDepositDetailsgetFixedDepositDetails(.....){
if(active){.....}
}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
if(active){.....}
}
@ManagedOperation
publicvoidactivateService(){
active=true;
}
@ManagedOperation
publicvoiddeactivateService(){
active=false;
}
}
The above example listing shows that the FixedDepositService class doesnt directly use JMX API to
registeritsinstanceswiththeMBeanserverandtoexposeitsmethodsasJMXoperations.
JMS(JavaMessageService)
SpringsJMSsupportsimplifiessendingandreceivingmessagesfromJMSproviders.
InMyBankapplication,whenacustomersubmitsarequesttoreceivedetailsoftheirfixeddepositsvia
email, the FixedDepositService sends the request details to a JMS messaging middleware (like
ActiveMQ).Therequestislaterprocessedbyamessagelistener.SpringsimplifiesinteractionwithJMS
providers by providing a layer of abstraction. The following example listing shows how
FixedDepositServiceclasssendsrequestdetailstoaJMSproviderusingSpringsJmsTemplate:
Examplelisting1-10–FixedDepositServicethatsendsJMSmessages
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.jms.core.JmsTemplate;
publicclassFixedDepositService{
@Autowired
privatetransientJmsTemplatejmsTemplate;
.....
publicbooleansubmitRequest(Requestrequest){
jmsTemplate.convertAndSend(request);
}
}
TheaboveexamplelistingshowsthattheFixedDepositServicedefinesavariableoftypeJmsTemplate,
andisannotatedwithSprings@Autowiredannotation.Fornow,youcanassumethatthe@Autowired
annotationprovidesaccesstoaJmsTemplateinstance.TheJmsTemplateinstanceknowsabouttheJMS
destinationtowhichtheJMSmessageistobesent.HowtheJmsTemplateisconfiguredisdescribedin
detail in chapter 8. The FixedDepositServices submitRequest method invokes JmsTemplate’s
convertAndSend method to send request details (represented by Request argument of submitRequest
method)asaJMSmessagetotheJMSprovider.
Onceagain,theaboveexamplelistingshowsthatifyouareusingSpringFrameworktosendmessagesto
JMSproviders,thenyoudontneedtodirectlydealwithJMSAPI.
Caching
Springscacheabstractionprovidesaconsistentapproachtousecachinginyourapplication.
Itscommontousecachingsolutionstoimprovetheperformanceofanapplication.MyBankapplication
usesacachingproducttoimprovetheperformanceofreadoperationsforfixeddepositdetails.Spring
Frameworksimplifiesinteractingwithdifferentcachingsolutionsbyabstractingcaching-relatedlogic.
ThefollowingexamplelistingshowsthattheFixedDepositServicesgetFixedDepositDetailsmethoduses
Springscacheabstractionfeaturetocachefixeddepositdetails:
Examplelisting1-11–FixedDepositServicethatcachesfixeddepositdetails
importorg.springframework.cache.annotation.Cacheable;
publicclassFixedDepositService{

@Cacheable("FixedDeposits")
publicFixedDepositDetailsgetFixedDepositDetails(.....){.....}

publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){.....}
}
In the above example listing, Springs @Cacheable annotation indicates that the fixed deposit details
returned by the getFixedDepositDetails method are cached. If the getFixedDepositDetails method is
invoked with the same argument value(s), the getFixedDepositDetails method is not executed, and the
fixeddepositdetailsarereturnedfromthecache.ThisshowsthatifyouareusingSpringFrameworkyou
dontneedtowritecaching-relatedlogicinyourclasses.Springscacheabstractionisexplainedindetail
inchapter8.
In this section, we saw that Spring Framework simplifies developing enterprise applications by
transparentlyprovidingservicestoPOJOs,thereby shieldingdevelopersfrom lowerlevelAPIdetails.
Spring also provides easy integration with standard frameworks, like Hibernate, iBATIS, Quartz, JSF,
Struts,EJB,andsoon,whichmakesSpringanidealchoiceforenterpriseapplicationdevelopment.
Now,thatwehavelookedatsomeofthebenefitsofusingSpringFramework,letstakealookathowto
developasimpleSpringapplication.
1-5AsimpleSpringapplication
Inthissection,we’lllookatasimpleSpringapplicationthatusesSpringsDIfeature.TouseSpringsDI
featureinanapplication,followthesesteps:
1.identifyapplicationobjectsandtheirdependencies
2.createPOJOclassescorrespondingtotheapplicationobjectsidentifiedinstep1
3.createconfigurationmetadatathatdepictsapplicationobjectsandtheirdependencies
4.createaninstanceofSpringIoCcontainerandpasstheconfigurationmetadatatoit
5.accessapplicationobjectsfromtheSpringIoCcontainerinstance
LetsnowlookatabovementionedstepsinthecontextofMyBankapplication.
Identifyingapplicationobjectsandtheirdependencies
WediscussedearlierthattheMyBankapplicationshowsaformforcreatingafixeddeposit(referfigure
1-3) to its users for creating a fixed deposit. The following sequence diagram shows the application
objects(andtheirinteraction)thatcomeintopicturewhentheusersubmitstheform:
Figure1-4MyBanksapplicationobjectsandtheirdependencies
In the above sequence diagram, FixedDepositController represents a web controller that receives the
requestwhentheformissubmitted.ThefixeddepositdetailsarecontainedintheFixedDepositDetails
object.TheFixedDepositController invokes the createFixedDeposit method of FixedDepositService (a
servicelayerobject).Then,FixedDepositServiceinvokesFixedDepositDaoobject(adataaccessobject)
to save the fixed deposit details in the applications data store. So, we can interpret from the above
diagram that FixedDepositService is a dependency of FixedDepositController object, and
FixedDepositDaoisadependencyofFixedDepositServiceobject.
IMPORT chapter 1/ch01-bankapp-xml (This project shows a simple Spring application that uses
Springs DI feature. To run the application, execute the main method of the MyBankApp class of this
project)
CreatingPOJOclassescorrespondingtoidentifiedapplicationobjects
Onceyouhaveidentifiedapplicationobjects,thenextstep istocreatePOJOclassescorresponding to
these application objects. POJO classes corresponding to the FixedDepositController,
FixedDepositService and FixedDepositDao application objects are available in ch01-bankapp-xml
project.Thech01-bankapp-xmlprojectrepresentsasimplifiedversionofMyBankapplicationthatuses
SpringsDIfeature.Youshouldimportthech01-bankapp-xmlprojectintoyourIDEasintheremaining
stepswe’llbelookingatthefilescontainedinthisproject.
In section 1-3 we discussed that a dependency is passed to an application object as a constructor
argument or as a setter method argument. The following code listing shows that an instance of
FixedDepositService(adependencyofFixedDepositController)ispassedasasettermethodargumentto
theFixedDepositControllerobject:
Examplelisting1-12–FixedDepositControllerclass
Project–ch01-bankapp-xml
Sourcelocation-src/main/java/sample/spring/chapter01/bankapp
packagesample.spring.chapter01.bankapp;
.....
publicclassFixedDepositController{
.....
privateFixedDepositServicefixedDepositService;
.....
publicvoidsetFixedDepositService(FixedDepositServicefixedDepositService){
logger.info("SettingfixedDepositServiceproperty");
this.fixedDepositService=fixedDepositService;
}
.....
publicvoidsubmit(){
fixedDepositService.createFixedDeposit(newFixedDepositDetails(1,10000,
365,"someemail@something.com"));
}
.....
}
In the above example listing, FixedDepositService dependency is passed to FixedDepositController
throughsetFixedDepositServicemethod.We’llsoonseethatthesetFixedDepositServicesettermethodis
invokedbySpring.
NOTE If you look at the FixedDepositController,FixedDepositService and FixedDepositDao classes,
you’ll notice that none of these classes implement any Spring-specific interface or extend from any
Spring-specificclass.
Lets now look at how application objects and their dependencies are specified in the configuration
metadata.
Creatingtheconfigurationmetadata
We saw in section 1-3 that the configuration metadata specifies application objects and their
dependencies, which is read by the Spring container to instantiate application objects and inject their
dependencies.Inthissection,we’llfirstlookatwhatotherinformationiscontainedintheconfiguration
metadata,followedbyanin-depthlookathowconfigurationmetadataisspecifiedinXMLformat.
The configuration metadata specifies information about the enterprise services (like transaction
management,securityandremoteaccess)thatarerequiredbytheapplication.Forinstance,ifyouwant
Spring to manage transactions, you need to configure an implementation of Springs
PlatformTransactionManager interface in the configuration metadata. The PlatformTransactionManager
implementation is responsible for managing transactions (refer chapter 7 to know more about Springs
transactionmanagementfeature).
Ifyourapplicationinteractswithmessagingmiddlewares(likeActiveMQ),databases(likeMySQL),e-
mailservers,andsoon,thenSpring-specificobjectsthatsimplifyinteractingwiththeseexternalsystems
arealsodefinedintheconfigurationmetadata.Forinstance,ifyourapplicationsendsorreceivesJMS
messages from ActiveMQ, then you can configure Springs JmsTemplate class in the configuration
metadata to simplify interaction with ActiveMQ. We saw in example listing 1-10 that if you use
JmsTemplateforsendingmessagestoaJMSprovider,thenyoudon’tneedtodealwithlower-levelJMS
API(referchapter8toknowmoreaboutSpringssupportforinteractingwithJMSproviders).
YoucansupplytheconfigurationmetadatatotheSpringcontainerviaanXMLfileorthroughannotations
inPOJOclasses.StartingwithSpring3.0,youcanalsosupplytheconfigurationmetadatatotheSpring
containerthroughJavaclassesannotatedwithSprings@Configurationannotation.Inthissection,well
seehow configurationmetadata is specifiedinXMLformat.In chapter 6,well see how configuration
metadataissuppliedviaannotationsinPOJOclassesandthrough@ConfigurationannotatedJavaclasses.
You provide the configuration metadata for an application in XML format by creating anapplication
contextXMLfilethatcontainsinformationabouttheapplicationobjectsandtheirdependencies.Example
listing 1-3 showed how an application context XML file looks like. The following XML shows the
application context XML file of MyBank application that consists of FixedDepositController,
FixedDepositService and FixedDepositDao objects (refer figure 1-4 to see how these objects interact
witheachother):
Examplelisting1-13–applicationContext.xml-MyBanksapplicationcontextXMLfile
Project–ch01-bankapp-xml
Sourcelocation-src/main/resources/META-INF/spring
<?xmlversion="1.0"encoding="UTF-8"standalone="no"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<beanid="controller"
class="sample.spring.chapter01.bankapp.FixedDepositController">
<propertyname="fixedDepositService"ref="service"/>
</bean>
<beanid="service"class="sample.spring.chapter01.bankapp.FixedDepositService">
<propertyname="fixedDepositDao"ref="dao"/>
</bean>
<beanid="dao"class="sample.spring.chapter01.bankapp.FixedDepositDao"/>
</beans>
ThefollowingaretheimportantpointstonoteabouttheapplicationcontextXMLfileshownabove:
·The<beans>elementistherootelementoftheapplicationcontextXMLfile,andisdefinedin
spring-beans-4.0.xsdschema(alsoreferredtoasSpringsbeansschema).Thespring-beans-4.0.xsd
schema is contained in spring-beans-4.0.0.RELEASE.jar JAR file that comes with the Spring
Frameworkdistribution.
·Each<bean>elementconfiguresanapplicationobjectthatismanagedbytheSpringcontainer.In
SpringFrameworksterminology,a<bean>elementrepresentsabeandefinition.Theobjectthat
theSpringcontainercreatesbasedonthebeandefinitionisreferredtoasabean.Theidattribute
specifiesauniquenameforthebean,andtheclassattributespecifiesthefully-qualifiedclassname
ofthebean.Youcanalsousethenameattributeof<bean>elementtospecifyaliasesforthebean.
InMyBankapplication,theapplicationobjectsareFixedDepositController, FixedDepositService
andFixedDepositDao;therefore,wehave3<bean>elements-oneforeachapplicationobject.As
application objects configured by <bean> elements are managed by the Spring container, the
responsibility for creating them and injecting their dependencies is with the Spring container.
Insteadofdirectlycreatinginstancesofapplicationobjectsdefinedby<bean>elements,youshould
obtainthemfromtheSpringcontainer.Laterinthissection,welllookathowtoobtainapplication
objectsmanagedbySpringcontainer.
·        No<bean>element is defined corresponding to the FixedDepositDetails domain object of
MyBank application. This is because domain objects arenot typically managed by the Spring
container;theyarecreatedbytheORMframework(likeHibernate)usedbytheapplication,oryou
createthemprogrammaticallyusingthenewoperator.
·        The <property> element specifies a dependency (or a configuration property) of the bean
configuredbythe<bean>element.The<property>elementcorrespondstoaJavaBean-stylesetter
method in the bean class which is invoked by the Spring container to set a dependency (or a
configurationproperty)ofthebean.
Letsnowlookathowdependenciesareinjectedviasettermethods.
Injectingdependenciesviasettermethods
To understand how dependencies are injected via setter methods defined in the bean class, let’s once
againlookattheFixedDepositControllerclassofMyBankapplication:
Examplelisting1-14–FixedDepositControllerclass
Project–ch01-bankapp-xml
Sourcelocation-src/main/java/sample/spring/chapter01/bankapp
packagesample.spring.chapter01.bankapp;
importorg.apache.log4j.Logger;
publicclassFixedDepositController{
privatestaticLoggerlogger=Logger.getLogger(FixedDepositController.class);
privateFixedDepositServicefixedDepositService;
publicFixedDepositController(){
logger.info("initializing");
}
publicvoidsetFixedDepositService(FixedDepositServicefixedDepositService){
logger.info("SettingfixedDepositServiceproperty");
this.fixedDepositService=fixedDepositService;
}
.....
}
The above example listing shows that the FixedDepositController class declares an instance variable
namedfixedDepositServiceoftypeFixedDepositService.ThefixedDepositServicevariableissetbythe
setFixedDepositServicemethod-aJavaBean-stylesettermethodforfixedDepositServicevariable.This
isanexampleofsetter-basedDI,whereinasettermethodsatisfiesadependency.
The following figure describes the bean definition for the FixedDepositController class in the
applicationContext.xmlfile(referexamplelisting1-13):
Figure1-5Definingdependenciesusing<property>elements
The above bean definition shows that the FixedDepositController bean defines its dependence on
FixedDepositServicebeanvia<property>element.The<property>elementsnameattributecorresponds
totheJavaBean-stylesettermethodinthebeanclassthatisinvokedbytheSpringcontaineratthetimeof
beancreation.The<property>element’srefattributeidentifiestheSpringbeanwhoseinstanceneedsto
becreatedandpassedtotheJavaBean-stylesettermethod.Thevalueofrefattributemustmatchtheid
attribute’s value (or one of the names specified by the name attribute) of a <bean> element in the
configurationmetadata.
Infigure1-5,thevalueof<property>elementsnameattributeisfixedDepositService,whichmeansthat
the <property> element corresponds to the setFixedDepositService setter method of
FixedDepositController class (refer example listing 1-14). As the value of <property> elements ref
attribute is service, the <property> element refers to the <bean> element whose id attribute’s value is
service.Now,the<bean>elementwhoseidattribute’svalueisserviceistheFixedDepositServicebean
(refer example listing 1-13). Spring container creates an instance of FixedDepositService class (a
dependency), and invokes the setFixedDepositService method (a JavaBean-style setter method for
fixedDepositService variable) of FixedDepositController (a dependent object), passing the
FixedDepositServiceinstance.
InthecontextofFixedDepositControllerapplicationobject,thefollowingfiguresummarizesthepurpose
ofnameandrefattributesof<property>element:
Figure 1-6 <property> elements name attribute corresponds to a JavaBean-style setter method that
satisfiesabeandependency,andrefattributereferstoanotherbean.
The above figure shows that fixedDepositService value of name attribute corresponds to the
setFixedDepositServicemethodofFixedDepositControllerclass,andservicevalueofrefattributerefers
tothebeanwhoseidisservice.
NOTEItisfairlycommontorefertoabeandefinitionbyitsname(whichisidattribute’svalue)ortype
(whichisclassattribute’svalue)ortheinterfaceimplementedbythebeanclass.Forinstance,youcan
refer to ‘FixedDepositController bean as ‘controller bean’. And, if the FixedDepositController class
implements FixedDepositControllerIntf interface, you can refer to ‘FixedDepositController bean as
‘FixedDepositControllerIntfbean’.
ThefollowingdiagramsummarizeshowtheSpringcontainercreatesbeansandinjectstheirdependencies
basedontheconfigurationmetadatasuppliedbytheapplicationContext.xmlfile(referexamplelisting1-
13)ofMyBankapplication:
Figure1-7-ThesequenceinwhichSpringIoCcontainercreatesbeansandinjectstheirdependencies.
The above figure shows the sequence of steps followed by the Spring IoC container to create
FixedDepositController, FixedDepositService and FixedDepositDao beans and inject their
dependencies.  Before attempting to create beans, the Spring container reads and validates the
configuration metadata supplied by the applicationContext.xml file. The order in which the beans are
created by the Spring container depends on the order in which they are defined in the
applicationContext.xml file.  Spring container ensures that the dependencies of a bean are completely
configured before the setter method is invoked. For example, the FixedDepositController bean is
dependentonFixedDepositServicebean;therefore,SpringcontainerconfigurestheFixedDepositService
beanbeforeinvokingthesetFixedDepositServicemethodofFixedDepositControllerbean.
The bean definitions that we have seen so far, instruct Spring container to create bean instances by
invokingtheno-argumentconstructorofthebeanclass,andinjectdependenciesusingsetter-basedDI.In
chapter 2, we’ll look at bean definitions that instruct Spring container to create a bean instance via a
factorymethod defined in a class. Also, well look at how to inject dependencies through constructor
arguments(referredtoasconstructor-basedDI),throughargumentstothefactorymethodthatcreatesthe
beaninstance,andbyusingsetter-basedDIonthebeaninstancereturnedbythefactorymethod.
LetsnowlookathowtocreateaninstanceofSpringcontainerandpassconfigurationmetadatatoit.
CreatinganinstanceofSpringcontainer
Springs ApplicationContext object represents an instance of Spring container. Spring provides a few
built-in implementations of ApplicationContext interface, like ClassPathXmlApplicationContext,
FileSystemXmlApplicationContext, XmlWebApplicationContext, XmlPortletApplicationContext, and so
on. The choice of the ApplicationContext implementation depends on how you have defined the
configuration metadata (using XML, annotations or Java code), and the type of your application
(standalone, web or portlet application). For instance, ClassPathXmlApplicationContext and
FileSystemXmlApplicationContext classes are suitable forstandalone applications in which
configuration metadata is supplied in XML format, XmlWebApplicationContext is suitable for web
applications in which the configuration metadata is supplied in XML format,
AnnotationConfigWebApplicationContext is suitable forweb applications in which configuration
metadataissuppliedthroughJavacode,andsoon.
As MyBank application represents a standalone application, we can use either
ClassPathXmlApplicationContext or FileSystemXmlApplicationContext class to create an instance of
Spring container. You should note that the ClassPathXmlApplicationContext class loads an application
contextXMLfilefromthespecifiedclasspathlocation,andtheFileSystemXmlApplicationContextclass
loadsanapplicationcontextXMLfilefromthespecifiedlocationonthefilesystem.
The following BankApp class of MyBank application shows that an instance of Spring container is
createdusingtheClassPathXmlApplicationContextclass:
Examplelisting1-15–BankAppclass
Project–ch01-bankapp-xml
Sourcelocation-src/main/java/sample/spring/chapter01/bankapp
packagesample.spring.chapter01.bankapp;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassBankApp{
.....
publicstaticvoidmain(Stringargs[]){
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
.....
}
}
TheaboveexamplelistingshowstheBankApp’smainmethod,whichisresponsibleforbootstrappingthe
Springcontainer.TheclasspathlocationoftheapplicationcontextXMLfileispassedtotheconstructor
of ClassPathXmlApplicationContext class. The creation of ClassPathXmlApplicationContext instance
resultsincreationofthosebeansintheapplicationcontextXMLfilethataresingleton-scopedandsetto
bepre-instantiated.Inchapter 2,well discussbean scopes, andwhatitmeanstohave beanspre- or
lazily-instantiated by Spring container. For now, you can assume that the beans defined in the
applicationContext.xml file of MyBank application are singleton-scoped and set to be pre-instantiated.
This means that the beans defined in the applicationContext.xml file are created when an instance of
ClassPathXmlApplicationContextiscreated.
Now,thatwehaveseenhowtocreateaninstanceoftheSpringcontainer,letslookathowtoretrieve
beaninstancesfromtheSpringcontainer.
AccessbeansfromtheSpringcontainer
Theapplicationobjectsdefinedvia<bean>elementsarecreatedandmanagedbytheSpringcontainer.
You can access instances of these application objects by calling one of the getBean methods of the
ApplicationContextinterface.
The following example listing shows the main method of BankApp class that retrieves an instance of
FixedDepositControllerbeanfromtheSpringcontainerandinvokesitsmethods:
Examplelisting1-16–BankAppclass
Project–ch01-bankapp-xml
Sourcelocation-src/main/java/sample/spring/chapter01/bankapp
packagesample.spring.chapter01.bankapp;
importorg.apache.log4j.Logger;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassBankApp{
privatestaticLoggerlogger=Logger.getLogger(BankApp.class);
publicstaticvoidmain(Stringargs[]){
Appli