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[]){
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");

FixedDepositControllerfixedDepositController=
(FixedDepositController)context.getBean("controller");
logger.info("Submissionstatusoffixeddeposit:"+fixedDepositController.submit());
logger.info("Returnedfixeddepositinfo:"+fixedDepositController.get());
}
}
At first, the ApplicationContexts getBean method is invoked to retrieve an instance of
FixedDepositController bean from the Spring container, followed by invocation of submit and get
methodsofFixedDepositControllerbean.TheargumentpassedtothegetBeanmethodisthenameofthe
beanwhoseinstanceyouwanttoretrievefromtheSpringcontainer.Thenameofthebeanpassedtothe
getBeanmethodmustbethevalueoftheidornameattributeofthebeanthatyouwanttoretrieve.Ifno
bean with the specified name is registered with the Spring container, an exception is thrown by the
getBeanmethod.
In example listing 1-16, to configure the FixedDepositController instance, we didnt programmatically
createaninstanceofFixedDepositService and set it on the FixedDepositController instance. Also, we
didnt create an instance of FixedDepositDao and set it on the FixedDepositService instance. This is
becausethetaskofcreatingdependencies,andinjectingthemintothethedependentobjectsishandledby
theSpringcontainer.
If you go to ch01-bankapp-xml project and execute the main method of BankApp class, you’ll see the
followingoutputontheconsole:
INFOsample.spring.chapter01.bankapp.FixedDepositController-initializing
INFOsample.spring.chapter01.bankapp.FixedDepositService-initializing
INFOsample.spring.chapter01.bankapp.FixedDepositDao-initializing
INFOsample.spring.chapter01.bankapp.FixedDepositService-SettingfixedDepositDaoproperty
INFOsample.spring.chapter01.bankapp.FixedDepositController-SettingfixedDepositServiceproperty
INFOsample.spring.chapter01.bankapp.BankApp-Submissionstatusoffixeddeposit:true
INFOsample.spring.chapter01.bankapp.BankApp-Returnedfixeddepositinfo:id:1,depositamount:10000.0,tenure:365,email:
someemail@something.com
The above output shows that Spring container creates an instance of each of the beans defined in the
applicationContext.xmlfileofMyBankapplication.Also,Springcontainerusessetter-basedDItoinject
an instance of FixedDepositService into FixedDepositController instance, and an instance of
FixedDepositDaointotheFixedDepositServiceinstance.
LetsnowlookatsomeoftheframeworksthatarebuiltontopofSpringFramework.
1-6FrameworksbuiltontopofSpring
Though there are many frameworks from SpringSource that use Spring Framework as the foundation,
we’lllook atsomeofthewidelypopular ones.Foramorecomprehensivelistofframeworks,andfor
moredetailsaboutanindividualframework,itsrecommendedthatyouvisittheSpringSourcewebsite
(www.springsource.org).
Thefollowingtableprovidesahigh-leveloverviewoftheframeworksfromSpringSourcethatarebuilt
ontopofSpringFramework:
Framework Description
SpringSecurity
Authenticationandauthorizationframeworkforenterpriseapplications.Youneedto
configure a few beans in your application context XM L file to incorporate
authenticationandauthorizationfeaturesintoyourapplication.
SpringData
Provides a consistent programming model to interact with different types of
databases.Forinstance,youcanuseittointeractwithnon-relationaldatabases,like
MongoDBorNeo4j,andyoucanalsouseitforaccessingrelationaldatabasesusing
JPA.
SpringBatch Ifyourapplicationrequiresbulkprocessing,thisframeworkisforyou.
SpringIntegration ProvidesEnterpriseApplicationIntegration(EAI)capabilitiestoapplications.
SpringSocial If your application requires interaction with social media websites, like Facebook
andTwitter,thenyou’llfindthisframeworkhighlyuseful.
SpringBlazeDS
Integration
IfyouaredevelopinganAdobeFlexbasedapplication,youcanusethisframework
toconnectFlexfrontendwithSpring-basedbusinesstier.
AstheframeworksmentionedintheabovetablearebuiltontopofSpringFramework,beforeusingany
oftheseframeworksmakesurethattheyarecompatiblewiththeSpringFrameworkversionthatyouare
using.
1-7Summary
Inthischapter,welookedatthebenefitsofusingSpringFramework.WealsolookedatasimpleSpring
applicationthatshowedhowtospecifyconfigurationmetadatainXMLformat,createtheSpringcontainer
instanceandretrievebeansfromit.Inthenextchapter,welllookatsomeofthefoundationconceptsof
SpringFramework.
Chapter2SpringFrameworkbasics
2-1Introduction
Inthepreviouschapter,wesawthattheSpringcontainerinvokestheno-argumentconstructorofabean
classtocreateabeaninstance,andsetter-basedDIisusedtosetbeandependencies.Inthischapter,we’ll
goastepfurtherandlookat:
§Springssupportfor‘programmingtointerfacesdesignprinciple
§differentapproachestoinstantiatingSpringbeans
§constructor-basedDIforpassingbeandependenciesasconstructorarguments
§constructor-andsetter-basedDIforpassingsimpleStringvaluestobeans,and
§beanscopes
Lets begin this chapter with looking at how Spring improves testability of applications by supporting
‘programmingtointerfacesdesignprinciple.
2-2Programmingtointerfacesdesignprinciple
Insection1-5ofchapter1,wesawthatadependentPOJOclasscontainedreferencetotheconcreteclass
of the dependency. For example, the FixedDepositController class contained reference to the
FixedDepositService class, and the FixedDepositService class contained reference to the
FixedDepositDaoclass.Ifadependentclasshasdirectreferencetotheconcreteclassofthedependency,
it results in tight coupling between the classes. This means that if you want to substitute a different
implementationofthedependency,itdrequirechangingthedependentclass.
Letsnowlookatascenarioinwhichadependentclasscontainsdirectreferencetotheconcreteclassof
thedependency.
Scenario:Dependentclasscontainsreferencetotheconcreteclassofdependency
Lets say that the FixedDepositDao class makes use of plain JDBC to interact with the database. To
simplify database interaction, you create another DAO implementation, FixedDepositHibernateDao,
whichusesHibernateORMfordatabaseinteraction.Now,toswitchfromplainJDBCtoHibernateORM
implementation,you’llneedtochangeFixedDepositServiceclasstouseFixedDepositHibernateDaoclass
insteadofFixedDepositDao,asshowninthefollowingexamplelisting:
Examplelisting2-1–FixedDepositServiceclass
publicclassFixedDepositService{
privateFixedDepositHibernateDaofixedDepositDao;
publicvoidsetFixedDepositDao(FixedDepositHibernateDaofixedDepositDao){
this.fixedDepositDao=fixedDepositDao;
}
publicFixedDepositDetailsgetFixedDepositDetails(longid){
returnfixedDepositDao.getFixedDepositDetails(id);
}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
returnfixedDepositDao.createFixedDeposit(fixedDepositDetails);
}
}
The above example listing shows that reference to FixedDepositDao class was replaced by
FixedDepositHibernateDaosothatHibernateORMcanbeusedfordatabaseinteraction.Thisshowsthat
if a dependent class refers to the concrete implementation class of the dependency, then substituting a
differentimplementationrequireschangesinthedependentclass.
Letsnowlookatascenarioinwhichadependentclasscontainsreferencetotheinterfaceimplemented
bythedependency.
Scenario:Dependentclasscontainsreferencetotheinterfaceimplementedbythe
dependency
WeknowthataJavainterfacedefinesacontracttowhichtheimplementationclassesconform.So,ifa
class depends on the interface implemented by the dependency, no change is required in the class if a
different implementation of the dependency is substituted. The application design approach in which a
class depends on the interface implemented by the dependency is referred to as ‘programming to
interfaces.Theinterfaceimplementedbythedependencyclassisreferredtoasadependencyinterface.
Asitisagooddesignpracticetoprogramtointerfacesthanto‘programtoclasses’,thefollowingclass
diagramshowsthatitisagooddesignifABeanclassdependsonBBeaninterfaceandnotonBBeanImpl
classthatimplementsBBeaninterface:
Figure2-1-Programtointerfacesisagooddesignpracticethanto‘programtoclasses
The following class diagram shows how FixedDepositService class can make use of ‘programming to
interfacesdesignapproachtoeasilyswitchthestrategyusedfordatabaseinteraction:
Figure2-2–TheFixedDepositServicedependsonFixedDepositDaointerface,whichisimplementedby
FixedDepositJdbcDaoandFixedDepositHibernateDaoclasses.
The above figure shows that the FixedDepositService class is not directly dependent on the
FixedDepositJdbcDaoorFixedDepositHibernateDaoclass.Instead,FixedDepositServicedependsonthe
FixedDepositDao interface (the dependency interface) implemented by FixedDepositJdbcDao and
FixedDepositHibernateDao classes. Now, depending on whether you want to use plain JDBC or
Hibernate ORM framework, you supply an instance of FixedDepositJdbcDao or
FixedDepositHibernateDaototheFixedDepositServiceinstance.
As FixedDepositService depends on FixedDepositDao interface, you can support other database
interactionstrategies inthe future. Lets say that you decidetouse iBATIS(now renamed to MyBatis)
persistence framework for database interaction. You can use iBATIS without making any changes to
FixedDepositService class by simply creating a new FixedDepositIbatisDao class that implements
FixedDepositDao interface, and supplying an instance of FixedDepositIbatisDao to the
FixedDepositServiceinstance.
Sofarwehaveseenthat‘programmingtointerfaces’designapproachresultsinloosecouplingbetweena
dependentclassanditsdependencies.Letsnowlookathowthisdesignapproachimprovestestabilityof
thedependentclasses.
Improvedtestabilityofdependentclasses
In figure 2-2, we saw that the FixedDepositService class holds reference to the FixedDepositDao
interface.FixedDepositJdbcDaoandFixedDepositHibernateDaoareconcreteimplementationclassesof
FixedDepositDaointerface.Now,tosimplifyunittestingofFixedDepositServiceclass,youcansubstitute
amockimplementationofFixedDepositDaointerfacethatdoesntrequireadatabase.
If the FixedDepositService class had direct reference to FixedDepositJdbcDao or
FixedDepositHibernateDao class, testing FixedDepositService class would have required setting up a
databasefortestingpurposes.Thisshowsthatbyusingamockimplementationofdependencyinterface,
youcansavetheefforttosetuptheinfrastructureforunittestingyourdependentclasses.
LetsnowseehowSpringsupports‘programmingtointerfacesdesignapproachinapplications.
Springssupportfor‘programmingtointerfacesdesignapproach
Touseprogrammingtointerfacesdesignapproach inyour Springapplication,youneedtoensurethe
followingthings:
§the<bean>elementsintheconfigurationmetadataspecifytheconcreteclassesofthedependency
§thedependentbean classes refer tothedependency interface insteadof the concrete class ofthe
dependency
Lets now look at the modified MyBank application that uses ‘programming to interfaces’ design
approach.
IMPORT chapter 2/ch02-bankapp-interfaces (This project shows how ‘programming to interfaces’
designapproachisusedincreatingSpringapplications.Toruntheapplication,executethemainmethod
oftheBankAppclassofthisproject)
MyBankapplicationthatusesprogrammingtointerfaces’designapproach
The following class diagram depicts the modified MyBank application that uses ‘programming to
interfacesdesignapproach:
Figure2-3-MyBankapplicationthatuses‘programtointerfacesdesignapproach
Theabovefigureshowsthatadependentclassdependsontheinterfaceimplementedbythedependency,
and not on the concrete implementation class of the dependency. For instance, the
FixedDepositControllerImpl class depends on the FixedDepositService interface, and the
FixedDepositServiceImplclassdependsontheFixedDepositDaointerface.
ThefollowingexamplelistingshowstheFixedDepositServiceImpl class based onthedesignshownin
figure2-3:
Examplelisting2-2–FixedDepositServiceclass
Project–ch02-bankapp-interfaces
Sourcelocation-src/main/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
privateFixedDepositDaofixedDepositDao;
.....
publicvoidsetFixedDepositDao(FixedDepositDaofixedDepositDao){
this.fixedDepositDao=fixedDepositDao;
}
publicFixedDepositDetailsgetFixedDepositDetails(longid){
returnfixedDepositDao.getFixedDepositDetails(id);
}
publicbooleancreateFixedDeposit(FixedDepositDetailsfdd){
returnfixedDepositDao.createFixedDeposit(fdd);
}
}
The above example listing shows that the FixedDepositServiceImpl class contains reference to the
FixedDepositDao interface. The FixedDepositDao implementation that you want to inject into the
FixedDepositServiceImplinstanceisspecifiedintheapplicationcontextXMLfile.Asshowninfigure2-
3, you can inject any one of the following concrete implementations of FixedDepositDao interface:
FixedDepositIbatisDao,FixedDepositJdbcDaoandFixedDepositHibernateDao.
ThefollowingexamplelistingshowstheapplicationContext.xmlfilethat caters tothe design shown in
figure2-3:
Examplelisting2-3–applicationContext.xml-MyBanksapplicationcontextXMLfile
Project–ch02-bankapp-interfaces
Sourcelocation-src/main/resources/META-INF/spring
<?xmlversion="1.0"encoding="UTF-8"standalone="no"?>
<beans.....>
<beanid="controller"
class="sample.spring.chapter02.bankapp.controller.FixedDepositControllerImpl">
<propertyname="fixedDepositService"ref="service"/>
</bean>
<beanid="service"class="sample.spring.chapter02.bankapp.service.FixedDepositServiceImpl">
<propertyname="fixedDepositDao"ref="dao"/>
</bean>
<beanid="dao"class="sample.spring.chapter02.bankapp.dao.FixedDepositHibernateDao"/>
</beans>
The above applicationContext.xml file shows that an instance of FixedDepositHibernateDao (an
implementation of FixedDepositDao interface) is injected into FixedDepositServiceImpl. Now, if you
decidetouseiBATISinsteadofHibernateforpersistence,thenallyouneedtodoistochangetheclass
attributeofthedaobeandefinitionintheapplicationContext.xmlfiletorefertothefully-qualifiednameof
theFixedDepositIbatisDaoclass.
LetsnowlookatdifferentwaysinwhichSpringcontainercaninstantiatebeans.
2-3DifferentapproachestoinstantiatingSpringbeans
SofarwehaveseenbeandefinitionexamplesthatinstructSpringcontainertocreatebeaninstancesby
invokingtheno-argumentconstructorofthebeanclass.Considerthefollowingbeandefinition:
<beanid=”myBeanclass=”mypackage.MyBean”/>
In the above bean definition, MyBean class represents a POJO class that defines a no-argument
constructor. MyBean class doesn’t implement any Spring-specific interface or extend from any Spring-
specific class. This effectively means that the Spring container can create and manage instance of any
classthatprovidesano-argumentconstructor.
NOTE It is important to note that the Spring container can create and manage instance of any class,
irrespectiveofwhethertheclassprovidesano-argumentconstructorornot.Insection2-4,we’lllookat
beandefinitionsinwhichtheconstructorofthebeanclassacceptsoneormorearguments.
Ifyouhaveanexistingprojectthatusesfactoryclassestocreateobjectinstances,youcanstilluseSpring
containertomanageobjectscreatedbythesefactories.LetsnowlookathowSpringcontainerinvokesa
staticoraninstancefactorymethodofaclasstomanagethereturnedobjectinstance.
Instantiatingbeansviastaticfactorymethods
Infigure2-3,wesawthattheFixedDepositDaointerfaceisimplementedbyFixedDepositHibernateDao,
FixedDepositIbatisDao and FixedDepositJdbcDao classes. The following example listing shows a
FixedDepositDaoFactoryclassthatdefinesastaticfactorymethodforcreatingandreturninganinstance
ofFixedDepositDaobasedontheargumentpassedtothestaticmethod:
Examplelisting2-4–FixedDepositDaoFactoryclass
publicclassFixedDepositDaoFactory{
privateFixedDepositDaoFactory(){}

publicstaticFixedDepositDaogetFixedDepositDao(StringdaoType){
FixedDepositDaofixedDepositDao=null;
if("jdbc".equalsIgnoreCase(daoType)){
fixedDepositDao=newFixedDepositJdbcDao();
}
if("hibernate".equalsIgnoreCase(daoType)){
fixedDepositDao=newFixedDepositHibernateDao();
}
.....
returnfixedDepositDao;
}
}
TheaboveexamplelistingshowsthattheFixedDepositDaoFactoryclassdefinesagetFixedDepositDao
staticmethodthatcreatesandreturnsaninstanceofFixedDepositJdbcDao,FixedDepositHibernateDao
orFixedDepositIbatisDaoclass,dependingonthevalueofthedaoTypeargument.
ThefollowingbeandefinitionfortheFixedDepositDaoFactoryclassinstructsSpringcontainertoinvoke
FixedDepositDaoFactory’sgetFixedDepositDao method to obtain an instance of FixedDepositJdbcDao
class:
Examplelisting2-5–BeandefinitionfortheFixedDepositDaoFactoryclass
<beanid="dao"class="sample.spring.FixedDepositDaoFactory"
factory-method="getFixedDepositDao">
<constructor-argindex=”0”value="jdbc"/>
</bean>
Intheabovebeandefinition,classattributespecifiesthefully-qualifiednameoftheclassthatdefinesthe
staticfactorymethod.Thefactory-methodattributespecifiesthenameofthestaticfactorymethodthatthe
SpringcontainerinvokestoobtainaninstanceofFixedDepositDaoobject.The<constructor-arg>element
is defined in Springs beansschema and is used for passing arguments to constructors, and static and
instancefactorymethods.Theindexattributereferstothelocationoftheargumentintheconstructor,orin
thestaticorinstancefactorymethod.Intheabovebeandefinition,thevalue0ofindexattributemeans
that the <constructor-arg> element is supplying value for the first argument, which is daoType, of the
getFixedDepositDaofactorymethod.Thevalueattributespecifiestheargumentvalue.Ifafactorymethod
acceptsmultiplearguments,youneedtodefinea<constructor-arg>elementforeachofthearguments.
ItisimportanttonotethatcallingApplicationContextsgetBeanmethodtoobtaindaobean(referexample
listing 2-5) will result in invocation of the FixedDepositDaoFactorys getFixedDepositDao factory
method. This means that calling getBean("dao") returns the FixedDepositDao instance created by the
getFixedDepositDaofactorymethod,andnotaninstanceofFixedDepositDaoFactoryclass.
Now,thatwehaveseentheconfigurationofthefactoryclassthatcreatesaninstanceofFixedDepositDao,
the following example listing shows how to inject an instance of FixedDepositDao into
FixedDepositServiceImplclass:
Examplelisting2-6–Injectingobjectinstancescreatedbystaticfactorymethod
<beanid="service"class="sample.spring.chapter02.bankapp.FixedDepositServiceImpl">
<propertyname=“fixedDepositDao"ref="dao"/>
</bean>
<beanid="dao"class="sample.spring.chapter02.basicapp.FixedDepositDaoFactory"
factory-method="getFixedDepositDao">
<constructor-argindex=”0”value="jdbc"/>
</bean>
In the above example listing, <property> element injects an instance of FixedDepositDao returned by
FixedDepositDaoFactory’sgetFixedDepositDao factory methodintoFixedDepositServiceImpl instance.
If you compare the bean definition for the FixedDepositServiceImpl class shown above with the one
shown in example listing 2-3, youll notice that they are exactly the same. This shows that the bean
dependencies are specifiedthe same way irrespective of how (using no-argumentconstructor or static
factorymethod)theSpringcontainercreatesbeaninstances.
LetsnowlookathowSpringcontainerinstantiatebeansbyinvokinganinstancefactorymethod.
Instantiatingbeansviainstancefactorymethods
ThefollowingexamplelistingshowstheFixedDepositDaoFactoryclassthatdefinesaninstancefactory
methodforcreatingandreturninganinstanceofFixedDepositDao:
Examplelisting2-7–FixedDepositDaoFactoryclass
publicclassFixedDepositDaoFactory{
publicFixedDepositDaoFactory(){
}

publicFixedDepositDaogetFixedDepositDao(StringdaoType){
FixedDepositDaoFixedDepositDao=null;
if("jdbc".equalsIgnoreCase(daoType)){
FixedDepositDao=newFixedDepositJdbcDao();
}
if(“hibernate”.equalsIgnoreCase(daoType)){
FixedDepositDao=newFixedDepositHiberateDao();
}
.....
returnfixedDepositDao;
}
}
Ifaclassdefinesaninstancefactorymethod,theclassmustdefineapublicconstructorsothattheSpring
containercancreateaninstanceofthatclass.Intheaboveexamplelisting,theFixedDepositDaoFactory
class defines a public no-argument constructor. The FixedDepositDaoFactorys getFixedDepositDao
methodisaninstancefactorymethodthatcreatesandreturnsaninstanceofFixedDepositDao.
The following example listing shows how to instruct Spring container to invoke
FixedDepositDaoFactory’sgetFixedDepositDaomethodtoobtainaninstanceofFixedDepositDao:
Examplelisting2-8–ConfigurationtoinvokeFixedDepositDaoFactorysgetFixedDepositDaomethod
<beanid="daoFactory"class="sample.spring.chapter02.basicapp.FixedDepositDaoFactory"/>
<beanid="dao"factory-bean="daoFactory"factory-method="getFixedDepositDao">
<constructor-argindex="0"value="jdbc"/>
</bean>
<beanid="service"class="sample.spring.chapter02.bankapp.FixedDepositServiceImpl">
<propertyname=“fixedDepositDao"ref="dao"/>
</bean>
TheaboveexamplelistingshowsthattheFixedDepositDaoFactoryclass(aclassthatcontainsinstance
factory method) is configured like a regular Spring bean, and a separate <bean> element is used to
configuretheinstancefactorymethoddetails.Toconfiguredetailsofaninstancefactorymethod,factory-
beanandfactory-methodattributesof<bean>elementareused.Thefactory-bean attribute referstothe
beanthatdefinestheinstancefactorymethod,andthefactory-methodattributespecifiesthenameofthe
instance factory method. In the above example listing, <property> element injects an instance of
FixedDepositDao returned by FixedDepositDaoFactorys getFixedDepositDao factory method into
FixedDepositServiceImplinstance.
Aswithstaticfactorymethods,youcanpassargumentstoinstancefactorymethodsusing<constructor-
arg> element. It is important to note that invoking ApplicationContextsgetBean method to obtain dao
bean in the above example listing will result in invocation of the FixedDepositDaoFactorys
getFixedDepositDaofactorymethod.
So far we have looked at bean definition examples in which dependencies are injected into beans via
settermethods.Let’snowlookatdifferentDImechanismsthatyoucanuseforinjectingdependencies.
2-4Dependencyinjectiontechniques
In Spring, dependency injection is performed by passing arguments to a beans constructor and setter
methods.Ifyouareusingastaticorinstancefactorymethodtocreatebeaninstances,youcanpassbean
dependencies to the factory method or you can set them on the bean instance returned by the factory
method.
We’llnowlookatexamplesthatdemonstratedifferentDItechniques.
Setter-basedDI
Sofarinthisbook,weveseenexamplesofsetter-basedDI.Insetter-basedDI,<property>elementsare
used to specify bean dependencies. The <property> element is also used to pass configuration
information(ifany)requiredbythebean.
LetssaythattheMyBankapplicationcontainsaPersonalBankingServiceservicethatallowscustomers
toretrievebankaccountstatement,checkbankaccountdetails,updatecontactnumber,changepassword,
and contact customer service. The PersonalBankingService class uses JmsMessageSender (for sending
JMS messages), EmailMessageSender (for sending emails) and WebServiceInvoker (for invoking
external web services) objects toaccomplish its intended functionality. The following example listing
showsthePersonalBankingServiceclass:
Examplelisting2-9–PersonalBankingServiceclass
publicclassPersonalBankingService{
privateJmsMessageSenderjmsMessageSender;
privateEmailMessageSenderemailMessageSender;
privateWebServiceInvokerwebServiceInvoker;
.....
publicvoidsetJmsMessageSender(JmsMessageSenderjmsMessageSender){
this.jmsMessageSender=jmsMessageSender;
}
publicvoidsetEmailMessageSender(EmailMessageSenderemailMessageSender){
this.emailMessageSender=emailMessageSender;
}
publicvoidsetWebServiceInvoker(WebServiceInvokerwebServiceInvoker){
this.webServiceInvoker=webServiceInvoker;
}
.....
}
The above example listing shows that a setter method is defined for JmsMessageSender,
EmailMessageSenderandWebServiceInvokerdependenciesofPersonalBankingServiceclass.
We can use setter-based DI to inject the dependencies of the PersonalBankingService class, as shown
here:
Examplelisting2-10–BeandefinitionsforPersonalBankingServiceclassanditsdependencies
<beanid="personalBankingService"class="PersonalBankingService">
<propertyname="emailMessageSender"ref="emailMessageSender"/>
<propertyname="jmsMessageSender"ref="jmsMessageSender"/>
<propertyname="webServiceInvoker"ref="webServiceInvoker"/>
</bean>
<beanid="jmsMessageSender"class="JmsMessageSender">
.....
</bean>
<beanid="webServiceInvoker"class="WebServiceInvoker"/>
.....
</bean>
<beanid="emailMessageSender"class="EmailMessageSender"/>
.....
</bean>
The personalBankingService bean definition shows that a <property> element is specified for each
dependencyofPersonalBankingServiceclass.
PersonalBankingServiceusesEmailMessageSenderbeantosendanemailnotificationtothecustomers
emailaddressincasecustomerchangeshiscontactnumber.EmailMessageSenderrequiresemailserver
address, and username and password for authenticating with the email server. The following example
listingshowsthatthe<property>elementcanalsobeusedforsettingbeanpropertiesoftypeString:
Examplelisting2-11EmailMessageSenderclassandthecorrespondingbeandefinition
publicclassEmailMessageSender{
privateStringhost;
privateStringusername;
privateStringpassword;
.....
publicvoidsetHost(Stringhost){
this.host=host;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
.....
}

<beanid="emailMessageSender"class="EmailMessageSender">
<propertyname="host"value="smtp.gmail.com"/>
<propertyname="username"value="myusername"/>
<propertyname="password"value="mypassword"/>
</bean>
The above example listing shows that <property> elements have been used to set host, username and
passwordpropertiesofEmailMessageSenderbean.ThevalueattributespecifiestheStringvaluetobeset
for the bean property identified by the name attribute. The host, username and password properties
representconfigurationinformationrequiredbyEmailMessageSenderbean.Inchapter3,we’llseehow
the <property> element is used to set primitive type (like int, long, and so on), collection type (like
java.util.List,java.util.Map,andsoon)andcustomtype(likeAddress)properties.
Setter-based DI is also used to inject dependencies into beans created bystatic and instance factory
methods.Let’slookathowtousesetter-basedDIinconjunctionwithstaticandinstancefactorymethods.
Injectingdependenciesintobeaninstancescreatedbyfactorymethods
Youcanusesetter-basedDItoinjectdependenciesofthebeaninstancereturnedbyastaticorinstance
factorymethod.
ConsiderthefollowingFixedDepositJdbcDaoclassthatdefinesadatabaseInfoproperty:
Examplelisting2-12–FixedDepositJdbcDaoclass
publicclassFixedDepositJdbcDao{
privateDatabaseInfodatabaseInfo;
.....
publicFixedDepositJdbcDao(){}
publicvoidsetDatabaseInfo(DatabaseInfodatabaseInfo){
this.databaseInfo=databaseInfo;
}
.....
}
In the above example listing, the databaseInfo attribute represents a dependency of the
FixedDepositJdbcDaoclassthatisfulfilledbysetDatabaseInfomethod.
The following FixedDepositDaoFactory class defines a factory method responsible for creating and
returninganinstanceofFixedDepositDaoJdbcclass:
Examplelisting2-13–FixedDepositDaoFactoryclass
publicclassFixedDepositDaoFactory{
publicFixedDepositDaoFactory(){
}

publicFixedDepositDaogetFixedDepositDao(StringdaoType){
FixedDepositDaoFixedDepositDao=null;
if("jdbc".equalsIgnoreCase(daoType)){
FixedDepositDao=newFixedDepositJdbcDao();
}
if(“hibernate”.equalsIgnoreCase(daoType)){
FixedDepositDao=newFixedDepositHiberateDao();
}
.....
returnfixedDepositDao;
}
}
Intheaboveexamplelisting,thegetFixedDepositDaomethodisaninstancefactorymethodforcreating
FixedDepositDao instances. The getFixedDepositDao method creates an instance of
FixedDepositJdbcDaoinstanceifthevalueofdaoTypeargumentisjdbc.Itisimportanttonotethatthe
getFixedDepositDaomethoddoesn’tsetthedatabaseInfopropertyoftheFixedDepositJdbcDaoinstance.
Aswesawinexamplelisting2-8,thefollowingbeandefinitionsinstructSpringcontainertocreatean
instance of FixedDepositJdbcDao by invoking the getFixedDepositDao instance factory method of
FixedDepositDaoFactoryclass:
Examplelisting2-14–ConfigurationtoinvokeFixedDepositDaoFactorysgetFixedDepositDaomethod
<beanid="daoFactory"class="FixedDepositDaoFactory"/>
<beanid="dao"factory-bean="daoFactory"factory-method="getFixedDepositDao">
<constructor-argindex="0"value="jdbc"/>
</bean>
ThedaobeandefinitionresultsininvocationofFixedDepositDaoFactory’sgetFixedDepositDaomethod,
which creates and returns an instance of FixedDepositJdbcDao. But, the FixedDepositJdbcDao’s
databaseInfopropertyisnotset.TosetthedatabaseInfodependency,youcanperformsetter-basedDIon
theFixedDepositJdbcDaoinstancereturnedbythegetFixedDepositDaomethod,asshownhere:
Examplelisting2-15–ConfigurationtoinvokeFixedDepositDaoFactorysgetFixedDepositDaomethod
andsetdatabaseInfopropertyofreturnedFixedDepositJdbcDaoinstance
<beanid="daoFactory"class="FixedDepositDaoFactory"/>
<beanid="dao"factory-bean="daoFactory"factory-method="getFixedDepositDao">
<constructor-argindex="0"value="jdbc"/>
<propertyname="databaseInfo"ref="databaseInfo"/>
</bean>
<beanid="databaseInfo"class="DatabaseInfo"/>
The above bean definition shows that <property> element is used to set databaseInfo property of
FixedDepositJdbcDao instance returned by getFixedDepositDao instance factory method. As with the
instancefactorymethod,youcanusethe<property>elementtoinjectdependenciesintothebeaninstance
returnedbythestaticfactorymethod.
Letsnowlookathowtoinjectbeandependenciesviaconstructorarguments.
Constructor-basedDI
Inconstructor-basedDI,dependenciesofabeanarepassedasargumentstothebeanclasssconstructor.
For instance, the following example listing shows PersonalBankingService class whose constructor
acceptsJmsMessageSender,EmailMessageSenderandWebServiceInvokerobjects:
Examplelisting2-16–PersonalBankingServiceclass
publicclassPersonalBankingService{
privateJmsMessageSenderjmsMessageSender;
privateEmailMessageSenderemailMessageSender;
privateWebServiceInvokerwebServiceInvoker;
.....
publicPersonalBankingService(JmsMessageSenderjmsMessageSender,
EmailMessageSenderemailMessageSender,
WebServiceInvokerwebServiceInvoker){
this.jmsMessageSender=jmsMessageSender;
this.emailMessageSender=emailMessageSender;
this.webServiceInvoker=webServiceInvoker;
}
.....
}
The arguments to the PersonalBankingService’s constructor represent dependencies of the
PersonalBankingService class. The following example listing shows how dependencies of
PersonalBankingServiceinstancearesuppliedvia<constructor-arg>elements:
Examplelisting2-17–PersonalBankingServicebeandefinition
<beanid="personalBankingService"class="PersonalBankingService">
<constructor-argindex="0"ref="jmsMessageSender"/>
<constructor-argindex="1"ref="emailMessageSender"/>
<constructor-argindex="2"ref="webServiceInvoker"/>
</bean>
<beanid="jmsMessageSender"class="JmsMessageSender">
.....
</bean>
<beanid="webServiceInvoker"class="WebServiceInvoker"/>
.....
</bean>
<beanid="emailMessageSender"class="EmailMessageSender"/>
.....
</bean>
In the above example listing, <constructor-arg> elements specify details of the constructor arguments
passedtothePersonalBankingServiceinstance.Theindexattributespecifiestheindexoftheconstructor
argument.Iftheindexattributevalueis0,itmeansthatthe<constructor-arg>elementcorrespondstothe
firstconstructorargument,andiftheindexattributevalueis1,itmeansthatthe<constructor-arg>element
correspondstothesecondconstructorargument,andsoon.Wesawearlierthatrefattributeof<property>
elementisusedforpassingreferencetoabean.Similarly,refattributeof<constructor-arg>elementis
usedforpassingreferencetoabean.Likethe<property>element,the<constructor-arg>elementisalso
usedtopassconfigurationinformation(ifany)requiredbythebean.
You should note that the <constructor-arg> element is also used for passing arguments to static and
instancefactorymethodsthatcreatebeaninstances(refersection2-3).
NOTE Instead of using ref attribute of <property> and <constructor-arg> elements, you can use <ref>
elementinsidethe<property>and<constructor-arg>elementstosetreferencetobeans.Therefattribute
ispreferredasitmakestheXMLlessverbose.
The following example listing shows the EmailMessageSender class and the corresponding bean
definitionthatdemonstratesuseof<constructor-arg>elementstosupplyvaluesforStringtypeconstructor
arguments:
Examplelisting2-18EmailMessageSenderclassandthecorrespondingbeandefinition
publicclassEmailMessageSender{
privateStringhost;
privateStringusername;
privateStringpassword;
.....
publicEmailMessageSender(Stringhost,Stringusername,Stringpassword){
this.host=host;
this.username=username;
this.password=password;
}
.....
}
<beanid="emailMessageSender"class="EmailMessageSender">
<constructor-argindex="0"value="smtp.gmail.com"/>
<constructor-argindex="1"value="myusername"/>
<constructor-argindex="2"value="mypassword"/>
</bean>
Sofarwehaveseenthat<constructor-arg>elementisusedforinjectingbeandependenciesandpassing
valuesforStringtypeconstructorarguments.Inchapter3,wellseehowthe<constructor-arg>elementis
usedtosetprimitivetype(likeint,long,andsoon),collectiontype(likejava.util.List,java.util.Map,and
soon)andcustomtype(likeAddress)properties.
Letsnowlookathowwecanuseconstructor-basedDIalongwithsetter-basedDI.
Usingamixofconstructor-andsetter-basedDImechanisms
Ifabeanclassrequiresbothconstructor-andsetter-basedDImechanisms,youcanuseacombinationof
<constructor-arg>and<property>elementstoinjectdependencies.
The following example listing shows a bean class whose dependencies are injected as arguments to
constructorandsettermethods:
Examplelisting2-19–PersonalBankingServiceclass
publicclassPersonalBankingService{
privateJmsMessageSenderjmsMessageSender;
privateEmailMessageSenderemailMessageSender;
privateWebServiceInvokerwebServiceInvoker;
.....
publicPersonalBankingService(JmsMessageSenderjmsMessageSender,
EmailMessageSenderemailMessageSender){
this.jmsMessageSender=jmsMessageSender;
this.emailMessageSender=emailMessageSender;
}

publicvoidsetWebServiceInvoker(WebServiceInvokerwebServiceInvoker){
this.webServiceInvoker=webServiceInvoker;
}
.....
}
In the PersonalBankingService class, jmsMessageSender and emailMessageSender dependencies are
injected as constructor arguments, and webServiceInvoker dependency is injected via the
setWebServiceInvoker setter method. The following bean definition shows that both <constructor-arg>
and<property>elementsareusedtoinjectdependenciesofPersonalBankingServiceclass:
Examplelisting2-20–Mixingconstructor-andsetter-basedDImechanisms
<beanid="dataSource"class="PersonalBankingService">
<constructor-argindex="0"ref="jmsMessageSender"/>
<constructor-argindex="1"ref="emailMessageSender"/>
<propertyname="webServiceInvoker"ref="webServiceInvoker"/>
</bean>
Now,that we have seenhowtoinstructSpringcontainertocreatebeansand performDI,let’slookat
differentscopesthatyoucanspecifyforbeans.
2-5Beanscopes
Youmaywanttospecifythescopeofabeantocontrolwhetherasharedinstanceofthebeaniscreated
(singletonscope),oranewbeaninstanceiscreatedeverytimethebeanisrequested(prototypescope)
fromtheSpringcontainer.Thescopeofabeanisdefinedbythescopeattributeofthe<bean>element.If
thescopeattributeisnotspecified,itmeansthatthebeanisasingleton-scopedbean.
NOTEInwebapplicationscenarios,Springallowsyoutospecifyadditionalscopes:request,session
and globalSession. These scopes determine thelifetime of the bean instance. For instance, a request-
scoped beans lifetimeis limited toasingle HTTP request.Asin this chapter we’ll not be discussing
SpringWebMVCorSpringPortletMVC,we’llrestrictthediscussiontosingletonandprototypescopes.
Therequest,sessionandglobalSessionscopesaredescribedinchapter10.
IMPORTchapter2/ch02-bankapp-scopes(Thisproject shows usageof singletonandprototype bean
scopes.Toruntheapplication,executethemainmethodoftheBankAppclassofthisproject.Theproject
alsocontains2JUnittests,PrototypeTestandSingletonTestthatyoucanexecute)
Singleton
Thesingletonscopeisthedefaultscope for all the beansdefinedintheapplicationcontext XML file.
Instance of a singleton-scoped bean is created when the Spring container is created, and is destroyed
whentheSpringcontainerisdestroyed.Springcontainercreatesasingleinstanceofasingleton-scoped
bean,whichissharedbyallthebeansthatdependonit.
ThefollowingexamplelistingshowstheapplicationContext.xmlfileofch02-bankapp-scopesprojectin
whichallthebeansaresingleton-scoped:
Examplelisting2-21–applicationContext.xml-Singleton-scopedbeans
Project–ch02-bankapp-scopes
Sourcelocation-src/main/resources/META-INF/spring
<beans.....>
<beanid="controller"
class="sample.spring.chapter02.bankapp.controller.FixedDepositControllerImpl">
<propertyname=“fixedDepositService"ref="service"/>
</bean>
<beanid="service"
class="sample.spring.chapter02.bankapp.service.FixedDepositServiceImpl">
<propertyname=“fixedDepositDao"ref="dao"/>
</bean>
<beanid="dao"class="sample.spring.chapter02.bankapp.dao.FixedDepositDaoImpl"/>
.....
</beans>
IntheaboveapplicationContext.xmlfile,controller,serviceanddaobeansaresingleton-scopedbecause
no scope attribute is specified for the <bean> elements. This means that only a single instance of
FixedDepositControllerImpl,FixedDepositServiceImplandFixedDepositDaoImpl classes is createdby
theSpringcontainer.Asthesebeansaresingleton-scoped,Springcontainerreturnsthesameinstanceof
thebeaneverytimeweretrieveoneofthesebeansusingApplicationContext’sgetBeanmethod.
NOTEIfthescopeattributeisnotspecifiedorthevalueofscopeattributeissingleton,itmeansthatthe
beanissingleton-scoped.
ThefollowingexamplelistingshowsthetestInstancesmethodofSingletonTest(aJUnittestclass)classof
ch02-bankapp-scopes project. The testInstances method tests whether multiple invocation of
ApplicationContextsgetBeanmethodreturnsthesameordifferentinstanceofthecontrollerbean:
Examplelisting2-22–SingletonTestJUnittestclass
Project–ch02-bankapp-scopes
Sourcelocation-src/test/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
importstaticorg.junit.Assert.assertSame;
importorg.junit.BeforeClass;
importorg.junit.Test;
importsample.spring.chapter02.bankapp.controller.FixedDepositController;
publicclassSingletonTest{
privatestaticApplicationContextcontext;
@BeforeClass
publicstaticvoidinit(){
context=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
}
@Test
publicvoidtestInstances(){
FixedDepositControllercontroller1=(FixedDepositController)context.getBean("controller");
FixedDepositControllercontroller2=(FixedDepositController)context.getBean("controller");
assertSame("DifferentFixedDepositControllerinstances",controller1,controller2);
}
.....
}
Intheaboveexamplelisting,JUnit’s@BeforeClassannotationspecifiesthattheinitmethodisinvoked
beforeanyofthetestmethods(thatis,methodsannotatedwithJUnits@Testannotation)intheclass.This
means that @BeforeClass annotated method is invoked onlyonce, and @Test annotated methods are
executedonlyaftertheexecutionof@BeforeClassannotatedmethod.Notethattheinitmethodisastatic
method. The init method creates an instance of ApplicationContext object by passing the configuration
metadata (shown in example listing 2-21) to the ClassPathXmlApplicationContext’s constructor. The
testInstancesmethodobtains2instancesofcontrollerbeanandcheckswhetherboththeinstancesarethe
samebyusingJUnitsassertSameassertion.Asthecontrollerbeanissingleton-scoped,controller1and
controller2 bean instances are the same. For this reason, SingletonTest’s testInstances test executes
withoutanyassertionerrors.
ThefollowingfigureshowsthattheSpringcontainerreturnsthesameinstanceofcontrollerbeanwhen
youcalltheApplicationContextsgetBeanmethodmultipletimes:
Figure2-4Multiplerequestsforasingleton-scopedbeanresultsinthesamebeaninstancereturnedbythe
Springcontainer
The above figure shows that multiple calls to obtain controller bean returns the same instance of the
controllerbean.
NOTEInfigure2-4,thecontrollerbeaninstanceisrepresentedbya2-compartmentrectangle.Thetop
compartmentshowsthenameofthebean(thatis,thevalueoftheidattributeofthe<bean>element)and
thebottomcompartmentshowsthetypeofthebean(thatis,thevalueoftheclassattributeofthe<bean>
element). In the rest of this book, we’ll use this convention to show bean instances inside a Spring
container.
Asingleton-scopedbeaninstanceissharedamongstthebeansthatdependonit.Thefollowingexample
listing shows the testReference method of SingletonTest JUnit test class that checks if the
FixedDepositDao instance referenced by the FixedDepositController instance is the same as the one
obtaineddirectlybycallinggetBeanmethodofApplicationContext:
Examplelisting2-23–testReferencemethodofSingletonTestJUnittestclass
Project–ch02-bankapp-scopes
Sourcelocation-src/test/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
importstaticorg.junit.Assert.assertSame;
importorg.junit.Test;
publicclassSingletonTest{
privatestaticApplicationContextcontext;
.....
@Test
publicvoidtestReference(){
FixedDepositControllercontroller=(FixedDepositController)context.getBean("controller");
FixedDepositDaofixedDepositDao1=
controller.getFixedDepositService().getFixedDepositDao();
FixedDepositDaofixedDepositDao2=(FixedDepositDao)context.getBean("dao");
assertSame("DifferentFixedDepositDaoinstances",fixedDepositDao1,fixedDepositDao2);
}
}
Intheaboveexamplelisting,thetestReferencemethodfirstretrievestheFixedDepositDaoinstance(refer
fixedDepositDao1variableintheaboveexamplelisting)referencedbytheFixedDepositControllerbean,
followed by directly retrieving another instance of FixedDepositDao bean (refer fixedDepositDao2
variable in the above example listing) using ApplicationContexts getBean method. If you execute the
testReference test, you’ll see that the test completes successfully because the fixedDepositDao1 and
fixedDepositDao2instancesarethesame.
Figure2-5showsthattheFixedDepositDaoinstancereferencedbyFixedDepositControllerinstanceisthe
sameastheonereturnedbyinvokinggetBean("dao")methodonApplicationContext.
Figure2-5Singleton-scopedbeaninstanceissharedbetweenbeansthatdependonit
TheabovefigureshowsthattheFixedDepositDaoinstancereferencedbyFixedDepositController bean
instance and the one retrieved directly by calling ApplicationContexts getBean are same. If there are
multiple beans dependent on a singleton-scoped bean, then all the dependent beans share the same
singleton-scopedbeaninstance.
Lets now look at whether or not the same singleton-scoped bean instance is shared between multiple
Springcontainerinstances.
Singleton-scopedbeansandmultipleSpringcontainerinstances
Thescopeofasingleton-scopedbeaninstanceislimitedtotheSpringcontainerinstance.Thismeansthat
if you create 2 instances of the Spring container using the same configuration metadata, each Spring
containerhasitsowninstancesofthesingleton-scopedbeans.
ThefollowingexamplelistingshowsthetestSingletonScopemethodofSingletonTestclass,whichtests
whethertheFixedDepositControllerbeaninstanceretrievedfromtwodifferentSpringcontainerinstances
aresameordifferent:
Examplelisting2-24–testSingletonScopemethodofSingletonTestJUnittestclass
Project–ch02-bankapp-scopes
Sourcelocation-src/test/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
importstaticorg.junit.Assert.assertNotSame;
publicclassSingletonTest{
privatestaticApplicationContextcontext;
.....
@BeforeClass
publicstaticvoidinit(){
context=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
}
@Test
publicvoidtestSingletonScope(){
ApplicationContextanotherContext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
FixedDepositControllerfixedDepositController1=(FixedDepositController)anotherContext
.getBean("controller");
FixedDepositControllerfixedDepositController2=
(FixedDepositController)context.getBean("controller");
assertNotSame("SameFixedDepositControllerinstances",
fixedDepositController1,fixedDepositController2);
}
}
TheSingletonTest’sinitmethod(annotatedwithJUnit’s@BeforeClassannotation)createsaninstanceof
ApplicationContext(identifiedbycontextvariable)beforeany@Testannotatedmethodisexecuted.The
testSingletonScopemethodcreates one more instance ofSpring container (identifiedbyanotherContext
variable) using the same applicationContext.xml file. An instance of FixedDepositController bean is
retrieved from both the Spring containers and checked if they arenot the same. If you execute the
testSingletonScope test, youll find that the test completes successfully because the
FixedDepositControllerbeaninstanceretrievedfromcontextinstanceisdifferentfromtheoneretrieved
fromanotherContextinstance.
ThefollowingfiguredepictsthebehaviorexhibitedbythetestSingletonScopemethod:
Figure2-6EachSpringcontainercreatesitsowninstanceofasingleton-scopedbean
TheabovefigureshowsthateachSpringcontainercreatesitsowninstanceofcontrollerbean.Thisisthe
reasonwhycontextandanotherContextinstancesreturndifferentinstancesofcontrollerbeanwhenyou
callgetBean("controller")method.
ThetestSingletonScopemethodshowedthateachSpringcontainercreatesitsowninstanceofasingleton-
scopedbean.ItisimportanttonotethatSpringcontainercreatesaninstanceofasingleton-scopedbean
foreach bean definition. The following example listing shows multiple bean definitions for the
FixedDepositDaoImplclass:
Examplelisting2-25–applicationContext.xml-Multiplebeandefinitionsforthesameclass
Project–ch02-bankapp-scopes
Sourcelocation-src/main/resources/META-INF/spring
<beanid="dao"class="sample.spring.chapter02.bankapp.dao.FixedDepositDaoImpl"/>
<beanid="anotherDao"
class="sample.spring.chapter02.bankapp.dao.FixedDepositDaoImpl"/>
ThebeandefinitionsshownintheaboveexamplelistingareforFixedDepositDaoImplclass.Asscope
attributeisnotspecified,beandefinitionsshownintheaboveexamplelistingrepresentsingleton-scoped
beans.Evenifmultiplebeandefinitionsaredefinedforaclass,Springcontainercreatesabeaninstance
corresponding to each bean definition. This means that Spring container creates distinct instances of
FixedDepositDaoImpl class corresponding to dao and anotherDao bean definitions. The following
example listing shows SingletonScope’s testSingletonScopePerBeanDef method that tests whether the
FixedDepositDaoImpl instances corresponding to dao and anotherDao bean definitions are same or
different:
Examplelisting2-26–testSingletonScopePerBeanDefmethodofSingletonTestJUnittestclass
Project–ch02-bankapp-scopes
Sourcelocation-src/test/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
importstaticorg.junit.Assert.assertNotSame;
publicclassSingletonTest{
privatestaticApplicationContextcontext;
.....
@Test
publicvoidtestSingletonScopePerBeanDef(){
FixedDepositDaofixedDepositDao1=(FixedDepositDao)context.getBean("dao");
FixedDepositDaofixedDepositDao2=(FixedDepositDao)context.getBean("anotherDao");
assertNotSame("SameFixedDepositDaoinstances",fixedDepositDao1,fixedDepositDao2);
}
}
Intheaboveexamplelisting,fixedDepositDao1andfixedDepositDao2variablesrepresentinstancesof
FixedDepositDaoImplclassthatSpringcontainercreatescorrespondingtothedaoandanotherDaobean
definitions, respectively. If you execute the testSingleScopePerBeanDef test, itll execute without any
assertion errors because the fixedDepositDao1 instance (corresponding to dao bean definition) and
fixedDepositDao2instance(correspondingtoanotherDaobeandefinition)aredistinct.
Thefollowingfiguresummarizesthatasingleton-scopedbeaniscreatedperbeandefinition:
Figure2-7Thereisonesingleton-scopedbeaninstanceperbeandefinition
Theabovefigureshowsthatthereexistsoneinstanceofsingleton-scopedbeanperbeandefinitioninthe
Springcontainer.
We mentioned earlier that a singleton-scoped bean is pre-instantiated by default, which means an
instanceofasingleton-scopedbeaniscreatedwhenyoucreateaninstanceoftheSpringcontainer.Lets
nowlookathowyoucanlazilyinitializeasingleton-scopedbean.
Lazilyinitializingasingleton-scopedbean
You can instruct Spring container to create an instance of a singleton-scoped bean only when it is
requested for the first time. The following lazyExample bean definition shows how to instruct Spring
containertolazyinitializelazyBeanbean:
Examplelisting2-27–Lazilyinitializingasingleton-scopedbean
<beanid="lazyBean"class="example.LazyBean"lazy-init=”true/>
The<bean>element’slazy-initattributespecifieswhetherthebeaninstanceiscreatedlazilyoreagerly.If
thevalueistrue(asincaseofthebeandefinitionshownabove),thebeaninstanceisinitializedbythe
Springcontainerwhenitreceivestherequestforthebeanforthefirsttime.
Thefollowingsequencediagramshowshowlazy-initattributeaffectsthecreationofasingleton-scoped
beaninstance:
Figure2-8Alazily-initializedsingleton-scopedbeaninstanceiscreatedwhenitisrequestedforthefirst
timebytheapplication
In the above diagram, BeanA represents a singleton-scoped bean instance that isnot set to be lazily-
initialized,andLazyBeanrepresentsasingleton-scopedbeanthatissettobelazily-initialized.Whenthe
Spring container instance is created, BeanA is also instantiated because it isnot set to be lazily-
initialized. On the other hand, LazyBean is instantiated when ApplicationContexts getBean method is
invokedforthetimefirsttimetoretrieveaninstanceofLazyBeanfromtheSpringcontainer.
NOTEYoucanuse<beans>elementsdefault-lazy-initattributetospecifydefaultinitializationstrategy
forbeansdefinesintheapplicationcontextXMLfile.Ifthe<bean>element’slazy-initattributespecifies
adifferentvaluethanthe<beans>elementsdefault-lazy-init,thevaluespecifiedbythelazy-initattribute
appliestothebean.
Asasingleton-scopedbeancanbelazily-initializedorpre-instantiatedbytheSpringcontainer,youmay
bethinkingatthistimewhetheryoushoulddefineyoursingleton-scopedbeanstobelazily-initializedor
pre-instantiated.Inmostapplicationscenarios,itisbeneficialtopre-instantiatesingleton-scopedbeansto
discover configuration issues at the time of creation of the Spring container. The following example
listingshowsaaBeansingleton-scopedbeanthatissettobelazily-initialized,andthatdependsonbBean
bean:
Examplelisting2-28–Alazily-initializedsingleton-scopedbean
publicclassABean{
privateBBeanbBean;

publicvoidsetBBean(BBeanbBean){
this.bBean=bBean;
}
.....
}
<beanid="aBean"class="ABean"lazy-init="true">
<propertyname="bBean"value="bBean"/>
</bean>
<beanid="bBean"class="BBean"/>
Intheaboveexamplelisting,ABean’sbBeanpropertyreferstotheBBeanbean.Noticethatinsteadofref
attribute, value attribute of <property> element has been used to set ABeans bBean property. If you
createanApplicationContextinstancebypassingittheXMLfilecontainingtheabovebeandefinition,no
errors will be reported. But, when you try to fetch the aBean bean by invoking ApplicationContext’s
getBeanmethod,you’llgetthefollowingerrormessage:
Causedby:java.lang.IllegalStateException:Cannotconvertvalueoftype[java.lang.String]torequiredtype[BBean]forproperty'bBean:no
matchingeditorsorconversionstrategyfound
The above error message is shown because the Spring container fails to convert the String value of
ABean’sbBeanpropertytoBBeantype.Thishighlightsasimpleconfigurationissueinwhichinsteadof
specifying<bean>elementsrefattribute,valueattributewasspecified.IftheaBeanbeanwasdefinedas
pre-instantiated(insteadoflazily-initialized),theaboveconfigurationissuecouldhavebeencaughtatthe
timewecreatedaninstanceofApplicationContext,andnotwhenwetriedtoobtainaninstanceofaBean
beanfromtheApplicationContext.
Letsnowlookatprototype-scopedbeansinSpring.
Prototype
Aprototype-scopedbeanisdifferentfromasingleton-scopedbeaninthesensethattheSpringcontainer
always returns a new instance of a prototype-scoped bean. Another distinctive feature of prototype-
scopedbeansisthattheyarealwayslazily-initialized.
The following FixedDepositDetails bean in the applicationContext.xml file of ch02-bankapp-scopes
projectrepresentsaprototype-scopedbean:
Examplelisting2-29–applicationContext.xml-Aprototype-scopedbeanexample
Project–ch02-bankapp-scopes
Sourcelocation-src/main/resources/META-INF/spring
<beanid="FixedDepositDetails"
class="sample.spring.chapter02.bankapp.domain.FixedDepositDetails"
scope="prototype"/>
Theaboveexamplelistingshowsthatthe<bean>elementsscopeattributevalueissettoprototype.This
meansthattheFixedDepositDetailsbeanisaprototype-scopedbean.
The following testInstances method of PrototypeTest JUnit test class shows that the 2 instances of
FixedDepositDetailsbeanretrievedfromtheSpringcontaineraredifferent:
Examplelisting2-30–testInstancesmethodofPrototypeTestJUnittestclass
Project–ch02-bankapp-scopes
Sourcelocation-src/test/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
importstaticorg.junit.Assert.assertNotSame;
publicclassPrototypeTest{
privatestaticApplicationContextcontext;
.....
@Test
publicvoidtestInstances(){
FixedDepositDetailsfixedDepositDetails1=
(FixedDepositDetails)context.getBean("fixedDepositDetails");
FixedDepositDetailsfixedDepositDetails2=
(FixedDepositDetails)context.getBean("fixedDepositDetails");
assertNotSame("SameFixedDepositDetailsinstances",
fixedDepositDetails1,fixedDepositDetails2);
}
}
If you execute the testInstances test, it’ll complete without any assertion errors because the 2
FixedDepositDetails instances (fixedDepositDetails1 and fixedDepositDetails2) obtained from the
ApplicationContextaredifferent.
Letsnowlookathowtochoosetherightscope(singletonorprototype)forabean.
Choosingtherightscopeforyourbeans
Ifabeandoesn’tmaintainanyconversationalstate(thatis,itisstatelessinnature),itshouldbedefinedas
a singleton-scoped bean. If a bean maintains conversational state, it should be defined as a prototype-
scopedbean.FixedDepositServiceImpl,FixedDepositDaoImplandFixedDepositControllerImplbeansof
MyBank application are stateless in nature; therefore, they are defined as singleton-scoped beans.
FixedDepositDetails bean (adomain object) of MyBank application maintains conversational state;
therefore,itisdefinedasaprototype-scopedbean.
NOTEIfyouareusinganORMframework(likeHibenateoriBATIS)inyourapplication,thedomain
objectsarecreatedeitherbytheORMframeworkoryoucreatethemprogrammaticallyinyour
applicationcodeusingthenewoperator.Itisbecauseofthisreasondomainobjectsarenotdefinedinthe
applicationcontextXMLfileiftheapplicationusesanORMframeworkforpersistence.
2-6Summary
In this chapter,we discussed some ofthe basics ofSpring Framework.We looked at ‘programming to
interfacesdesignapproach,differentapproachestocreatebeaninstances,constructor-basedDIandbean
scopes.Inthenextchapter,we’lllookathowtosetdifferenttypes(likeint,long,Map,Set,andsoon)of
beanpropertiesandconstructorarguments.
Chapter3-Configuringbeans
3-1Introduction
Inpreviouschapters,wetoucheduponsomeofthebasicconceptsofSpringFramework.Wesawhow
SpringbeansandtheirdependenciesarespecifiedintheapplicationcontextXMLfile.Wealsolookedat
singleton-andprototype-scopedbeans,anddiscussedtheimplicationsofassigningthesescopestobeans.
Inthischapter,we’lllookat:
§beandefinitioninheritance
§howargumentstoabeanclass’sconstructorareresolved
§howtoconfigurebeanpropertiesandconstructorargumentsofprimitivetype(likeint,float,andso
on),collectiontype(likejava.util.List,java.util.Map,andsoon),customtype(likeAddress),and
soon
§ how you can make the application context XML file less verbose by using p-namespace and c-
namespacetospecifybeanpropertiesandconstructorarguments,respectively
§SpringsFactoryBeaninterfacethatallowsyoutowriteyourownfactoryclassfor creatingbean
instances
3-2Beandefinitioninheritance
Wesawinchapter1and2thatabeandefinitionintheapplicationcontextXMLfilespecifiesthefully-
qualifiednameofthebeanclassanditsdependencies.Insomescenarios,tomakeabeandefinitionless
verbose,youmaywantabeandefinitiontoinheritconfigurationinformationfromanotherbeandefinition.
LetslookatonesuchscenarioinMyBankapplication.
IMPORTchapter3/ch03-bankapp-inheritance(Thisproject showstheMyBankapplicationthatuses
beandefinitioninheritance.Toruntheapplication,executethemainmethodoftheBankAppclassofthis
project)
MyBankBeandefinitioninheritanceexample
Inthepreviouschapter,wesawthattheMyBankapplicationaccessesdatabasethroughDAOs.Let’ssay
that the MyBank application defines a DatabaseOperations class that simplifies interacting with the
database.So,alltheDAOsintheMyBankapplicationdependonDatabaseOperationsclasstoperform
databaseoperations,asshowninthefollowingfigure:
Figure 3-1 - DAO classes in MyBank application make use of DatabaseOperations class to perform
databaseinteraction
TheabovefigureshowsthattheFixedDepositDaoandPersonalBankingDaoclassesaredependentonthe
DatabaseOperations class. The following application context XML file shows the bean definitions for
theseclasses:
Examplelisting3-1–DAObeansaredependentonDatabaseOperationsbean
<beanid="databaseOperations"
class="sample.spring.chapter01.bankapp.utils.DatabaseOperations"/>
<beanid="personalBankingDao"
class="sample.spring.chapter01.bankapp.dao.PersonalBankingDaoImpl">
<propertyname="databaseOperations"ref="databaseOperations"/>
</bean>
<beanid="FixedDepositDao"
class="sample.spring.chapter01.bankapp.dao.FixedDepositDaoImpl">
<propertyname="databaseOperations"ref="databaseOperations"/>
</bean>
Both the personalBankingDao and FixedDepositDao bean definitions use the <property> element to
performdependencyinjectionoftheDatabaseOperationsinstance.Asthenameofthepropertythatrefers
totheDatabaseOperationsinstanceisdatabaseOperationsinboththebeandefinitions,itimpliesthatboth
PersonalBankingDaoImpl and FixedDepositDaoImpl classes define a setDatabaseOperations method to
allowSpringcontainertoinjectDatabaseOperationsinstance.
If multiple beans in your application share a common set of configuration (properties, constructor
arguments,andsoon),youcancreateabeandefinitionthatactsasaparentforotherbeandefinitions.In
case of personalBankingDao and fixedDepositDao bean definitions, the common configuration is the
databaseOperations property. The following example listing shows that the personalBankingDao and
fixedDepositDaobeandefinitionsmakeuseofbeandefinitioninheritance:
Examplelisting3-2–applicationContext.xml-MyBanksapplicationcontextXMLfile
Project–ch03-bankapp-inheritance
Sourcelocation-src/main/resources/META-INF/spring
<beanid="databaseOperations"
class="sample.spring.chapter03.bankapp.utils.DatabaseOperations"/>
<beanid="daoTemplate"abstract="true">
<propertyname="databaseOperations"ref="databaseOperations"/>
</bean>

<beanid="FixedDepositDao"parent="daoTemplate"
class="sample.spring.chapter03.bankapp.dao.FixedDepositDaoImpl"/>

<beanid="personalBankingDao"parent="daoTemplate"
class="sample.spring.chapter03.bankapp.dao.PersonalBankingDaoImpl"/>
Intheaboveexamplelisting,thedaoTemplatebeandefinitiondefinesthecommonconfigurationsharedby
both the fixedDepositDao and personalBankingDao bean definitions. As both the fixedDepositDao and
personalBankingDaobeandefinitionsrequirethedatabaseOperationsdependency(referexamplelisting
3-1),thedaoTemplatebeandefinitiondefinesthedatabaseOperationsdependencyusingthe<property>
element.The<bean>element’sparentattributespecifiesthenameofthebeandefinitionfromwhichthe
configuration is inherited. As the parent attribute value is daoTemplate for fixedDepositDao and
personalBankingDao bean definitions, they inherit databaseOperations property from the daoTemplate
beandefinition.Theexamplelistings3-1and3-2aresame,exceptthattheexamplelisting3-2makesuse
ofbeandefinitioninheritance.
Ifthe<bean>element’sabstractattributevalueissettotrue,itmeansthatthebeandefinitionisabstract.
It is important to note that the Spring containerdoesn’t attempt to create a bean corresponding to an
abstractbeandefinition.Itisimportanttonotethatyoucan’tdefineabeantobedependentonanabstract
bean,thatis,youcan’tuse<property>or<constructor-arg>elementtorefertoanabstractbean.
In example listing 3-2, daoTemplate bean definition is abstract. You may have noticed that the
daoTemplatebeandefinitiondoesn’tspecifytheclassattribute.Ifaparentbeandefinitiondoesn’tspecify
theclassattribute,childbeandefinitions(likethefixedDepositDaoandpersonalBankingDao)specifythe
class attribute. It is important to note that if you dont specify the class attribute, you must define the
parent bean definition as abstract so that Spring container doesnt attempt to create a bean instance
correspondingtoit.
ToverifythatthefixedDepositDaoandpersonalBankingDaobeandefinitionsinheritdaoTemplate bean
definitionsdatabaseOperationsproperty,executethemainmethodofBankAppclass ofch03-bankapp-
inheritance project. BankApp’s main method invokes methods on the fixedDepositDao and
personalBankingDaobeans;thosebeansinturninvokemethodsontheDatabaseOperationsinstance.Ifa
DatabaseOperations instance isnot injected into the fixedDepositDao and personalBankingDao beans,
java.lang.NullPointerExceptionwillbethrown.
ThefollowingdiagramsummarizeshowbeandefinitioninheritanceworksincaseofFixedDepositDao
andpersonalBankingDaobeandefinitions:
Figure3-2–BeandefinitioninheritanceinMyBankapplication
The above figure shows that the fixedDepositDaoand personalBankingDao bean definitions inherit the
databaseOperations property (shown initalics in the boxes labeled fixedDepositDao and
personalBankingDao)fromthedaoTemplatebeandefinition.TheabovefigurealsodepictsthattheSpring
container doesnt attempt to create a bean instance corresponding to the daoTemplate bean definition
becauseitismarkedasabstract.
Letsnowlookatwhatconfigurationinformationgetsinheritedfromtheparentbeandefinition.
Whatgetsinherited?
Achildbeandefinitioninheritsthefollowingconfigurationinformationfromtheparentbeandefinition:
·properties–specifiedvia<property>elements
·constructorarguments–specifiedvia<constructor-arg>elements
·methodoverrides(discussedinsection4-5ofchapter4)
·initializationanddestroymethods(discussedinchapter5),and
·factorymethods–specifiedviafactory-methodattributeof<bean>element(refersection2-3of
chapter2toknowhowstaticandinstancefactorymethodsareusedforcreatingbeans)
IMPORTchapter3/ch03-bankapp-inheritance-example(ThisprojectshowstheMyBankapplication
thatusesbeandefinitioninheritance.Inthisproject,youllseemultiplescenariosinwhichbeandefinition
inheritanceisused.Toruntheapplication,executethemainmethodoftheBankAppclassofthisproject)
Letsnowlookatsomeofthebeandefinitioninheritanceexamples.
Beandefinitioninheritanceexampleparentbeandefinitionisnotabstract
Thefollowingexamplelistingshowsabeaninheritanceexampleinwhichtheparentbeandefinitionis
notabstract,andthechildbeandefinitionsdefineanadditionaldependency:
Examplelisting3-3–applicationContext.xml-Beandefinitioninheritance–parentbeandefinitionisnot
abstract
Project–ch03-bankapp-inheritance-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanid="serviceTemplate"
class="sample.spring.chapter03.bankapp.base.ServiceTemplate">
<propertyname="jmsMessageSender"ref="jmsMessageSender"/>
<propertyname="emailMessageSender"ref="emailMessageSender"/>
<propertyname="webServiceInvoker"ref="webServiceInvoker"/>
</bean>

<beanid="fixedDepositService"class=".....FixedDepositServiceImpl"
parent="serviceTemplate">
<propertyname=“fixedDepositDao"ref="fixedDepositDao"/>
</bean>
<beanid="personalBankingService"class=".....PersonalBankingServiceImpl"
parent="serviceTemplate">
<propertyname="personalBankingDao"ref="personalBankingDao"/>
</bean>
<beanid="userRequestController"class=".....UserRequestControllerImpl">
<propertyname="serviceTemplate"ref="serviceTemplate"/>
</bean>
A littlebackgroundbefore we delve into the details ofthe above listedconfiguration: a service inthe
MyBank application may send JMS messages to a messaging-middleware or send emails to an email
server or it may invokean external web service. Intheabove example listing, the jmsMessageSender,
emailMessageSender and webServiceInvoker beans simplify these tasks by providing a layer of
abstraction.TheserviceTemplatebeanprovidesaccesstojmsMessageSender,emailMessageSenderand
webServiceInvoker beans. This is the reason why the serviceTemplate bean is dependent on the
jmsMessageSender,emailMessageSenderandwebServiceInvokerbeans.
Example listing 3-3 shows that the serviceTemplate bean definition is the parent bean definition of
fixedDepositServiceandpersonalBankingServicebeandefinitions.NoticethattheserviceTemplatebean
definitionisnotabstract;theclassattributespecifiesServiceTemplateastheclass.Inourpreviousbean
definition inheritance example (refer example listing 3-2), child bean definitions didn’t define any
properties.Intheaboveexamplelisting,noticethatthefixedDepositServiceandpersonalBankingService
childbeandefinitionsdefinefixedDepositDaoandpersonalBankingDaoproperties,respectively.
As parent bean definitions properties are inherited by the child bean definitions,
FixedDepositServiceImpl and PersonalBankingServiceImpl classes must define setter methods for
jmsMessageSender, emailMessageSender and webServiceInvoker properties. You have the option to
either define setter methods in FixedDepositServiceImpl and PersonalBankingServiceImpl classes or
make FixedDepositServiceImpl and PersonalBankingServiceImpl classes as subclasses of
ServiceTemplate class. In ch03-bankapp-inheritance-examples, the FixedDepositServiceImpl and
PersonalBankingServiceImplclassesaresubclassesofServiceTemplateclass.
ThefollowingexamplelistingshowsthePersonalBankingServiceImplclass:
Examplelisting3-4–PersonalBankingServiceImplclass
Project–ch03-bankapp-inheritance-examples
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/service
packagesample.spring.chapter03.bankapp.service;
publicclassPersonalBankingServiceImplextendsServiceTemplateimplements
PersonalBankingService{
privatePersonalBankingDaopersonalBankingDao;
publicvoidsetPersonalBankingDao(PersonalBankingDaopersonalBankingDao){
this.personalBankingDao=personalBankingDao;
}
@Override
publicBankStatementgetMiniStatement(){
returnpersonalBankingDao.getMiniStatement();
}
}
In example listing 3-3, we saw that the personalBankingService bean definition specifies
personalBankingDao as a dependency. In the above example listing, the setPersonalBankingDao setter
method corresponds to the personalBankingDao dependency. Also, notice that the
PersonalBankingServiceImplclassisasubclassoftheServiceTemplateclass.
Thefollowingdiagramshowsthataparentbeandefinition(likeserviceTemplate)neednotbeabstract,
child bean definitions (like fixedDepositService and personalBankingService) may define additional
properties, and classes represented by parent (like ServiceTemplate class) and child bean definitions
(like FixedDepositServiceImpl and PersonalBankingServiceImpl) may themselves be related by
inheritance:
Figure3-3–Childbeandefinitionsaddadditionalproperties,parentbeandefinitionisnotabstract,and
parent-childrelationshipexistsbetweentheclassesrepresentedbytheparentandchildbeandefinitions
Figure3-3shows:
·SpringcontainercreatesaninstanceofserviceTemplatebeanbecauseitsnotdefinedasabstract
·FixedDepositServiceImplandPersonalBankingServiceImplclasses(correspondingtothechild
bean definitions) are subclasses of ServiceTemplate class – the class corresponding to the
serviceTemplateparentbeandefinition.
·        And, fixedDepositService and personalBankingService bean definitions define additional
properties,fixedDepositDaoandpersonalBankingDao,respectively.Youshouldnotethatthechild
beandefinitionscanalsodefineadditionalconstructorargumentsandmethodoverrides(discussed
insection4-5).
AsserviceTemplatebeandefinitionisnotabstract,otherbeanscandefineserviceTemplatebeanastheir
dependency. For instance, in example listing 3-3, the serviceTemplate bean is a dependency of
userRequestController bean. You can infer from this discussion that if a parent bean definition is not
abstract,thefunctionalityofferedbytheparentbeancanbeutilizednotonlybychildbeansbutalsoby
otherbeansintheapplicationcontext.
Beandefinitioninheritanceexampleinheritingfactorymethodconfiguration
Childbeandefinitionscanusebeandefinitioninheritancetoinheritfactorymethodconfigurationfromthe
parentbeandefinition.Letslookatanexamplethatshowsfactorymethodconfigurationsareinheritedby
childbeandefinitions.
ThefollowingControllerFactoryclassdefinesagetControllerinstancefactorymethod:
Examplelisting3-5–ControllerFactoryclass
Project–ch03-bankapp-inheritance-examples
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/controller
packagesample.spring.chapter03.bankapp.controller;
publicclassControllerFactory{
publicObjectgetController(StringcontrollerName){
Objectcontroller=null;
if("fixedDepositController".equalsIgnoreCase(controllerName)){
controller=newFixedDepositControllerImpl();
}
if("personalBankingController".equalsIgnoreCase(controllerName)){
controller=newPersonalBankingControllerImpl();
}
returncontroller;
}
}
The above example listing shows that the getController factory method creates an instance of
FixedDepositControllerImpl or PersonalBankingControllerImpl class, depending upon the value of the
controllerNameargumentpassedtoit.IfthevalueofcontrollerNameargumentisfixedDepositController,
thegetController methodcreates an instance ofFixedDepositControllerImpl class. And, if the value of
controllerNameargumentispersonalBankingController,thegetControllermethodcreatesaninstanceof
PersonalBankingControllerImplclass.
The following bean definitions inthe applicationContext.xml file of ch03-bankapp-inheritance-example
project show that the child bean definitions inherit the getControllerinstance factory method
configurationfromtheparentbeandefinition:
Example listing 3-6 – applicationContext.xml - Bean definition inheritance – inheriting the factory
methodconfiguration
Project–ch03-bankapp-inheritance-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanid="controllerFactory"
class="sample.spring.chapter03.bankapp.controller.ControllerFactory"/>
<beanid="controllerTemplate"factory-bean="controllerFactory"
factory-method="getController"abstract="true">
</bean>
<beanid="fixedDepositController"parent="controllerTemplate">
<constructor-argindex="0"value="fixedDepositController"/>
<propertyname=“fixedDepositService"ref="fixedDepositService"/>
</bean>
<beanid="personalBankingController"parent="controllerTemplate">
<constructor-argindex="0"value="personalBankingController"/>
<propertyname="personalBankingService"ref="personalBankingService"/>
</bean>
In the above example listing, the ControllerFactory class represents a factory class that defines a
getControllerinstance factory method. The controllerTemplate bean definition specifies that the
ControllerFactorysgetController factorymethodis used forcreatingbeaninstances.ThegetController
method (refer example listing 3-5) creates an instance of FixedDepositControllerImpl or
PersonalBankingControllerImplbean,dependingontheargumentpassedtothegetControllermethod.
As the controllerTemplate bean definition has been defined as abstract, it is up to the
fixedDepositController and personalBankingController child bean definitions to use the getController
factorymethodconfiguration.ThefixedDepositControllerbeandefinitionwouldliketopassanargument
to the ControllerFactorys getController factory method so that it creates an instance of
FixedDepositControllerImplbean.And,personalBankingControllerbeandefinitionwouldliketopassan
argument to the ControllerFactorys getController factory method so that it creates an instance of
PersonalBankingControllerImpl bean. We saw in section 2-3 of chapter 2 that the <constructor-arg>
element is used to pass an argument to aninstance factory method. In example listing 3-6, the
<constructor-arg>elementhasbeenusedbyfixedDepositControllerandpersonalBankingControllerchild
beandefinitionstopassfixedDepositService’and‘personalBankingService’values,respectively,tothe
getControllerfactorymethod.
It is recommended that you now run the main method of BankApp class of ch03-bankapp-inheritance-
examplesprojecttoseeusageofthebeandefinitioninheritanceexamplesdiscussedinthissection.
Letsnowlookathowconstructorargumentsarematched.
3-3Constructorargumentmatching
Inthepreviouschapter,wesawthattheconstructorargumentsarespecifiedinthebeandefinitionsusing
the<constructor-arg>element.Inthissection,we’lllookathowSpringcontainermatchesaconstructor
argumentspecifiedbya<constructor-arg>elementtothecorrespondingconstructorargumentspecifiedin
thebeanclasssconstructor.
Beforewegointothedetailsofconstructorargumentmatching,let’slookbackathowwepassarguments
toabeanclasssconstructor.
IMPORT chapter 3/ch03-bankapp-constructor-args-by-type (This project shows the MyBank
application in which bean class’s constructor arguments are matched by type (explained later in this
section).Toruntheapplication,executethemainmethodoftheBankAppclassofthisproject)
Passingsimplevaluesandbeanreferencesusing<constructor-arg>element
If a constructor argument is of simple Java type (like int, String, and so on), the <constructor-arg>
element’svalueattributeisusedtospecifythevalueoftheconstructorargument.Ifaconstructorargument
is a reference to a bean, you specify the name of the bean using the <constructor-arg> elements ref
attribute.
ThefollowingexamplelistingshowstheUserRequestControllerImplclassofch03-bankapp-constructor-
args-by-typeprojectwhoseconstructoracceptsanargumentoftypeServiceTemplate:
Examplelisting3-7–UserRequestControllerImplclass
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/controller
packagesample.spring.chapter03.bankapp.controller;
publicclassUserRequestControllerImplimplementsUserRequestController{
privateServiceTemplateserviceTemplate;

publicUserRequestControllerImpl(ServiceTemplateserviceTemplate){
this.serviceTemplate=serviceTemplate;
}

@Override
publicvoidsubmitRequest(Requestrequest){
//--dosomethingusingServiceTemplate
serviceTemplate.getJmsMessageSender();//--Forex.,sendJMSmessage
.....
}
}
The following example listing shows that a reference to ServiceTemplate instance (represented by
serviceTemplatebeandefinition)ispassedtoUserRequestControllerImplsconstructorusingrefattribute
of<constructor-arg>element:
Example listing 3-8 – applicationContext.xml - Passing reference to a Spring bean as constructor
argument
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/resources/META-INF/spring
<beanid="serviceTemplate"class="sample.spring.chapter03.bankapp.base.ServiceTemplate">
.....
</bean>
<beanid="userRequestController"
class="sample.spring.chapter03.bankapp.controller.UserRequestControllerImpl">
<constructor-argindex="0"ref="serviceTemplate"/>
</bean>
With this background information on how to pass simple values and bean references as constructor
arguments,letsnowlookathowSpringcontainermatchesconstructorargumenttypestolocatethebeans
constructortobeinvoked.
Constructorargumentmatchingbasedontype
Ifthe<constructor-arg>elementsindexattributeisnotspecified,Springcontainerlocatestheconstructor
tobeinvokedbymatchingthetypesreferencedbythe<constructor-arg>elementswiththeargumenttypes
specifiedinthebeanclass’sconstructor(s).
LetsfirstlookathowSpringcontainermatchesconstructorargumentswhentheconstructorargumentsare
Springbeansthatarenotrelatedbyinheritance.
ConstructorargumentsrepresentingdistinctSpringbeans
The following example listing shows the ServiceTemplate class that defines a constructor that accepts
referencestoJmsMessageSender,EmailMessageSenderandWebServiceInvokerbeans:
Examplelisting3-9–ServiceTemplateclass
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/base
packagesample.spring.chapter03.bankapp.base;
publicclassServiceTemplate{
.....
publicServiceTemplate(JmsMessageSenderjmsMessageSender,
EmailMessageSenderemailMessageSender,
WebServiceInvokerwebServiceInvoker){
.....
}
}
The following example listing shows the bean definitions for the ServiceTemplate class and the beans
referencedbyServiceTemplate:
Examplelisting3-10–applicationContext.xml-BeandefinitionfortheServiceTemplate class and its
dependencies
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/resources/META-INF/spring
<beanid="serviceTemplate"class="sample.spring.chapter03.bankapp.base.ServiceTemplate">
<constructor-argref="emailMessageSender"/>
<constructor-argref="jmsMessageSender"/>
<constructor-argref="webServiceInvoker"/>
</bean>
<beanid="jmsMessageSender"class="sample.spring.chapter03.bankapp.base.JmsMessageSender"/>
<bean id="emailMessageSender" class="sample.spring.chapter03.bankapp.base.EmailMessageSender"
/>
<beanid="webServiceInvoker"class="sample.spring.chapter03.bankapp.base.WebServiceInvoker"/>
Intheaboveexamplelisting,the<constructor-arg>elementsofserviceTemplatebeandon’tspecifythe
index attribute. The order in which the constructor arguments are specified by  the <constructor-arg>
elements is: EmailMessageSender, JmsMessageSender, WebServiceInvoker. The order in which
constructor arguments are specified in the ServiceTemplate classs constructor is: JmsMessageSender,
EmailMessageSender,WebServiceInvoker.Asyoucansee,theorderinwhichconstructorargumentsare
definedbythe<constructor-arg>elementsisdifferentfromtheorderspecifiedbytheServiceTemplate
classsconstructor.
If you execute the main method of BankApp class of ch03-bankapp-constructor-args-by-type project,
you’ll find that the Spring container successfully creates an instance of ServiceTemplate bean. This is
becauseJmsMessageSender,EmailMessageSenderandWebServiceInvokerclassesaredistinctinnature
(thatis,theyarenotrelatedbyinheritance),whichmakesiteasierfortheSpringcontainertoinjecttheir
instancesintotheServiceTemplateclasssconstructorinthecorrectorder.
Iftheconstructorargumenttypesarerelatedbyinheritance,Springcontainerneedsextrainstructionsto
help resolve constructor arguments. Lets now look at how Spring container matches constructor
argumentswhenbeansreferencedbytheconstructorargumentsarerelatedbyinheritance.
ConstructorargumentsrepresentingrelatedSpringbeans
ConsiderthefollowingSampleBeanbeanclasswhoseconstructoracceptsargumenttypesthatarerelated
byinheritance:
Examplelisting3-11–SampleBeanclass
publicclassSampleBean{
publicSampleBean(ABeanaBean,BBeanbBean){.....}
.....
}
The above example listing shows that the SampleBean classs constructor accepts ABean and BBean
typesasarguments.ABeanandBBeanrepresentSpringbeansthatarerelatedbyinheritance;BBeanisa
subclassofABean.
The following application context XML file shows the bean definitions for SampleBean, ABean and
BBeanclasses:
Examplelisting3-12–BeandefinitionsforSampleBean,ABeanandBBeanclasses
<beanid="aBean"class="example.ABean"/>
<beanid="bBean"class="example.BBean"/>

<beanid="sampleBean"class="example.SampleBean">
<constructor-argref="bBean"/>
<constructor-argref="aBean"/>
</bean>
AsaBeanandbBeanbeansarerelatedbyinheritance,Springcontainerappliesconstructorargumentsto
the SampleBeans constructor in the order in which <constructor-arg> elements appear in the bean
definitionfortheSampleBeanclass.IntheabovesampleBeanbeandefinition,thefirst<constructor-arg>
elementreferstobBeanbeanandthesecond<constructor-arg>elementreferstoaBeanbean.Thismeans
that bBean is passed as the first constructor argument and aBean is passed as the second constructor
argumenttotheSampleBeanconstructor.AsinstanceofABean(thesuperclass)can’t bepassedwhere
BBean(thesubclass)instanceisexpected,thesecond<constructor-arg>elementinthesampleBeanbean
definitionresultsinexceptionbeingthrownbytheSpringcontainer.Tohandlesuchscenarios,youcan
use <constructor-arg> elements index or type attribute to identify the constructor argument to which
<constructor-arg>elementapplies.Forinstance,thefollowingsampleBeanbeandefinitionmakesuseof
type attribute to indicate the type of the constructor argument to which the <constructor-arg> element
applies:
Examplelisting3-13 –<constructor-arg> element’stype attribute identifies the type of the constructor
argument
<beanid="sampleBean"class="example.SampleBean">
<constructor-argtype="sample.spring.chapter03.bankapp.controller.BBean"ref="bBean"/>
<constructor-argtype="sample.spring.chapter03.bankapp.controller.ABean"ref="aBean"/>
</bean>
The<constructor-arg>element’stypeattributespecifiesthefully-qualifiednameofthetypetowhichthe
<constructor-arg>elementapplies.Intheaboveexamplelisting,thefirst<constructor-arg>appliestothe
constructorargumentoftypeBBean,andthesecond<constructor-arg>elementappliestotheconstructor
argument of type ABean. Specifying the type attribute takes away the ambiguity that arises when
constructorargumentsarerelatedbyinheritance.
NOTEIftwoormoreconstructorargumentsareofthesametype,theonlyoptionistouseindex
attributetoidentifytheconstructorargumenttowhicheach<constructor-arg>elementapplies.
Sofarwehavelookedatconstructorargumenttypematchingscenariosinwhichconstructorarguments
represented distinct or related Spring beans. We’ll now look at how constructor argument types are
matchedforstandardJavatypes(likeint,long,boolean,String,Date,andsoon)andcustomtypes.
ConstructorargumentsrepresentingstandardJavatypesandcustomtypes
Ifthetypeofaconstructorargumentisaprimitivetype(likeint,long,boolean,andsoon)oraStringtype
or a custom type (like Address), the <constructor-arg> element’s value attribute is used to specify the
value. If there are 2 or more constructor arguments into which the string value specified by the value
attributecanbeconverted,it’llnotbepossiblefortheSpringcontainertoderivethetype(forexample,
whetherthevaluerepresentsanintorlongorString)oftheconstructorargument.Insuchscenarios,you
needtoexplicitlyspecifythetypeoftheconstructorargumentusingthetypeattribute.
ThefollowingexamplelistingshowstheTransferFundsServiceImplclassthatdefinesaconstructorwhich
acceptsargumentsoftypesString,boolean,longandint:
Examplelisting3-14–TransferFundsServiceImplclass
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/service
packagesample.spring.chapter03.bankapp.service;
publicclassTransferFundsServiceImplimplementsTransferFundsService{
publicTransferFundsServiceImpl(StringwebServiceUrl,booleanactive,longtimeout,
intnumberOfRetrialAttempts){.....}
.....
}
As the above example listing shows, TransferFundsServiceImpl constructor accepts the following
arguments:webServiceUrl,active,timeoutandnumberOfRetrialAttempts.Thefollowingbeandefinition
for the TransferFundsServiceImpl class shows how constructor argument values can be passed to the
TransferFundsServiceImplsconstructor:
Examplelisting3-15–BeandefinitionfortheTransferFundsServiceImplclass
<beanid="transferFundsService"
class="sample.spring.chapter03.bankapp.service.TransferFundsServiceImpl">
<constructor-argvalue="http://someUrl.com/xyz"/>
<constructor-argvalue="true"/>
<constructor-argvalue="5"/>
<constructor-argvalue="200"/>
</bean>
Letsassumethatthe3rd<constructor-arg>element(valueattribute’svalueis‘5’)issupposedtosupply
valueforthenumberOfRetrialAttemptsconstructorargument,andthe4th<constructor-arg>element(value
attribute’s value is ‘200’) is supposed to supply value for the timeout constructor argument. Spring
containerapplies<constructor-arg>elementstotheTransferFundsServiceImpl’sconstructorintheorder
inwhich<constructor-arg>elementsappearinthetransferFundsServicebeandefinition.Thismeansthat
the 3rd <constructor-arg> element applies to timeout argument, and the 4th <constructor-arg> element
appliestonumberOfRetrialAttemptsargument.Tohandlesuchambiguities,youcanspecifythetypeofa
constructorargumentvia<constructor-arg>element’stypeattribute,asshowninthefollowingexample
listing:
Examplelisting3-16–applicationContext.xml-<constructor-arg>element’stypeattribute
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/resources/META-INF/spring
<beanid="transferFundsService"
class="sample.spring.chapter03.bankapp.service.TransferFundsServiceImpl">
<constructor-argtype="java.lang.String"value="http://someUrl.com/xyz"/>
<constructor-argtype="boolean"value="true"/>
<constructor-argtype="int"value="5"/>
<constructor-argtype="long"value="200"/>
</bean>
IntheabovebeandefinitionfortheTransferFundsServiceImplclass,typeattributeisusedtospecifythe
constructor argument type. Spring container can now use type matching to correctly apply constructor
arguments.
NOTEIftwoormoreconstructorargumentsareofthesametype,theonlyoptionistouseindexattribute
foridentifyingtheconstructorargumenttowhicheach<constructor-arg>elementapplies.
Inthissection,wesawhowtypematchingisperformedbySpringtoresolveconstructorarguments.Lets
nowlookathowyoucaninstructSpringtoperformconstructorargumentmatchingbasedonconstructor
argumentsname.
IMPORT chapter 3/ch03-bankapp-constructor-args-by-name (This project shows the MyBank
application in which bean class’s constructor arguments are matched byname.To run the application,
executethemainmethodoftheBankAppclassofthisproject)
Constructorargumentmatchingbasedonname
The <constructor-arg> elements name attribute is used for specifying the name of the constructor
argument to which the <constructor-arg> element applies. The following example listing shows once
againtheTransferFundsServiceImplclasswhoseconstructoracceptsmultiplearguments:
Examplelisting3-17–TransferFundsServiceImplclass
Project–ch03-bankapp-constructor-args-by-name
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/service
packagesample.spring.chapter03.bankapp.service;
publicclassTransferFundsServiceImplimplementsTransferFundsService{
.....
publicTransferFundsServiceImpl(StringwebServiceUrl,booleanactive,longtimeout,
intnumberOfRetrialAttempts){.....}
}
The above example listing shows that the names of the constructor arguments defined by
TransferFundsServiceImpls constructor are: webServiceUrl, active, timeout and
numberOfRetrialAttempts.
NOTETheTransferFundsServiceImplclasssconstructoracceptsargumentsthataresimpleJavatypes
(like,int,long,boolean,String,andsoon),buttheconceptexplainedinthissectionalsoappliesto
scenariosinwhichconstructorargumentsarereferencestoSpringbeans.
ThefollowingbeandefinitionfortheTransferFundsServiceImplclassuses<constructor-arg>element’s
name attribute to specify the name of the constructor argument to which the <constructor-arg> element
applies:
Examplelisting3-18–applicationContext.xml-<constructor-arg>element’snameattribute
Project–ch03-bankapp-constructor-args-by-name
Sourcelocation-src/main/resources/META-INF/spring
<beanid="transferFundsService"
class="sample.spring.chapter03.bankapp.service.TransferFundsServiceImpl">
<constructor-argname="webServiceUrl"value="http://someUrl.com/xyz"/>
<constructor-argname="active"value="true"/>
<constructor-argname="numberOfRetrialAttempts"value="5"/>
<constructor-argname="timeout"value="200"/>
</bean>
TheaboveconfigurationwillworkonlyifTransferFundsServiceImplclassiscompiledwithdebugflag
enabled(referto-goptionofjavac).Whenthedebugflagisenabled,namesofconstructorargumentsare
preserved in the generated .class file. If you dont compile your classes with debug flag enabled, the
constructorargumentnamesarelostduringcompilation,andSpringhasnowaytolocatetheconstructor
argument corresponding to the constructor argument name specified by the <constructor-arg> element’s
nameattribute.
Ifyoudontwanttocompileyourclassesusingdebugflagenabled,youcanuse@ConstructorProperties
annotation(introducedinJavaSE6)toclearlyspelloutnamesoftheconstructorarguments,asshown
hereforTransferFundsServiceImplclass:
Examplelisting3-19–@ConstructorPropertiesannotation
Project–ch03-bankapp-constructor-args-by-name
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/service
packagesample.spring.chapter03.bankapp.service;
importjava.beans.ConstructorProperties;
publicclassTransferFundsServiceImplimplementsTransferFundsService{
@ConstructorProperties({"webServiceUrl","active","timeout","numberOfRetrialAttempts"})
publicTransferFundsServiceImpl(StringwebServiceUrl,booleanactive,longtimeout,
intnumberOfRetrialAttempts){.....}
}
In the above example listing, @ConstructorProperties annotation specifies the names of constructor
argumentsintheorderinwhichtheyappearinthebeanclass’sconstructor.Youmustensurethatyouuse
thesameconstructorargumentnamesinthe<constructor-arg>elements.
Letsnowlookathowthe@ConstructorPropertiesannotationaffectsbeandefinitioninheritance.
@ConstructorPropertiesannotationandbeandefinitioninheritance
If the constructor of the class corresponding to the parent bean definition is annotated with
@ConstructorPropertiesannotation,thebeanclasscorrespondingtothechildbeandefinitionmustalso
beannotatedwith@ConstructorPropertiesannotation.
The following example listing shows the serviceTemplate (parent bean definition) and
FixedDepositService(childbeandefinition)beandefinitions:
Examplelisting3-20–applicationContext.xml-Parentandchildbeandefinitions
Project–ch03-bankapp-constructor-args-by-name
Sourcelocation-src/main/resources/META-INF/spring
<beanid="serviceTemplate"
class="sample.spring.chapter03.bankapp.base.ServiceTemplate">
<constructor-argname="emailMessageSender"ref="emailMessageSender"/>
<constructor-argname="jmsMessageSender"ref="jmsMessageSender"/>
<constructor-argname="webServiceInvoker"ref="webServiceInvoker"/>
</bean>
<beanid="FixedDepositService"
class="sample.spring.chapter03.bankapp.service.FixedDepositServiceImpl"
parent="serviceTemplate">
<propertyname=“fixedDepositDao"ref="FixedDepositDao"/>
</bean>
TheaboveexamplelistingshowsthattheserviceTemplatebeandefinitionisnotabstract,whichmeans
that the Spring container will create an instance of serviceTemplate bean. The serviceTemplate bean
definition specifies 3 <constructor-arg> elements, corresponding to the 3 arguments defined by the
ServiceTemplateclass(referexamplelisting3-21).Aswehavespecifiedconstructorargumentsbyname
in the serviceTemplate bean definition, the ServiceTemplate class’s constructor is annotated with the
@ConstructorPropertiesannotationtoensurethatconstructorargumentnamesareavailabletoSpringat
runtime,asshownhere:
Examplelisting3-21–ServiceTemplateclass
Project–ch03-bankapp-constructor-args-by-name
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/base
packagesample.spring.chapter03.bankapp.base;
importjava.beans.ConstructorProperties;
publicclassServiceTemplate{
.....
@ConstructorProperties({"jmsMessageSender","emailMessageSender","webServiceInvoker"})
publicServiceTemplate(JmsMessageSenderjmsMessageSender,
EmailMessageSenderemailMessageSender,
WebServiceInvokerwebServiceInvoker){.....}
}
As FixedDepositService is a child bean definition of serviceTemplate, the <constructor-arg>
configurationinserviceTemplatebeandefinitionisinheritedbytheFixedDepositServicebeandefinition.
ThismeansthattheFixedDepositServiceImplclassmustdefineaconstructorthatacceptsthesamesetof
arguments as defined by the ServiceTemplate class, and itmust also be annotated with
@ConstructorProperties annotation. If you dont annotate FixedDepositServiceImpls constructor with
@ConstructorPropertiesannotation,Springcontainerwillnotbeabletomatchtheinherited<constructor-
arg>elementswiththeconstructorargumentsspecifiedintheFixedDepositServiceImplsconstructor.
Youcantuse@ConstructorPropertiesannotationforpassingargumentsbynametoastaticorinstance
factorymethod,asexplainednext.
@ConstructorPropertiesannotationandfactorymethods
We saw in section 2-3 of chapter 2 that the <constructor-arg> elements are also used for passing
argumentstostaticandinstancefactorymethods.Youmightthinkthatyoucanpassargumentsbynameto
static and instance factory methods by specifying the <constructor-arg> element’s name attribute and
annotating the factory method with @ConstructorProperties annotation. You should note that
@ConstructorProperties annotation is meant only for constructors; you can’t annotate methods with
@ConstructorProperties annotation. So, if you want to pass arguments by name to a static orinstance
factorymethod,theonlyoptionyouhaveistocompileclasseswithdebugflagenabled.
NOTEIfyoucompileclasseswithdebugflagenabled,itresultsin.classfilesthatarelargerinsize,but
hasnoimpactontheruntimeperformanceoftheapplication.Itonlyresultsinincreasedloadingtimefor
theclasses.
LetsnowlookathowtoenableordisabledebugflaginEclipseIDE.
Enabling(ordisabling)thedebugflaginEclipseIDE
InEclipseIDE,followthesestepstoenablethedebugflagforprojects:
1.GotoWindowsàPreferencesandselecttheoptionJavaàCompiler
2.YoullnowseeasectiontitledClassfileGeneration.Inthissection,ifyoucheckthecheckbox
labeled‘Addvariableattributestogeneratedclassfiles(usedbythedebugger),thedebugflagis
enabled.Uncheckingthischeckboxwilldisablethedebugflag.
Sofarwehavemostlyseenbeandefinitionexamplesinwhichbeanpropertiesandconstructorarguments
werereferencestootherbeans.Wellnowlookatbeandefinitionexamplesinwhichbeanpropertiesand
constructorargumentsareofprimitivetype,collectiontype,java.util.Date,java.util.Properties,andsoon.
3-4 Configuring different types of bean properties and constructor
arguments
Inrealworldapplicationdevelopmentscenarios,propertiesandconstructorargumentsofaSpringbean
could range from a String type to reference to another bean to any other standard (like java.util.Date,
java.util.Map)orcustom(likeAddress)type.Sofarwehaveseenexamplesofhowtosupplyvaluefor
String type bean properties (using value attribute of <property> element) and String type constructor
arguments (using value attribute of <constructor-arg> element). We also looked at how to inject
dependenciesviabeanproperties(usingrefattributeof<property>element)andconstructorarguments
(usingrefattributeof<constructor-arg>elements).
Inthissection,we’lllookatbuilt-inPropertyEditorimplementationsinSpringthatsimplifypassingbean
properties and constructor arguments of types java.util.Date, java.util.Currency, primitive type, and so
on.We’llalsolookathowtospecifyvaluesforcollectiontypes(likejava.util.Listandjava.util.Map)in
the application context XML file, and how to register a custom PropertyEditor implementation with
Spring.
Lets now look at bean definition examples that demonstrate use of built-in PropertyEditor
implementations.
IMPORT chapter 3/ch03-simple-types-examples (This project shows a Spring application in which
bean properties and constructor arguments are of primitive type, java.util.Date, java.util.List,
java.util.Map, and so on. This project also shows how to register a custom PropertyEditor
implementationwithSpringcontainer.Toruntheapplication,executethemainmethodoftheSampleApp
classofthisproject)
Built-inpropertyeditorsinSpring
JavaBeansPropertyEditorsprovidethenecessarylogicforconvertingaJavatypetoastringvalue,and
viceversa.Springprovidesacoupleofbuilt-inPropertyEditorsthatareusedforconvertingstringvalue
of a bean property or a constructor argument (specified via value attribute of <property> and
<constructor-arg>elements)totheactualJavatypeofthepropertyorconstructorargument.
Beforewelookat examples involvingbuilt-inPropertyEditors,lets firstunderstand the importance of
PropertyEditorsinsettingvaluesofbeanpropertiesorconstructorarguments.
ConsiderthefollowingBankDetailsclassthatwewanttoconfigureasasingleton-scopedbeanwithpre-
definedvaluesforitsattributes:
Examplelisting3-22–BankDetailsclass
publicclassBankDetails{
privateStringbankName;
publicvoidsetBankName(StringbankName){
this.bankName=bankName;
}
}
Intheaboveexamplelisting,bankNameisanattributeoftheBankDetailsclass,andisoftypeString.The
followingbeandefinitionfortheBankDetailsclassshowshowtosetthevalueofbankNameattributeto
‘MyPersonalBank:
Examplelisting3-23–BeandefinitionfortheBankDetailsclass
<beanid="bankDetails"class="BankDetails">
<propertyname="bankName"value="MyPersonalBank"/>
</bean>
In the above bean definition, the <property> element’s value attribute specifies a string value for the
bankNameproperty.Asyoucansee,ifabeanpropertyisoftypeString,youcansimplysetthatproperty
valueusing<property> element’s value attribute. Similarly, if a constructor argument is of type String,
youcansettheconstructorargumentvalueusing<constructor-arg>element’svalueattribute.
Letssaythatthefollowingattributes(alongwiththeirsettermethods)areaddedtotheBankDetailsclass:
a bankPrimaryBusiness attribute of type byte[], a headOfficeAddress attribute of type char[], a
privateBank attribute of type char, a primaryCurrency attribute of type java.util.Currency, a
dateOfInception attribute of type java.util.Date, and a branchAddresses attribute of type
java.util.Properties.ThefollowingexamplelistingshowsthemodifiedBankDetailsclass:
Examplelisting3-24–BankDetailsclasscontainingdifferenttypesofproperties
Project–ch03-simple-types-examples
Sourcelocation-src/main/java/sample/spring/chapter03/beans
packagesample.spring.chapter03.beans;
.....
publicclassBankDetails{
privateStringbankName;
privatebyte[]bankPrimaryBusiness;
privatechar[]headOfficeAddress;
privatecharprivateBank;
privateCurrencyprimaryCurrency;
privateDatedateOfInception;
privatePropertiesbranchAddresses;
.....
publicvoidsetBankName(StringbankName){
this.bankName=bankName;
}
//--moresettermethods
}
YoucanconfiguretheBankDetailsclassasaSpringbeanbyspecifyingstringvaluesfortheproperties,
and letting the Spring container convert these string values into the corresponding Java types of the
propertiesbyusingregisteredJavaBeansPropertyEditorimplementations.
ThefollowingbeandefinitionfortheBankDetailsclassshowsthatsimplestringvaluesarespecifiedfor
differentpropertytypes:
Examplelisting3-25–applicationContext.xml-BeandefinitionfortheBankDetailsclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails">
<propertyname="bankName"value="MyPersonalBank"/>
<propertyname="bankPrimaryBusiness"value="Retailbanking"/>
<propertyname="headOfficeAddress"value="Addressofheadoffice"/>
<propertyname="privateBank"value="Y"/>
<propertyname="primaryCurrency"value="INR"/>
<propertyname="dateOfInception"value="30-01-2012"></property>
<propertyname="branchAddresses">
<value>
x=BranchX'saddress
y=BranchY'saddress
</value>
</property>
</bean>
Theaboveexamplelistingshows thatstring valuesarespecifiedforpropertiesoftypesjava.util.Date,
java.util.Currency, char[], byte[], char and java.util.Properties. Spring container uses registered
PropertyEditors for converting the string value of the property or constructor argument to the
correspondingJavatypeofthepropertyorconstructorargument.Forinstance,Springcontainerconverts
the value 30-01-2012’ of dateOfInception property to java.util.Date type using CustomDateEditor (a
built-inPropertyEditorimplementationforjava.util.Datetype).
If you look at how branchAddresses property (of type java.util.Properties) is configured in example
listing 3-25, youll notice that instead of <property> elements value attribute, <value> sub-element of
<property> element has been used to specify the value for the property. In case of single-valued
properties,theuseof<property>elementsvalueattributeispreferredover<value>sub-element.But,if
youneedtospecifymultiplevaluesforapropertyorthevaluesneedtobespecifiedonseparatelines(as
inthecaseofbranchAddressesproperty),the<value>sub-elementispreferredovervalueattribute.In
the next section, you’ll see that values for properties (or constructor arguments) of type
java.util.Properties can also be specified using <props> sub-element of <property> ( or <constructor-
arg>)element.
Springcomeswithcoupleofbuilt-inPropertyEditorimplementationsthatperformthetaskofconverting
valuesspecifiedintheapplicationcontextXMLfiletotheJavatypeofthebeanpropertyorconstructor
argument.Thefollowingtabledescribessomeofthebuilt-inPropertyEditorimplementationsinSpring:
Built-in PropertyEditor
implementation Description
CustomBooleanEditor convertsstringvaluetoBooleanorbooleantype
CustomNumberEditor convertsstringvaluetoanumber(likeint,long,andsoon)
ChracterEditor convertsstringvaluetochartype
ByteArrayPropertyEditor convertsstringvaluetobyte[]
CustomDateEditor convertsstringvaluetojava.util.Datetype
PropertiesEditor convertsstringvaluetojava.util.Propertiestype
Theabovetableshowsonlyasubsetofbuilt-inPropertyEditorimplementationsinSpring.Foracomplete
list,refertotheorg.springframework.beans.propertyeditorspackageofSpring.Itisimportanttonotethat
not all built-in PropertyEditor implementations in Spring are registered with the Spring container by
default. For instance, you need to explicitly register CustomDateEditor to allow Spring container to
performconversionfromastringvaluetoajava.util.Datetype.Laterinthissection,welllookathow
youcanregisterpropertyeditorswithSpringcontainer.
Lets now look at how to specify values for bean properties (or constructor arguments) of types
java.util.List,java.util.Setandjava.util.Map.
Specifyingvaluesfordifferentcollectiontypes
The <list>, <map> and <set> sub-elements (defined in Springs beans schema) of <property> and
<constructor-arg> elements are used to set properties and constructor arguments of type java.util.List,
java.util.Mapandjava.util.Set,respectively.
NOTESpringsutilschemaalsoprovides<list>,<set>and<map>elementsthatsimplifysetting
propertiesandconstructorargumentsofdifferentcollectiontypes.Laterinthischapter,we’lllookat
Springsutilschemaelementsindetail.
ThefollowingDataTypesExampleclassshowsthatitsconstructoracceptsargumentsofdifferenttypes:
Examplelisting3-26–DataTypesExampleclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/java/sample/spring/chapter03/beans
packagesample.spring.chapter03.beans;
importjava.beans.ConstructorProperties;
.....
publicclassDataTypesExample{
privatestaticLoggerlogger=Logger.getLogger(DataTypesExample.class);

@SuppressWarnings("rawtypes")
@ConstructorProperties({"byteArrayType","charType","charArray",
"classType","currencyType","booleanType","dateType","longType",
"doubleType","propertiesType","listType","mapType","setType",
"anotherPropertiesType"})
publicDataTypesExample(byte[]byteArrayType,charcharType,
char[]charArray,ClassclassType,CurrencycurrencyType,
booleanbooleanType,DatedateType,longlongType,
doubledoubleType,PropertiespropertiesType,List<Integer>listType,
MapmapType,SetsetType,PropertiesanotherPropertiesType){
.....
logger.info("classType"+classType.getName());
logger.info("listType"+listType);
logger.info("mapType"+mapType);
logger.info("setType"+setType);
logger.info("anotherPropertiesType"+anotherPropertiesType);
}
}
The above example listing shows that the DataTypesExample classs constructor accepts arguments of
typesjava.util.List,java.util.Map,java.util.Setandjava.util.Properties,andsoon,andlogsthevalueof
eachconstructorargument.
ThefollowingexamplelistingshowsthebeandefinitionfortheDataTypesExampleclass:
Examplelisting3-27–applicationContext.xml-BeandefinitionforDataTypesExampleclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="anotherPropertiesType">
<props>
<propkey="book">GettingstartedwiththeSpringFramework</prop>
</props>
</constructor-arg>
<constructor-argname="listType"value-type="java.lang.Integer">
<list>
<value>1</value>
<value>2</value>
</list>
</constructor-arg>
<constructor-argname="mapType">
<map>
<entry>
<key>
<value>mapkey1</value>
</key>
<value>mapkey1’svalue</value>
</entry>
</map>
</constructor-arg>
<constructor-argname="setType">
<set>
<value>Element1</value>
<value>Element2</value>
</set>
</constructor-arg>
</bean>
Theaboveexamplelistingshows:
·        the value of anotherPropertiesType (of type java.util.Properties) is specified using the
<props>sub-elementof<constructor-arg>element.Each<prop>elementspecifiesakey-value
pair;thekeyattributespecifiesthekeyvalueandthecontentof<prop>elementisthevaluefor
thekey.Insteadofusing<props>element,youcanuse<value>sub-elementof<constructor-arg>
elementtospecifythevalueforanotherPropertiesTypeargument.
·thevalueoflistTypeconstructorargument(oftypejava.util.List)isspecifiedusingthe<list>
sub-element of <constructor-arg>. The <value> sub-elements of <list> element specify items
contained in the list. The <list> element’s value-type attribute specifies the Java type of the
elements that the java.util.List type constructor argument accepts. As the listType constructor
argumentisoftypeList<Integer>(referexamplelisting3-26),thevalue-typeattribute’svalueis
specifiedasjava.lang.Integer.Thevalue-typeattributeisoptional,andisparticularlyusefulif
you are using a parameterized List type, like List<Integer>. If you specify the value-type
attribute,Springcontainerusestheregisteredpropertyeditorstoperformconversionofvalues
tothetypespecifiedbythevalue-typeattribute,followedbyconverting(ifrequired)thevalues
tothetypeacceptedbytheparameterizedListtype.Ifyoudontspecifythevalue-typeattribute,
Springcontainersimplyusestheregisteredpropertyeditorstoperformconversionofvaluesto
thetypeacceptedbytheparameterizedListtype.
·thevalueofmapTypeconstructorargument(oftypejava.util.Map) is specified usingthe
<map>sub-elementof<constructor-arg>.The <entry>sub-elementof <map> specifies a key-
valuepaircontainedintheMap;the<key>elementspecifiesthekeyandthe<value>element
specifiesthevalueforthekey.Thekey-typeandvalue-typeattributesof<map>elementspecify
the Java type of keys and values that java.util.Map accepts. The key-type and value-type
attributes are optional, and especially useful if you are using parameterized Map type, like
Map<Integer,Integer>.Springcontainerusesregisteredpropertyeditorstoperformconversion
of keys and values to the types specified by the key-type and value-type attributes, and to the
typesacceptedbytheparameterizedMaptype.
·thevalueofthesetTypeconstructorargument(oftypejava.util.Set)isspecifiedusingthe
<set> sub-element of <constructor-arg>. Each <value> sub-element of <set> specifies an
elementcontainedintheSet.Thevalue-typeattributeof<set>elementspecifiestheJavatypeof
elementsthatjava.util.Setaccepts.Thevalue-typeattributeisoptional,andisusefulifyouare
using parameterized Set type, like Set<Integer>. Spring container uses registered property
editorstoperformconversionofvaluestothetypespecifiedbythevalue-typeattribute,andto
thetypeacceptedbytheparameterizedSettype.
InDataTypesExample class (refer example listing 3-26 and 3-27), constructor arguments of type List,
Map and Set contained elements of type String or Integer. In an application, a collection may contain
elements of type Map, Set, Class, Properties, or any other Java type. The elements contained in the
collectioncanalsobebeanreferences.Toaddresssuchscenarios,Springallowsyoutouseelementslike
<map>,<set>,<list>,<props>,<ref>,andsoon,assub-elementsof<list>,<map>and<set>elements.
LetsnowlookatexamplesthatdemonstratehowtoadddifferenttypesofelementstoMap,ListandSet
typeconstructorargumentsandbeanproperties.
AddingelementsoftypeList,Map,SetandPropertiestocollectiontypes
IfabeanpropertyorconstructorargumentisoftypeList<List>,simplyuseanested<list>element,as
shownhere:
Examplelisting3-28–Configurationexample:ListinsideaList
<constructor-argname="nestedList">
<list>
<list>
<value>AsimpleStringvalueinthenestedlist</value>
<value>AnothersimpleStringvalueinnestedlist</value>
</list>
</list>
</constructor-arg>
The <constructor-arg> element shown in the above example listing supplies value for a constructor
argumentnamednestedListwhichisoftypeList<List>.Thenested<list>elementrepresentsanelement
oftypeList.Similarly, you can use <map>,<set>and<props>elements inside a<list> element to set
value of properties or constructor arguments of type List<Map>, List<Set> and List<Properties>,
respectively.Aswiththe<list>element,a<set>elementcancontain<set>,<list>,<map>or<props>
element.Incaseofa<map>element,youcanuse<map>,<set>,<list>or<props>elementtospecifykey
andvalueofanentry.
ThefollowingexamplelistingshowshowyoucanspecifyvaluesforaMap<List,Set>typeconstructor
argument:
Examplelisting3-29–Configurationexample:MapcontainingListtypeaskeyandSettypeasvalue
<constructor-argname="nestedListAndSetMap">
<map>
<entry>
<key>
<list>
<value>aListelement</value>
</list>
</key>
<set>
<value>aSetelement</value>
</set>
</entry>
</map>
</constructor-arg>
The above example listing shows that the nestedListAndSetMap constructor argument is of Map type
whosekeyisoftypeListandvalueisoftypeSet.The<key>elementcanhaveeitherofthefollowing
elements as its sub-element: <map>,<set>,<list> and <props>. The value for the key can be defined
using<map>,<set>,<list>or<props>element.
Addingbeanreferencestocollectiontypes
Youcanuse<ref>elementsinside<list>and<set>elementstoaddreferencestobeansintoproperties
andconstructorargumentsoftypeListandSet,respectively.
The following example listing shows how references to beans are added to a List type constructor
argument:
Examplelisting3-30–Configurationexample:Listcontainingreferencetobeans
<bean.....>
<constructor-argname="myList">
<list>
<refbean="aBean"/>
<refbean="bBean"/>
</list>
</constructor-arg>
</bean>
<beanid="aBean"class="somepackage.ABean"/>
<beanid="bBean"class="somepackage.BBean"/>
Theaboveexamplelistingshows that the myList constructorargumentis of typeListand it contains 2
elements-areferencetoaBeanbeanandareferencetobBeanbean.The<ref>elementsbeanattribute
specifiesthenameofthebeanreferencedbythe<ref>element.
Aswiththe<list>element,youcanuse<ref>elementsinside<set>elementtoaddbeanreferencestoa
Set type constructor argument or bean property. In case of <map> element, you can use <ref> element
insidea<key>elementtospecifyabeanreferenceasakey,andusethe<ref>elementtospecifyabean
referenceasavalueforthekey.ThefollowingexamplelistingshowsaMaptypeconstructorargument
thatcontainsasinglekey-valuepairinwhichbothkeyandvaluearereferencestobeans:
Examplelisting3-31–Configurationexample:Mapcontainingbeanreferencesaskeysandvalues
<bean.....>
<constructor-argname="myMapWithBeanRef">
<map>
<entry>
<key>
<refbean="aBean"/>
</key>
<refbean="bBean"/>
</entry>
</map>
</constructor-arg>
</bean>
<beanid="aBean"class="somepackage.ABean"/>
<beanid="bBean"class="somepackage.BBean"/>
The above example listing shows that myMapWithBeanRef constructor argument is of type Map and it
contains a key-value pair in which the key is a reference to aBean bean and corresponding value is a
referencetobBeanbean.
Addingbeannamestocollectiontypes
Ifyouwanttoaddabeanname(asspecifiedbytheidattributeof<bean>element)toaList,MaporSet
type constructor argument or bean property, you can use the <idref>element inside <map>, <set> and
<list> elements. The following example listing shows a Map type constructor argument that contains a
singlekey-valuepair,wherebeannameisthekeyandbeanreferenceisthevalue:
Examplelisting3-32–Configurationexample:Mapcontainingbeannameaskeyandbeanreferenceas
value
<constructor-argname="myExample">
<map>
<entry>
<key>
<idrefbean="sampleBean"/>
</key>
<refbean="sampleBean"/>
</entry>
</map>
</constructor-arg>
<beanid="sampleBean"class="somepackage.SampleBean"/>
TheaboveexamplelistingshowsthatthemyExampleconstructorargumentisoftypeMapwhosekeyis
thestringvaluesampleBeanandvalueisthesampleBeanbean.Wecouldhaveused<value>elementto
setsampleBeanstringvalueasthekey,but<idref>elementisusedbecauseSpringcontainerverifies
existenceofthesampleBeanbeanwhentheapplicationisdeployed.
NOTEYoucanusethe<idref>elementinsidea<property>or<constructor-arg>elementtosetabean
nameasthevalueofabeanpropertyorconstructorargument.
Addingnullvaluestocollectiontypes
YoucanaddanullvaluetocollectionsoftypeSetandListusing<null>element.Thefollowingexample
listingshowshowtoaddanullvaluetoaSettypeconstructorargumentusing<null>element:
Examplelisting3-33–Configurationexample:Setcontaininganullelement
<constructor-argname="setWithNullElement">
<set>
<value>Element1</value>
<value>Element2</value>
<null/>
</set>
</constructor-arg>
Intheaboveexamplelisting,setWithNullElementconstructorargumentcontains3elements:Element1,
Element2andnull.
ToaddanullkeytoaMaptypeconstructorargumentorproperty,youcanuse<null>elementinsidethe
<key>element.And,toaddanullvalue,youcanadda<null>elementinsidethe<entry>element.The
following example listing shows a Map type constructor argument that contains a null key and a null
value:
Examplelisting3-34–Configurationexample:Mapcontaininganullkeyandanullvalue
<constructor-argname="mapType">
<map>
<entry>
<key>
<null/>
</key>
<null/>
</entry>
</map>
</constructor-arg>
TheaboveexamplelistingshowsthatanelementwithnullkeyandnullvalueisaddedtothemapType
constructorargumentusing<null>element.
NOTEYoucanalsouse<null>elementinside<property>and<constructor-arg>elementstosetnull
valuesforpropertiesandconstructorarguments,respectively.
Letsnowlookathowtospecifyvaluesforarraytypepropertiesandconstructorarguments.
Specifyingvaluesforarrays
If a bean class defines an array type property, you can set its value using the <array> sub-element of
<property> element. Similarly, you can set an array type constructor argument using the <array> sub-
elementof<constructor-arg>element.
Thefollowingexamplelistingshowshowyoucansetabeanpropertyoftypeint[]:
Examplelisting3-35–Configurationexample:Settingvalueofabeanpropertyoftypeint[]
<propertyname="numbersProperty">
<array>
<value>1</value>
<value>2</value>
</array>
</property>
Intheaboveexamplelisting,each<value>sub-elementofthe<array>elementrepresentsanelementin
thenumbersPropertyarray.ThepropertyeditorsregisteredwiththeSpringcontainerareusedtoconvert
thestringvaluespecifiedbyeachofthe<value>elementtointtype.Youcanuse<array>elementinside
<list>,<set>and<map>elements.Youcanalsouse<list>,<set>,<map>,<props>and<ref>elements
insidean<array>elementtocreatearraysofList,Set,Map,Propertiesandbeanreferences,respectively.
Ifyouwanttocreateanarrayofarrays,youcanuse<array>elementsinsidean<array>element.
Wediscussedthat<list>,<map>and<set>elementsareusedtosetpropertiesorconstructorarguments
of type List, Map andSet, respectively. Lets now look at the default collection implementation that is
createdbySpringforeachoftheseelements.
Defaultcollectionimplementationfor<list>,<set>and<map>elements
The following table shows the default collection implementation that is created by Spring for <list>,
<set>and<map>elements:
Collectionelement DefaultcollectionimplementationcreatedbyS pring
<list> java.util.ArrayList
<set> java.util.LinkedHashSet
<map> java.util.LinkedHashMap
Theabovetablesuggests:
·   if aproperty’s(or aconstructor arguments) value is specified using <list> element, Spring
createsaninstanceofArrayListandassignsittotheproperty(ortheconstructorargument).
·     if a propertys (or a constructor argument’s) value is specified using <set> element, Spring
createsaninstanceofLinkedHashSetandassignsittotheproperty(ortheconstructorargument).
·ifaproperty’s(oraconstructorarguments)valueisspecifiedusing<map>element,Spring
createsaninstanceofLinkedHashMapandassignsittotheproperty(ortheconstructorargument).
It is likely that you may want to substitute a different implementation of List, Set or Map to a bean
propertyoraconstructorargument.Forinstance,insteadofjava.util.ArrayList,youmaywanttoassignan
instanceofjava.util.LinkedListtoabeanpropertyoftypeList.Insuchscenarios,itisrecommendedto
use <list>, <map> and <set> elements of Springs util schema (explained in section 3-8). The <list>,
<set>and<map>elementsofSpringsutilschemaprovidetheoptiontospecifythefully-qualifiedname
oftheconcretecollectionclassthatyouwanttoassigntothepropertyorconstructorargumentofthebean.
Letsnowlookatsomeofthebuilt-inpropertyeditorsprovidedbySpring.
3-5Built-inpropertyeditors
Spring provides a couple of built-in property editors that are useful when setting bean properties and
constructor arguments. Let’s take a quick look at CustomCollectionEditor, CustomMapEditor and
CustomDateEditorbuilt-inpropertyeditors.Toviewthecompletelistofbuilt-inpropertyeditors,referto
org.springframework.beans.propertyeditorspackage.
CustomCollectionEditor
CustomCollectionEditor property editor is responsible for converting a source Collection (like,
java.util.LinkedList) type to the target Collection (like, java.util.ArrayList) type. By default,
CustomCollectionEditorisregisteredforSet,SortedSetandListtypes.
Consider the following CollectionTypesExampleclass that defines attributes (and corresponding setter
methods)oftypeSetandList:
Examplelisting3-36–CollectionTypesExampleclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/java/sample/spring/chapter03/beans
packagesample.spring.chapter03.beans;
importjava.util.List;
importjava.util.Set;
publicclassCollectionTypesExample{
privateSetsetType;
privateListlistType;
.....
//--settermethodsforattributes
publicvoidsetSetType(SetsetType){
this.setType=setType;
}
.....
}
CollectionTypesExampleclassdefinessetTypeandlistTypeattributesoftypeSetandList,respectively.
ThefollowingexamplelistingshowsthebeandefinitionforCollectionTypesExampleclass:
Examplelisting3-37–applicationContext.xml-BeandefinitionforCollectionTypesExampleclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanclass="sample.spring.chapter03.beans.CollectionTypesExample">
<propertyname="listType">
<set>
<value>setelement1</value>
<value>setelement2</value>
</set>
</property>
<propertyname="setType">
<list>
<value>listelement1</value>
<value>listelement2</value>
</list>
</property>
.....
</bean>
Youmightthinkthattheaboveconfigurationisincorrectbecause<set>elementhasbeenusedtosetthe
valueoflistType property(of type List), and <list> element has been used to set the value of setType
property(oftypeSet).
Theaboveconfigurationiscompletelylegal,andtheSpringcontainerdoesnotcomplain.Thisisbecause
CustomCollectionEditor converts the ArrayList instance (created corresponding to the <list> type
element)toLinkedHashSettype(animplementationofSettype)beforesettingthesetTypeproperty.Also,
CustomCollectionEditorconverts the LinkedHashSet instance (created corresponding to the <set> type
element)toArrayListtype(animplementationofListtype)beforesettingthelistTypeproperty.
Figure3-4–CustomCollectionEditorconvertstheLinkedHashSettoArrayListtype
Figure3-4showsthattheCustomCollectionEditorconvertstheLinkedHashSettypetoArrayListtosetthe
value of CollectionTypesExample’slistType property. The figure shows the sequence of steps that are
performed by Spring to set the value of listType property. First, Spring creates an instance of
LinkedHashSetcorrespondingtothe<set>element.AsthelistTypepropertyisoftypeList(referexample
listing3-36),theCustomCollectionEditorcomesintopictureforsettingthelistTypepropertysvalue.If
the type of the bean property is List, CustomCollectionEditor creates an instance of ArrayList and
populatesitwiththeelementsfromtheLinkedHashSet.Intheend,thevalueofthelistTypevariableisset
totheArrayListimplementationcreatedbyCustomCollectionEditor.
Itisimportanttonotethatifapropertyorconstructorargumenttypeisaconcretecollectionclass(like
LinkedList),CustomCollectionEditorsimplycreatesaninstanceoftheconcretecollectionclassandadds
elements to it from the source collection. The following figure shows a scenario in which the bean
propertyisoftypejava.util.Vector(aconcretecollectionclass):
Figure3-5CustomCollectionEditorconvertstheArrayListtoVectortype
The above figure shows that the CustomCollectionEditor creates an instance of Vector (a concrete
collectionclass)andaddselementstoitfromthesourcecollection,ArrayList.
LetsnowlookatCustomMapEditorpropertyeditor.
CustomMapEditor
CustomMapEditorpropertyeditordealswithconvertingasourceMaptype(likeHashMap) toa target
Maptype(likeTreeMap).Bydefault,CustomMapEditorisregisteredonlyforSortedMaptype.
Figure3-6showsascenarioinwhichCustomMapEditorconvertsLinkedHashMap(thesourceMaptype)
toTreeMap(animplementationofSortedMaptype).
Figure3-6showsthesequenceofstepsperformedbySpringtosetthevalueofmapTypeproperty.First,
Spring creates an instance of LinkedHashMap corresponding to the <map> element. As the mapType
propertyisoftypeSortedMap,CustomMapEditorcomesintopicturewhilesettingthevalueofmapType
property. CustomMapEditor creates an instance of TreeMap (a concrete implementation of SortedSet
interface),addskey-valuepairsfromLinkedHashMaptothenewlycreatedTreeMapinstanceandassigns
theTreeMapinstancetothemapTypeproperty.
Figure3-6CustomMapEditorconvertstheLinkedHashMap(thesourceMaptype)toTreeMap(thetarget
Maptype)type
CustomDateEditor
CustomDateEditorisapropertyeditorforjava.util.Datetypebeanpropertiesandconstructorarguments.
CustomDateEditorsupportsacustomjava.text.DateFormatthatisusedforformattingadate/timestringto
a java.util.Date type object, and parsing a java.util.Date type object to a date/time string. In the next
section,we’llseehowCustomDateEditorisusedforsettingbeanpropertiesandconstructorargumentsof
typejava.util.Date.In ch03-simple-types-examples project,CustomDateEditor converts the string value
ofabeanproperty(referdateOfInceptionattributeofBankDetailsclass)orconstructorargument(refer
dateTypeconstructorargumentofDataTypesExampleclass)tojava.util.Datetype.
Inch03-simple-types-examples project, some of the other built-in property editors that are utilized by
beans include: ByteArrayPropertyEditor - for converting a string value to byte[] (refer
bankPrimaryBusinessattributeofBankDetailsclass),CurrencyEditor–forconvertingacurrencycodeto
a java.util.Currency object (refer primaryCurrency attribute of BankDetails class),
CharacterArrayPropertyEditor – for converting a string value to a char[] (refer headOfficeAddress
attributeofBankDetailsclass),andsoon.
LetsnowlookathowtoregisterpropertyeditorswiththeSpringcontainer.
3-6RegisteringpropertyeditorswiththeSpringcontainer
SpringsBeanWrapperImplclassregistersacoupleofbuilt-inpropertyeditorswiththeSpringcontainer.
Forinstance,CustomCollectionEditor,CustomMapEditor,CurrencyEditor,ByteArrayPropertyEditorand
CharacterArrayEditor property editors are registered by default with the Spring container. But,
CustomDateEditor property editor isnot registered by default with the Spring container. To register
propertyeditorswith the Springcontainer,youcanuseSprings CustomEditorConfigurerspecial bean.
CustomEditorConfigurer class implements Springs BeanFactoryPostProcessor interface (explained in
detailinsection5-4ofchapter5),anditisautomaticallydetectedandexecutedbytheSpringcontainer.
In ch03-simple-types-examples project, BankDetails class (refer example listing 3-24) defines a
dateOfInceptionpropertyoftypejava.util.Date.ThevaluespecifiedforthedateOfInceptionpropertyis
‘30-01-2012’ (refer example listing 3-25). To convert the string value ‘30-01-2012’ to java.util.Date
type,youmustregisteracustompropertyeditorforjava.util.DatetypeoryoucanregisterSpringsbuilt-
inCustomDateEditorpropertyeditorwiththeSpringcontainer.
ToregisterpropertyeditorswiththeSpringcontainer,youneedtodothefollowing:
1.    Create a class that implements Springs PropertyEditorRegistrar interface. This class is
responsibleforregisteringpropertyeditorswiththeSpringcontainer.
2.ConfigurethePropertyEditorRegistrarimplementationasaSpringbeanintheapplicationcontext
XMLfile.
3.ConfigureSpringsCustomEditorConfigurerspecialbeanintheapplicationcontextXMLfile,and
provideitwithreferencetothePropertyEditorRegistrarimplementation(thatyoucreatedinstep1
andconfiguredinstep2).
Lets now see how CustomDateEditor is registered with the Spring container in ch03-simple-types-
examplesproject.
CreatingaPropertyEditorRegistrarimplementation
The following example listing shows the MyPropertyEditorRegistrar class that implements
PropertyEditorRegistrarinterface:
Examplelisting3-38–MyPropertyEditorRegistrarclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/java/sample/spring/chapter03/beans
packagesample.spring.chapter03.beans;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importorg.springframework.beans.PropertyEditorRegistrar;
importorg.springframework.beans.PropertyEditorRegistry;
importorg.springframework.beans.propertyeditors.CustomDateEditor;
publicclassMyPropertyEditorRegistrarimplementsPropertyEditorRegistrar{
@Override
publicvoidregisterCustomEditors(PropertyEditorRegistryregistry){
registry.registerCustomEditor(Date.class,newCustomDateEditor(
newSimpleDateFormat("dd-MM-yyyy"),false));
}
}
The above example listing shows that the MyPropertyEditorRegistrar class implements Springs
PropertyEditorRegistrar interface, and provides implementation for registerCustomEditors method
defined in the PropertyEditorRegistrar interface. The PropertyEditorRegistry instance passed to the
registerCustomEditors method is used for registering property editors. PropertyEditorRegistrys
registerCustomEditor method is used for registering a PropertyEditor implementation with the Spring
container. In the above example listing, PropertyEditorRegistrys registerCustomEditor is used for
registeringaCustomDateEditorpropertyeditorwiththeSpringcontainer.
ConfiguringtheCustomEditorConfigurerclass
The following example listing shows how the CustomEditorConfigurer class is configured in the
applicationcontextXMLfile:
Examplelisting3-39–applicationContext.xml-CustomEditorConfigurerconfiguration
Project–ch03-simple-types-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanid="myPropertyEditorRegistrar"
class="sample.spring.chapter03.beans.MyPropertyEditorRegistrar"/>
<beanid="editorConfigurer"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<propertyname="propertyEditorRegistrars">
<list>
<refbean="myPropertyEditorRegistrar"/>
</list>
</property>
</bean>
In the above example listing, myPropertyEditorRegistrar bean definition configures
MyPropertyEditorRegistrarclassasaSpringbean.MyPropertyEditorRegistrarclassimplementsSprings
PropertyEditorRegistrar interface, and is responsible for registering additional property editors with
Spring container. CustomEditorConfigurers propertyEditorRegistrars property specifies a list of
PropertyEditorRegistrar implementations. In the above example listing, myPropertyEditorRegistrar is
specified as one of the values of propertyEditorRegistrars property. CustomEditorConfigurer bean is
automaticallydetectedandexecutedbytheSpringcontainer,resultinginregistrationofpropertyeditors
bytheMyPropertyEditorRegistrarinstance.
Lets now look at how to use p-namespace (for bean properties) and c-namespace (for constructor
arguments)towriteconcisebeandefinitionsinapplicationcontextXMLfiles.
3-7Concisebeandefinitionswithpandcnamespaces
To make bean definitions less verbose in application context XML files, Spring provides p and c
namespaces tospecify values for bean properties andconstructor arguments, respectively. Thep and c
namespacesarealternativestousing<property>and<constructor-arg>elements,respectively.
Letsfirstlookatp-namespace.
IMPORTchapter3/ch03-namespaces-example(ThisprojectshowsaSpringapplicationinwhichbean
properties and constructor arguments are set using p- and c-namespaces, respectively. To run the
application,executethemainmethodoftheSampleAppclassofthisproject)
p-namespace
Tousep-namespacetosetbeanproperties,specifybeanpropertiesasattributesofthe<bean>element,
andspecifyeachbeanpropertytobeinthep-namespace.
Thefollowingbeandefinitionshowshowtousep-namespacetosetbeanproperties:
Examplelisting3-40–applicationContext.xml-p-namespaceexample
Project–ch03-namespaces-example
Sourcelocation-src/main/resources/META-INF/spring
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation=".....">
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails"
p:bankName="MyPersonalBank"p:bankPrimaryBusiness="Retailbanking"
p:headOfficeAddress="Addressofheadoffice"p:privateBank="Y"
p:primaryCurrency="INR"p:dateOfInception="30-01-2012"
p:branchAddresses-ref="branchAddresses"/>
.....
</beans>
In the application context XML file shown above, p-namespace is specified via xmlns attribute. The
bankDetailsbeandefinitionmakesuseofthepprefixforthep-namespacetospecifybeanproperties.If
you compare the above example listing with the example listing 3-25, youll notice that the above
examplelistingislessverbose.Eventhoughitispossibletouseamixof<property>elementsand p-
namespace to specify bean properties, it’s recommended that you choose one style for specifying bean
propertiesanduseitconsistentlyinbeandefinitions.
NOTE As p-namespace is implemented as part of Spring, there isno schema corresponding to p-
namespace. For this reason, you dont see any schema reference corresponding to p-namespace in
example listing 3-40. If you want your IDE to autocomplete bean property names when using p-
namespace,considerusingIntelliJIDEAorSpringSourceToolSuite(STS).
Ifabeanpropertyisnotareferencetoanotherbean,itisspecifiedusingthefollowingsyntax:
p:<property-name>="<property-value>"
here,<property-name>isthenameofthebeanproperty,and<property-value>isthevalueofthebean
property.
Ifabeanpropertyisareferencetoanotherbean,itisspecifiedusingthefollowingsyntax:
p:<property-name>-ref="<bean-reference>"
here,<property-name>isthenameofthebeanproperty,and<bean-reference>istheid(orname)of
thereferencedbean.Itisimportanttonotethatthenameofthebeanpropertyisfollowedby--ref.Asthe
branchAddressespropertyofBankDetailsbeanrepresentsareferencetothebranchAddressesbean,the
branchAddressespropertyisspecifiedasp:branchAddresses-refinexamplelisting3-40.
Letsnowlookathowc-namespaceisusedforsettingconstructorarguments.
c-namespace
To use c-namespace to supply values for constructor arguments, specify constructor arguments as
attributesofthe<bean>element,andspecifyeachconstructorargumenttobeinthec-namespace.
ThefollowingexamplelistingshowstheBankStatementclassthatwellconfigureasaSpringbeanusing
c-namespace.
Examplelisting3-41–BankStatementclass
Project–ch03-namespaces-example
Sourcelocation-src/main/java/sample/spring/chapter03/beans
packagesample.spring.chapter03.beans;
importjava.beans.ConstructorProperties;
publicclassBankStatement{
.....
@ConstructorProperties({"transactionDate","amount","transactionType",
"referenceNumber"})
publicBankStatement(DatetransactionDate,doubleamount,
StringtransactionType,StringreferenceNumber){
this.transactionDate=transactionDate;
this.amount=amount;
.....
}
.....
}
ThefollowingbeandefinitionfortheBankStatementclassshowsusageofc-namespaceforsettingvalues
ofconstructorarguments:
Examplelisting3-42–applicationContext.xml-c-namespaceexample
Project–ch03-namespaces-example
Sourcelocation-src/main/resources/META-INF/spring
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation=".....">
.....
<beanid="bankStatement"class="sample.spring.chapter03.beans.BankStatement"
c:transactionDate="30-01-2012"
c:amount="1000"
c:transactionType="Credit"
c:referenceNumber="1110202"/>
.....
</beans>
In the above example listing, c-namespace is specified via xmlns attribute. The bankStatement bean
definition makes use of the c prefix for the c-namespace to specify constructor arguments. The syntax
followedforspecifyingconstructorargumentsusingc-namespaceissimilartowhatwesawincaseofp-
namespace.
NOTE As c-namespace is implemented as part of Spring, there isno schema corresponding to c-
namespace. For this reason, you dont see any schema reference corresponding to c-namespace in
examplelisting 3-42.If youwantyour IDEtoautocompleteconstructorargumentnames whenusingc-
namespace,considerusingIntelliJIDEAorSpringSourceToolSuite(STS).
Ifaconstructorargumentisnotareferencetoanotherbean,itisspecifiedusingthefollowingsyntax:
c:<constructor-argument-name>="<constructor-argument-value>"
here, <constructor-argument-name> is the name of the constructor argument, and <constructor-
argument-value>isthevalueoftheconstructorargument.
Ifaconstructorargumentisareferencetoanotherbean,itisspecifiedusingthefollowingsyntax:
c:<constructor-argument-name>-ref="<bean-reference>"
here,<constructor-argument-name>isthenameoftheconstructorargument,and<bean-reference>is
theid(orname)ofthereferencedbean.Itisimportanttonotethatthenameoftheconstructorargumentis
followedby--ref.Forinstance,ifaconstructorargumentnamedmyargumentrepresentsareferencetoa
beanwithid‘x’,youspecifymyargumentconstructorargumentas:
c:myargument-ref="x"
As mentioned earlier, if a class is compiled with debug flag enabled, constructor argument names are
preserved in the generated .class file. If the BankStatement class is not compiled with the debug flag
enabled,theconfigurationshowninexamplelisting3-42willnotwork.Insuchcases,yousupplyvalues
forconstructorargumentsusingtheirindex,asshownhere:
Examplelisting3-43–Supplyingvaluesforconstructorargumentsusingtheirindex
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation=".....">
.....
<beanid="bankStatement"class="sample.spring.chapter03.beans.BankStatement"
c:_0="30-01-2012"
c:_1="1000"
c:_2="Credit"
c:_3="1110202"/>
.....
</beans>
The above example listing shows bean definition for the BankStatement class, which uses constructor
argument index instead of constructor arguments name to supply values. It is important to note that the
indexoftheconstructorargumentisprefixedwithanunderscorebecauseattributenamesinXMLcannot
beginwithanumericvalue.Ifaconstructorargumentisareferencetoanotherbean,-refmustbeaddedto
the index of the constructor argument. For instance, if the constructor argument at index 0 represents
referencetoanotherbean,itisspecifiedasc:_0-ref.Eventhoughit’spossibletouseacombinationof
<constructor-arg>elementsandc-namespacetospecifyconstructorarguments,it’srecommendedthatyou
chooseonestyleofspecifyingconstructorargumentsanduseitconsistentlyinbeandefinitions.
Wesawearlierhow<list>,<map>and<set>elementsareusedtosetpropertiesorconstructorarguments
oftypeList,Map andSet, respectively. Lets now look at Springs util schema that simplifies creating
collectiontypes,Propertiestype,constants,andsoon,andexposingthemasaSpringbeans.
3-8Spring’sutilschema
Springs util schema simplifies configuring beans by providing a concise way to perform common
configurationtasks.Thefollowingtabledescribesthevariouselementsofutilschema:
Element Description
<list> Createsajava.util.Listtype,andexposesitasabean
<map> Createsajava.util.Maptype,andexposesitasabean
<set> Createsajava.util.Settype,andexposesitasabean
<constant> Exposesapublicstaticfieldonatypeasabean
<property-path> Exposesabeanpropertyasabean
<properties> Createsajava.util.Propertiesfromapropertiesfile,andexposesitasabean
NOTE All the elements of Springs util schema accept a scope attribute that identifies whether the
exposedbeanisasingleton-orprototype-scoped.
SpringprovidesaFactoryBeaninterfacethatcanbeimplementedtocreateafactoryobjectresponsible
forcreatingbeaninstances.Insteadofusingutilschema’selementsmentionedintheabovetable,youcan
useanout-of-the-boxFactoryBeanimplementationprovidedbySpringtoperformthesamefunctionality.
Inthissection,we’lllookattheutilschema’selementsandthebuilt-inFactoryBeanimplementationsthat
youcanuseinsteadofutilschema’selements.
IMPORTchapter3/ch03-util-schema-examples(This project shows a Spring application that makes
useofSpringsutilschemaelementstocreatesharedinstancesofList,Set,Map,andsoon.Torunthe
application,executethemainmethodoftheSampleAppclassofthisproject)
Letsfirstlookatthe<list>element.
<list>
The<list> element ofSprings util schema is used for creating objects of type java.util.List, as shown
here:
Examplelisting3-44–applicationContext.xml-utilschema’s<list>element
Project–ch03-util-schema-examples
Sourcelocation-src/main/resources/META-INF/spring
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=".....http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="listType"ref="listType"/>
.....
</bean>
<util:listid="listType"list-class="java.util.ArrayList">
<value>AsimpleStringvalueinlist</value>
<value>AnothersimpleStringvalueinlist</value>
</util:list>
</beans>
First,youneedtoincludeSpringsutilschematoaccessitselements.Intheaboveexamplelisting,the
<list>elementofutilschemacreatesaninstanceofjava.util.ArrayListandexposesitasabean.Theid
attribute specifies the bean id with which the java.util.ArrayList instance is exposed, and list-class
attribute specifies the concrete implementation of java.util.List that you want to create. If you dont
specify the list-class attribute, an instance of java.util.ArrayList is created by default. The <value>
elementofSpringsbeansschemaisusedtospecifyindividualelementsofthelist.
As util schema’s <list> element exposes a List instance as a bean, you can refer to the exposed List
instancefromotherbeans.Forinstance,intheaboveexamplelisting,thelistTypeconstructorargument
(oftypejava.util.List) of DataTypesExamplebeanspecifies listType as the value of the ref attribute to
refertotheListinstancecreatedbytheutilschema’s<list>element.
If you compare the util schema’s <list> element shown in the above example listing with the beans
schema’s<list>element(referexamplelisting3-27),youllnoticethattheutilschema’s<list>element
gives youcontrol over the List implementation to create.  For instance, if you want to create a Vector
insteadofanArrayListinstance,specifyjava.util.Vectorasthevalueofthelist-classattribute.
LetsnowlookatSpringsListFactoryBeanwhichyoucanuseinsteadofutilschema’s<list>element.
ListFactoryBean
Analternativetousingutilschema’s<list>elementisSpringsListFactoryBean–afactorythatisused
forcreatinginstancesofjava.util.ListandmakingthemavailableasSpringbeans.
ThefollowingexamplelistingshowshowtheListFactoryBeancanbeusedinsteadoftheutilschema’s
<list>element:
Examplelisting3-45–ListFactoryBeanexample
<beans.....>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="listType"ref="listType"/>
.....
</bean>
<beanid="listType"class="org.springframework.beans.factory.config.ListFactoryBean">
<propertyname="sourceList">
<list>
<value>AsimpleStringvalueinlist</value>
<value>AnothersimpleStringvalueinlist</value>
</list>
</property>
</bean>
</beans>
Intheaboveexamplelisting,thesourceListpropertyofListFactoryBeanspecifiestheelementsinthelist.
Bydefault,ListFactoryBeancreatesaninstanceofjava.util.ArrayList.IfyouwanttheListFactoryBeanto
createaninstanceofanyotherListimplementation(likeVector),settheListFactoryBean’stargetListClass
property.ThetargetListClasspropertyspecifiesthefully-qualifiednameoftheconcreteimplementation
classofjava.util.ListinterfacethatshouldbecreatedbytheListFactoryBean.
Ifyoucompareexamplelistings3-44and3-45,youllnoticethatusingutilschema’s<list>elementisa
lotsimplerthanusingtheListFactoryBeantocreateaListinstanceandexposeitasabean.
<map>
The <map> element of Springs util schema is used for creating an object of type java.util.Map and
exposingitasabean,asshownhere:
Examplelisting3-46–applicationContext.xml-utilschema’s<map>element
Project–ch03-util-schema-examples
Sourcelocation-src/main/resources/META-INF/spring
<beans.....
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=".....http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="mapType"ref="mapType"/>
.....
</bean>
<util:mapid="mapType"map-class="java.util.TreeMap">
<entrykey="mapkey1"value="mapkey1’svalue"/>
</util:map>
.....
</beans>
Intheaboveexamplelisting,utilschema’s<map>elementcreatesaninstanceofjava.util.TreeMapand
exposes it as a bean. The id attribute specifies the id with which the bean is made available to other
beans,andmap-classattributespecifiesthefully-qualifiednameoftheconcreteimplementationclassof
java.util.Map interface that should be created by the <map> element. The <entry> element of Springs
beansschemaspecifiesakey-valuepairinthecreatedMapinstance.
Asthe<map>elementexposesaMapinstanceasabean,theexposedMapinstancecanbereferenced
fromotherbeans.Forinstance,intheaboveexamplelisting,DataTypesExample’smapTypeconstructor
argument (of type java.util.Map) specifies value of ref attribute as mapType to refer to the TreeMap
instancecreatedbythe<map>element.
NOTEWesawearlierinthischapterthat<key>and<value>sub-elementsof<entry>areusedtospecify
akey-valuepaircontainedintheMapinstance.Theexamplelisting3-46showsthatyoucanalsospecify
akey-valuepaircontainedintheMapinstancebyusing<entry>elementskeyandvalueattributes.
If you compare the util schema’s <map> element shown in the above example listing with the beans
schema’s <map> element in example listing 3-27, youll notice that the util schema’s <map> element
gives you control over the Map implementation to create.  For instance, if you want to use
LinkedHashMap instead of TreeMap, specify java.util.LinkedHashMap as the value of map-class
attribute. If you don’t specify the map-class attribute, Spring container creates an instance of
java.util.LinkedHashMapbydefault.
LetsnowlookatSpringsMapFactoryBeanthatyoucanuseinsteadofutilschema’s<map>element.
MapFactoryBean
Insteadofusingutilschema’s<map>element,youcanuseSpringsMapFactoryBean–afactorythatis
usedforcreatinginstancesofjava.util.MapandmakingthemavailableasSpringbeans.
ThefollowingexamplelistingshowshowMapFactoryBeanisused:
Examplelisting3-47–MapFactoryBeanexample
<beans.....>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="mapType"ref="mapType"/>
.....
</bean>
<beanid="mapType"class="org.springframework.beans.factory.config.MapFactoryBean">
<propertyname="sourceMap">
<map>
<entrykey="mapkey1"value="mapkey1’svalue"/>
</map>
</property>
</bean>
.....
</beans>
In the above example listing, MapFactoryBean’s sourceMap property specifies the key-value pairs
containedintheMapinstancecreatedbytheMapFactoryBean.Bydefault,MapFactoryBeancreatesan
instanceofjava.util.LinkedHashMap.YoucancontroltheMapinstancecreatedbyMapFactoryBeanby
setting the targetMapClass property. The targetMapClass specifies the fully-qualified name of the
concreteimplementationclassofjava.util.Mapinterface.Forinstance,ifyouspecifyjava.util.HashMap
asthevalueoftargetMapClass,MapFactoryBeancreatesaninstanceofjava.util.HashMap.
If you compare example listings 3-46 and 3-47, youll notice that using util schema’s <map> element
resultsinamoreconciseconfigurationthanMapFactoryBeanforcreatingMapinstances.
<set>
The<set>elementofSpringsutilschemaisusedforcreatinganobjectoftypejava.util.Setandexposing
itasabean,asshownhere:
Examplelisting3-48–applicationContext.xml-utilschema’s<set>element
Project–ch03-util-schema-examples
Sourcelocation-src/main/resources/META-INF/spring
<beans.....
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=".....http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="setType"ref="setType"/>
</bean>
<util:setid="setType"set-class="java.util.HashSet">
<value>Element1</value>
<value>Element2</value>
</util:set>
.....
</beans>
Intheaboveexamplelisting,utilschema’s<set>elementcreatesaninstanceofHashSetandexposesitas
aSpringbeanwithidassetType.Theidattributespecifiestheidwithwhichthebeanismadeavailable
to other beans, and the set-class attribute specifies the concrete implementation class of java.util.Set
interface that should be created by the <set> element. The <value> element of Springs beans schema
specifiesanelementinthecreatedSetinstance.
TheSetinstancecreatedbythe<set>elementcanbereferencedfromotherbeans.Forinstance,inthe
aboveexamplelisting,DataTypesExample’ssetTypeconstructorargument(oftypejava.util.Set)refersto
theHashSetinstancecreatedbythe<set>element.
Insteadofusingutilschema’s<set>element,youcanuseSpringsSetFactoryBeantocreateaSetinstance
andexposeitasaSpringbean.
SetFactoryBean
SpringsSetFactoryBeanisafactoryobjectforcreatinginstancesofjava.util.Settype.
ThefollowingexamplelistingshowshowyoucanuseSetFactoryBeantoperformthesamefunctionasthe
utilschema’s<set>element:
Examplelisting3-49–SetFactoryBeanexample
<beans.....>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="setType"ref="setType"/>
.....
</bean>
<beanid="setType"class="org.springframework.beans.factory.config.SetFactoryBean">
<propertyname="sourceSet">
<set>
<value>Element1</value>
<value>Element2</value>
</set>
</property>
</bean>
.....
</beans>
Intheaboveexamplelisting,SetFactoryBeanssourceSetpropertyspecifiestheelementscontainedinthe
SetinstancecreatedbytheSetFactoryBean.SetFactoryBeanstargetSetClasspropertyspecifiesthefully-
qualified name of the class that implements java.util.Set interface. If the targetSetClass property is
specified,SetFactoryBeancreatesaninstance of the class specified bythe targetSetClass property and
makes it available as a Spring bean. For instance, if you specify java.util.HashSet as the value of
targetSetClass,SetFactoryBeancreatesaninstanceofjava.util.HashSet.IfthetargetSetClasspropertyis
unspecified,SetFactoryBeancreatesaninstanceofjava.util.LinkedHashSet.
The above example listing shows that using util schema’s <set> element results in a more concise
configurationthanusingSetFactoryBeanforcreatingSetinstances.
<properties>
Theutilschema’s<properties>elementisusefulifyouwanttocreateaninstanceofjava.util.Properties
objectfromapropertiesfile,andexposethejava.util.Propertiesobjectasabean.
Thefollowingexamplelistingshowshowthe<properties>elementisused:
Examplelisting3-50–applicationContext.xml-utilschema’s<properties>element
Project–ch03-util-schema-examples
Sourcelocation-src/main/resources/META-INF/spring
<beans.....
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=".....http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails">
.....
<propertyname="branchAddresses"ref="branchAddresses"/>
</bean>
.....
<util:propertiesid="branchAddresses"
location="classpath:META-INF/addresses.properties"/>
</beans>
Intheaboveexamplelisting,<properties>elementcreatesaninstanceofjava.util.Propertiescontaining
propertiesloadedfromtheaddresses.propertiesfile(specifiedbythelocationattribute),andexposesthe
java.util.PropertiesinstanceasabeanwithbranchAddressesastheid(specifiedbytheidattribute).The
above example listing also shows that the branchAddresses property (of type java.util.Properties) of
BankDetailsbeanreferstothebranchAddressesbeancreatedbytheutilschema’s<properties>element.
Analternativetousingthe<properties>elementisSpringsPropertiesFactoryBean.
PropertiesFactoryBean
SpringsPropertiesFactoryBeanisafactoryforcreatinginstancesofjava.util.Properties.
The following example listing shows how you can use PropertiesFactoryBean to perform the same
functionastheutilschema’s<properties>element:
Examplelisting3-51–PropertiesFactoryBeanexample
<beans.....>
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails">
.....
<propertyname="branchAddresses"ref="branchAddresses"/>
</bean>
<beanid="branchAddresses"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<propertyname="location"value="classpath:META-INF/addresses.properties"/>
</bean>
.....
</beans>
Intheaboveexamplelisting,beandefinitionforSpringsPropertiesFactoryBeancreates an instance of
java.util.Properties from the properties loaded from addresses.properties file (specified by location
property),andexposesthejava.util.PropertiesinstanceasabeanwithbranchAddressesastheid.
<constant>
Theutilschema’s<constant>elementisusedforexposinganobjectspublicstaticfieldasaSpringbean.
Thefollowingexamplelistingshowsanexampleusageof<constant>element:
Examplelisting3-52–applicationContext.xml-utilschema’s<constant>element
Project–ch03-util-schema-examples
Sourcelocation-src/main/resources/META-INF/spring
<beans.....xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=".....http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="booleanType"ref="booleanTrue"/>
.....
</bean>
<util:constantid="booleanTrue"static-field="java.lang.Boolean.TRUE"/>
.....
</beans>
Theutilschema’s<constant>elementexposesthevaluespecifiedbyitsstatic-fieldattributeasaSpring
bean. In the above example listing, <constant> element exposes a bean whose value is
java.lang.Boolean.TRUEandidisbooleanTrue.Youcanspecifyanypublicstaticfieldasthevalueofthe
static-fieldattributeand refertoitfromotherbeansintheSpringcontainer.Forinstance,intheabove
example listing, booleanType bean is referenced by DataTypesExample’s booleanType constructor
argumentoftypeboolean.
A rather less concise way to expose public static fields as Spring beans is to use Springs
FieldRetrievingFactoryBean.
FieldRetrievingFactoryBean
SpringsFieldRetrievingFactoryBeanisafactoryforretrievingvalueofapublicstaticfieldspecifiedby
the FieldRetrievingFactoryBeans staticField property. The value retrieved by the
FieldRetrievingFactoryBeanisexposedasabean.YoucanalsousetheFieldRetrievingFactoryBeanto
retrieveanon-staticfieldvalue.
ThefollowingexamplelistingshowsanexampleusageofFieldRetrievingFactoryBean:
Examplelisting3-53–FieldRetrievingFactoryBeanexample
<beans.....>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="booleanType"ref="booleanTrue"/>
.....
</bean>
<beanid="booleanTrue"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<propertyname="staticField"value="java.lang.Boolean.TRUE"/>
</bean>
.....
</beans>
Intheaboveexamplelisting,FieldRetrievingFactoryBeanretrievesthevalueofjava.lang.Boolean.TRUE
field and exposes it as a bean. The bean exposed by the FieldRetrievingFactoryBean is referenced by
DataTypesExample’sbooleanTypeconstructorargumentoftypeboolean.
<property-path>
Theutilschema’s<property-path>elementisusedtoexposeabeanpropertyvalueasabean.
Thefollowingexamplelistingshowsanexampleusageof<property-path>element:
Examplelisting3-54–applicationContext.xml-utilschema’s<property-path>element
Project–ch03-util-schema-examples
Sourcelocation-src/main/resources/META-INF/spring
<beans.....
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=".....http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails">
.....
<propertyname="dateOfInception"ref="dateType"/>
.....
</bean>
<util:property-pathid="dateType"path="dataTypes.dateType"/>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<propertyname="dateType"value="30-01-2012"/>
.....
</bean>
</beans>
In the above example listing, DataTypesExample’s dateType property (of type java.util.Date) value is
specified as ‘30-01-2012’. The <property-path> element retrieves the DataTypesExample’s dateType
propertyandexposesitasabeanwithidasdateType.Thepathattributeof<property-path>elementhas
thefollowingsyntax:
<bean-name>.<bean-property>
Here,<bean-name>istheidornameofthebean,and<bean-property>isthenameoftheproperty.
As<property-path>elementexposesa bean,theexposedbean canbereferencedbyother beansinthe
Spring container. For instance in the above example listing, dateType bean is referenced by
dateOfInceptionpropertyofBankDetailsbean.
Instead of using <property-path> element, you can use Springs PropertyPathFactoryBean to expose a
beanpropertyvalueasabean.
PropertyPathFactoryBean
PropertyPathFactoryBean is a factory used for creating bean instances that represent a bean property
value.
ThefollowingexamplelistingshowshowtousePropertyPathFactoryBean:
Examplelisting3-55–PropertyPathFactoryBeanexample
<beans.....
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=".....http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails">
.....
<propertyname="dateOfInception"ref="dateType"/>
.....
</bean>
<beanid="dataType"
class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<propertyname="targetBeanName"value="dataTypes"/>
<propertyname="propertyPath"value="dateType"/>
</bean>

<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<propertyname="dateType"value="30-01-2012"/>
.....
</bean>
</beans>
In the above example listing, PropertyPathFactoryBean is used to create an instance of a bean that
representsthevalueofdateTypepropertyofdataTypesbean.PropertyPathFactoryBeanstargetBeanName
attributespecifiestheidornameofthebeanthatcontainstheproperty,andPropertyPathFactoryBeans
propertyPath attribute specifies thename ofthe property whose valueis tobeexposed as a bean. The
bean instance created by PropertyPathFactoryBean can be accessed by other beans in the Spring
container. In the above example listing, the dataType bean created by PropertyPathFactoryBean is
referencedbydateOfInceptionproperty(oftypejava.util.Date)ofBankDetailsbean.
Now, that we have taken an in-depth look at util schema elements, lets look at Springs FactoryBean
interface.
3-9FactoryBeaninterface
SpringsFactoryBeaninterfaceisimplementedbyclassesthatactasafactoryforcreatingbeaninstances.
Intheprevioussection,wesawthattheclassesthatimplementtheFactoryBeaninterfaceareconfigured
intheapplicationcontextXMLfilelikeanyotherbean.FactoryBeanisparticularlyusefulifyouwantto
performcomplicatedconditionalcheckstodecideonwhichbeantypetocreate,andtoexecutecomplex
beaninitializationlogic.
Letsnowlookatanapplicationscenarioinwhichwe’lluseFactoryBeanforselectingabeantype,and
thencreatingit.
MyBankapplication–Storingeventsinthedatabase
In MyBank application, important events, like credit and debit transactions, open and liquidate fixed
deposits,andsoon,aresavedinthedatabase.MyBankmaydirectlysavetheseeventsinthedatabaseor
indirectlybyfirstsendingtheeventstoamessagingmiddlewareorawebservice.Thefollowingtable
describestheclassesthataredefinedbytheMyBankapplicationfordirectlyorindirectlysavingevents:
Class Description
DatabaseEventSender
Classthatcontainsthefunctionalityforsavingeventsinthedatabase
MessagingEventSender Classthatcontainsthefunctionalityforsendingeventstoamessagingmiddleware
WebServiceEventSender Classthatcontainsthefunctionalityforsendingeventstoaremotewebservice
Thedecisiontodirectlysavetheeventsinthedatabaseortosendthemtoamessagingmiddlewareora
web service is based on configuration. For instance, if MyBank finds that there exists a
database.properties file, MyBank reads the configuration information (like database url, username and
password)fromthedatabase.propertiesfileandcreatestheDatabaseEventSenderinstance.Similarly,ifa
messging.propertiesfileexists,MyBankcreatesaninstanceofMessagingEventSenderinstance,andifa
webservice.propertiesfileexists,aninstanceofWebServiceEventSenderiscreated.
Initializing DatabaseEventSender, MessagingEventSender and WebServiceEventSender instances may
require executing complex initialization logic. For instance, you need to create (or obtain from JNDI)
javax.jms.ConnectionFactory and javax.jms.Destination instances and set them on the
MessagingEventSender instance so that the MessagingEventSender can send JMS messages to the
messagingmiddleware.
The following class diagram shows that the FixedDepositServiceImpl class of MyBank uses either
DatabaseEventSender or MessagingEventSender or WebServiceEventSender instance to directly or
indirectlysaveeventsrelatedtofixeddepositsinthedatabase:
Figure3-7FixedDepositServiceImplclassusesoneoftheimplementationsofEventSenderinterface.
Intheaboveclassdiagram,sendEventmethodofEventSenderinterfacedefinesthecontractfordirectly
or indirectly saving events in the database. DatabaseEventSender, MessagingEventSender and
WebServiceEventSender classes implement the EventSender interface and provide an appropriate
implementationforthesendEventmethod.
LetsnowlookathowFactoryBeansimplifieschoosingtherightimplementationofEventSenderinterface
andinitializingit.
IMPORTchapter3/ch03-bankapp-factorybean(ThisprojectshowstheMyBankapplicationthatusesa
FactoryBean implementation to create objects of type EventSender. To run the application, execute the
mainmethodoftheBankAppclassofthisproject)
MyBankFactoryBeanexample
In MyBank, selecting the right EventSender implementation and initializing it is an involved task;
therefore,itrepresentsanidealscenarioforusingaFactoryBeanimplementation.FactoryBeaninterface
definesthefollowingmethodsthatyouneedtoimplement:
·getObjectType:returnsthetypeoftheobjectmanagedbytheFactoryBeanimplementation.In
caseofMyBank,theFactoryBeanimplementationcreatesandreturnsobjectsoftypeEventSender.
·getObject:returnstheobjectmanagedbytheFactoryBeanimplementation.IncaseofMyBank,
the getObject method returns an instance of DatabaseEventSender or MessagingEventSender or
WebServiceEventSender.
· isSingleton:returnstrueiftheFactoryBean implementation is afactoryfor singleton-scoped
objects.IftheisSingletonmethodreturnstrue,theobjectreturnedbythegetObjectmethodiscached
bytheSpringcontainerandthesameinstanceisreturnedonsubsequentrequests.IftheFactoryBean
implementationisafactoryforprototype-scopedobjects,returnfalsefromtheisSingletonmethod.
IftheisSingletonmethod returns false, a fresh instance is created by getObject method on every
request. In case of MyBank, FactoryBean implementation returns an instance of
DatabaseEventSender or MessagingEventSender or WebServiceEventSender class. Once created,
the same instance is used throughout the lifetime of the MyBank application; therefore, the
isSingletonmethodreturnstrueincaseofMyBank.
ThefollowingexamplelistingshowstheEventSenderFactoryBean–theFactoryBeanimplementationthat
createsandreturnsobjectsoftypeEventSender:
Examplelisting3-56–EventSenderFactoryBeanclass
Project–ch03-bankapp-factorybean
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/event
packagesample.spring.chapter03.bankapp.event;
importorg.springframework.beans.factory.FactoryBean;
importorg.springframework.beans.factory.FactoryBeanNotInitializedException;
importorg.springframework.core.io.ClassPathResource;
.....
publicclassEventSenderFactoryBeanimplementsFactoryBean<EventSender>{
privateStringdatabasePropertiesFile;
privateStringwebServicePropertiesFile;
privateStringmessagingPropertiesFile;
.....
publicEventSendergetObject()throwsException{
EventSendereventSender=null;
Propertiesproperties=newProperties();
ClassPathResourcedatabaseProperties=null;
if(databasePropertiesFile!=null){
databaseProperties=newClassPathResource(databasePropertiesFile);
}
.....
if(databaseProperties!=null&&databaseProperties.exists()){
InputStreaminStream=databaseProperties.getInputStream();
properties.load(inStream);
eventSender=newDatabaseEventSender(properties);
}
elseif(webServiceProperties!=null&&webServiceProperties.exists()){.....}
elseif(messagingProperties!=null&&messagingProperties.exists()){.....}
returneventSender;
}
publicClass<?>getObjectType(){
returnEventSender.class;
}
publicbooleanisSingleton(){
returntrue;
}
}
The above example listing shows that the EventSenderFactoryBean implements FactoryBean interface.
The EventSender parameter in FactoryBean<EventSender> indicates that the FactoryBeans getObject
returns objects of type EventSender. The databasePropertiesFile, webServicePropertiesFile and
messagingPropertiesFile are properties of the EventSenderFactoryBean class, and they represent the
locationofdatabase.properties,webservice.propertiesandmessaging.propertiesfilesintheclasspath.
ThegetObjectmethodusesSpringsClassPathResourceclasstoverifywhetherthespecifiedproperties
file exists in the classpath or not. If the properties file exists, properties from that file are loaded and
passed as to the EventSender implementation classs constructor. For instance, in the above example
listing,ifdatabase.propertiesfile(representedbydatabasePropertiesFileproperty)exists,propertiesare
loaded from the database.properties file and passed as an argument to the DatabaseEventSenders
constructor.ThegetObjectTypemethodreturnsEventSendertypebecausetheEventSenderFactoryBeans
getObjectmethodreturnsobjectsoftypeEventSender.TheisSingletonmethodreturnstrue,whichmeans
thattheobjectreturnedbygetObjectmethodiscachedbySpringandthesameinstanceisreturnedevery
timeEventSenderFactoryBeansgetObjectmethodisinvoked.
Now, that you have seen how EventSenderFactoryBean class is implemented in the MyBank, you can
guesshowSpring’sbuilt-inFactoryBeanimplementations,likeListFactoryBean(forcreatinginstancesof
Listtype),MapFactoryBean(forcreatinginstancesofMaptype),SetFactoryBean(forcreatinginstances
ofSettype),andsoon,areimplemented.
The following example listing shows how EventSenderFactoryBean is configured in the application
contextXMLfile:
Examplelisting3-57–applicationContext.xml-EventSenderFactoryBeanconfiguration
Project–ch03-bankapp-factorybean
Sourcelocation-src/main/resources/META-INF/spring
<beans.....>
<beanid="service"
class="sample.spring.chapter03.bankapp.service.FixedDepositServiceImpl">
.....
<propertyname="eventSender"ref="eventSenderFactory"/>
</bean>
.....
<beanid="eventSenderFactory"
class="sample.spring.chapter03.bankapp.event.EventSenderFactoryBean">
<propertyname="databasePropertiesFile"value="META-INF/config/database.properties"/>
</bean>
</beans>
The above example listing shows thattheEventSenderFactoryBean is configured likeanyother Spring
bean.EventhoughaFactoryBeanimplementationisconfiguredlikeanyotherSpringbean,itistreated
differentlybytheSpringcontainer.Oneofthemostimportantdifferencesisthatifabeanisdependenton
a FactoryBean implementation, the Spring container invokes the getObject method of the FactoryBean
implementationandinjectsthereturnedobjectintothedependentbean.
NOTEYoushouldnotethatFactoryBeansgetObjectmethodisinvokedonlyoncebytheSpring
containeriftheisSingletonmethodreturnstrue.
In the above example listing, bean definition for the FixedDepositServiceImpl class shows that it is
dependent on the EventSenderFactoryBean – a FactoryBean implementation. So, the Spring container
invokestheEventSenderFactoryBeansgetObjectmethodandinjectsthereturnedEventSenderobjectinto
theFixedDepositServiceImplinstance.
The following example listing shows the FixedDepositServiceImpl class that requires EventSender
instancecreatedbyEventSenderFactoryBean:
Examplelisting3-58–FixedDepositServiceImplclass
Project–ch03-bankapp-factorybean
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/service
packagesample.spring.chapter03.bankapp.service;
importsample.spring.chapter03.bankapp.event.EventSender;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
.....
privateEventSendereventSender;
publicvoidsetEventSender(EventSendereventSender){
this.eventSender=eventSender;
}
.....
publicvoidcreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
.....
eventSender.sendEvent(event);
}
}
The above example listing shows that the FixedDepositServiceImpl class depends on an EventSender
instanceandnotontheEventSenderFactoryBeaninstance.TheSpringcontainerobtainstheEventSender
instancebyinvokingEventSenderFactoryBean’sgetObjectmethod,andinjectstheobtainedEventSender
instanceintotheFixedDepositServiceImplinstance.
Letsnow lookathowto access theFactoryBean itself and not the bean it creates and returns via the
getObjectmethod.
AccessingtheFactoryBeaninstance
If you want to obtain the FactoryBean itself from the Spring container, prefix the name (or id) of the
factorybeanwithampersand‘&’.
LetssaythattheFixedDepositServiceImplclassrequiresaccesstotheEventSenderFactoryBeanitself,
asshownhere:
Example listing 3-59 – FixedDepositServiceImpl class that depends on the EventSenderFactoryBean
itself
packagesample.spring.chapter03.bankapp.service;
importsample.spring.chapter03.bankapp.event.EventSenderFactoryBean;
importsample.spring.chapter03.bankapp.event.EventSender;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
.....
privateEventSenderFactoryBeaneventSenderFactoryBean;
publicvoidsetEventSenderFactoryBean(EventSenderFactoryBeaneventSenderFactoryBean){
this.eventSenderFactoryBean=eventSenderFactoryBean;
}
.....
publicvoidcreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
.....
EventSendereventSender=eventSenderFactoryBean.getObject();
evenSender.sendEvent(event);
}
}
Intheaboveexamplelisting,theFixedDepositServiceImplclassdependsontheEventSenderFactoryBean
itself,andusesitsgetObjectmethodtoobtainaninstanceofEventSenderobject.
Wesawinexamplelisting3-57thatwhenyoudefinetheEventSenderFactoryBeanbeanasadependency
of FixedDepositServiceImpl bean, the Spring container invokes the getObject method of
EventSenderFactoryBeanandinjectsthereturnedEventSenderobjectintotheFixedDepositServiceImpl
bean. To instruct the Spring container to inject the EventSenderFactoryBean itself, add ampersand ‘&’
prefixtotheid(orname)ofthebeanspecifiedbytherefattribute,asshowninthefollowingexample
listing:
Examplelisting3-60–InjectingtheEventSenderFactoryBeaninstanceintotheFixedDepositServiceImpl
bean
<beans.....>
<beanid="service"class="sample.spring.chapter03.bankapp.service.FixedDepositServiceImpl">
.....
<propertyname="eventSenderFactoryBean"ref="&amp;eventSenderFactory"/>
</bean>
.....
<beanid="eventSenderFactory"
class="sample.spring.chapter03.bankapp.event.EventSenderFactoryBean">
<propertyname="databasePropertiesFile"value="META-INF/config/database.properties"/>
</bean>
</beans>
In the above example listing, the following <property> element specifies that the
FixedDepositServiceImplbeanisdependentonEventSenderFactoryBean:
<propertyname="eventSenderFactoryBean"ref="&amp;eventSenderFactory"/>
Noticethattherefattribute’svalueis"&amp;eventSenderFactory".The&amp;prefixinstructstheSpring
containertoinjecttheEventSenderFactoryBeaninstanceitselfintotheFixedDepositServiceImplbean.
The use of ampersand ‘&’ is also required when you want to retrieve the FactoryBean instance itself
usingApplicationContext’sgetBeanmethod.ThefollowingexamplelistingshowstheBankAppclassof
MyBankapplicationthatretrievestheEventSenderobjectcreatedbytheEventSenderFactoryBean, and
theEventSenderFactoryBeaninstanceitself:
Examplelisting3-61–BankAppclass
Project–ch03-bankapp-factorybean
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp
packagesample.spring.chapter03.bankapp;
.....
publicclassBankApp{
privatestaticLoggerlogger=Logger.getLogger(BankApp.class);

publicstaticvoidmain(Stringargs[]){
ApplicationContextcontext=newClassPathXmlApplicationContext(
.....
logger.info("InvokinggetBean(\"eventFactory\")returns:"+
context.getBean("eventSenderFactory"));
logger.info("InvokinggetBean(\"&eventFactory\")returns:"+
context.getBean("&eventSenderFactory"));
}
}
If you execute the main method of the BankApp class shown above, youll find that calling
getBean("eventSenderFactory") returns an instance of DatabaseEventSender class, and
getBean("&eventSenderFactory")returnsEventSenderFactoryBeaninstance.
3-10Summary
In this chapter, we saw how you can use bean definition inheritance to create less verbose and easily
manageablebeandefinitions.Themajorityofthischapterfocusedonhowtosetdifferenttypesofbean
properties andconstructorargumentsusingbuilt-inFactoryBeanimplementations,Springsutil schema,
and p- and c-namespaces. We also looked at some of the built-in PropertyEditor implementations in
SpringandhowtoregisteradditionalpropertyeditorswiththeSpringcontainer.Inthenextchapter,well
takeanin-depthlookatdependencyinjectionfeatureofSpring.
Chapter4-Dependencyinjection
4-1Introduction
In the previous chapter, we looked at how to configure beans using Springs util schema, p- and c-
namespaces,FactoryBeanimplementations,andsoon.Inthischapterwefocusondifferentdependency
injectionscenarios which we typically come across inreal world application development efforts and
howSpringaddressesthesescenarios.
We’llbeginthischapterwithalookatinnerbeans-analternativetousingtherefattributeof<property>
and<constructor-arg> elements. Well then look at depends-on attribute of the <bean> element. In the
second half of this chapter, we’ll look at issues that may arise when singleton- and prototype-scoped
beans collaborate to provide application behavior. Well wrap this chapter with an in-depth look at
Springsautowiringfeature.
IMPORTchapter4/ch04-bankapp-dependencies(Thisprojectshowsusageofinnerbeansand<bean>
element’sdepends-onattribute.Thisprojectalsoshowsimplicationsofdefiningdependenceofsingleton-
scopedbeansonprototype-scopedbeans,andviceversa.Toruntheapplication,executethemainmethod
oftheBankAppclassofthisproject)
4-2Innerbeans
Ifadependencyofabeanisnotsharedbymultiplebeans,youcanconsiderdefiningthedependencyasan
inner bean. An inner bean is defined inside a <property> or <constructor-arg> element by using the
<bean>elementofSpringsbeansschema.Youshouldnotethataninnerbeanisonlyaccessibletothe
beandefinitionenclosingit,andnottootherbeansregisteredwiththeSpringcontainer.
Thefollowingexamplelistingshowshowwegenerallyrepresentbeandependencies:
Examplelisting4-1–Dependencyspecifiedusing<property>elementsrefattribute
<beanid="service"
class="sample.spring.chapter04.bankapp.service.FixedDepositServiceImpl">
<propertyname=“fixedDepositDao"ref="dao"/>
</bean>
<beanid="dao"class="sample.spring.chapter04.bankapp.dao.FixedDepositDaoImpl"/>
Theaboveexamplelistingshowsthattheservicebeanisdependentondaobean.Ifservicebeanisthe
onlybeanthatisdependentonthedaobean,thenyoucandefinethedaobeanasaninnerbeanofservice
bean.
Examplelisting4-2–applicationContext.xml-Innerbeanexample
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/resources/META-INF/spring
<beanid="service"
class="sample.spring.chapter04.bankapp.service.FixedDepositServiceImpl">
<propertyname=“fixedDepositDao">
<beanclass="sample.spring.chapter04.bankapp.dao.FixedDepositDaoImpl"/>
</property>
</bean>
In the above example listing, the bean definition for the FixedDepositDaoImpl class is inside the
<property>elementofservicebean.Ifyoucomparetheaboveexamplelistingwith4-1,youllnoticethat
the<property> element no longer specifies the ref attribute, and the <bean> element corresponding to
FixedDepositDaoImplclassdoesnthavetheidattributeanymore.
The<bean>elementcorrespondingtoaninnerbeandefinitiondoesn’tspecifyanidattributebecausean
inner bean is not registered with the Spring container. If you specify an id attribute for an inner bean
definition,itisignoredbytheSpringcontainer.Aninnerbeanisalwaysprototype-scoped;therefore,if
the <bean> element corresponding to an inner bean definition specifies the scope attribute, then it is
ignoredbytheSpringcontainer.Itisimportanttonotethataninnerbeanisanonymousinnature,andits
not accessible to other beans (except the bean that contains the inner bean definition) in the Spring
container.
NOTEAsincaseofnormalbeandefinition,youcanuse<property>,<constructor-arg>,andsoon,
elementsinsidethe<bean>elementoftheinnerbeandefinition.
Inthepreviouschapter,wesawthatSpringsutilschemaelementsareusedtocreatebeansthatrepresent
a List, Set, Map, and so on. We saw that the beans created by Springs util schema elements are
referenced by other beans. The concept of inner beans makes it possible to use Springs util schema
elements inside <property> and <constructor-arg> elements also, as shown in the following example
listing:
Examplelisting4-3–utilschema’s<list>elementdefinesaninnerbean
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=".....http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<beanid="someBean"class="com.sample.SomeBean">
.....
<constructor-argname="listType">
<util:listlist-class="java.util.ArrayList">
<value>AsimpleStringvalueinlist</value>
<value>AnothersimpleStringvalueinlist</value>
</util:list>
</constructor-arg>
.....
</bean>
</beans>
Intheaboveexamplelisting,thelistTypeconstructorargumentisoftypejava.util.List.Thevaluepassed
tothelistTypeconstructorargumentisspecifiedbytheutilschema’s<list>element.Notethatwedidnt
specifytheidattributeofthe<list>elementbecauseSpringcontainerignoresidsofinnerbeans.
Letsnowlookatdepends-onattributeof<bean>element.
4-3Explicitlycontrollingthebeaninitializationorderwithdepends-on
attribute
Insection1-4ofchapter1,wediscussedthatbeansarecreatedintheorderinwhichtheyaredefinedin
theapplicationcontextXMLfile.Theorderinwhichbeansarecreatedisalsodecidedbasedontheinter-
dependenciesofbeans.Forinstance,ifbeanAacceptsaninstanceofbeanBasaconstructorargument,
theSpringcontainerwillcreatebeanBbeforebeanAirrespectiveoftheorderinwhichtheyaredefined
intheapplicationcontextXMLfile.ThisbehavioroftheSpringcontainerensuresthatthedependencies
ofabean(beanBisadependencyinourexample)arecompletelyconfiguredbeforetheyareinjectedinto
thedependentbean(beanAisadependentbeaninourexample).
In some application scenarios, bean dependencies are not explicitly specified via <property> and
<constructor-arg> elements. If the bean dependencies arenot explicit, you can use <bean> element’s
depends-on attribute to explicitly specify dependencies of a bean. Spring container ensures that bean
dependencies specified by the depends-on attribute are initialized before the bean that specifies the
depends-onattribute.
Letsnowlookatanexamplescenarioinwhichdepends-onattributeisusedtocontroltheinitialization
orderofbeans.
MyBankimplieddependenciesbetweenbeans
IntheMyBankapplicationofthepreviouschapter,aFactoryBeanimplementationcreatedanEventSender
objectthatwasusedbytheFixedDepositServiceImplinstancetodirectlyorindirectlystoreeventsinthe
database (refer section 3-9 of chapter 3 for details). Lets say that instead of using a FactoryBean
implementation for creating an EventSender implementation, the approach shown in the following
diagramisadopted:
Figure4-1EventSenderSelectorServiceImplclasswritesthenameoftheEventSenderimplementation
intheappConfig.propertiesfile,whichislaterreadbytheFixedDepositServiceImplinstance
Theabovediagramshowsthat:
·anEventSenderSelectorServiceImplclassisusedtodecideontheEventSenderimplementation
(DatabaseEventSender or WebServiceEventSender or MessagingEventSender) to be used by the
FixedDepositServiceImplclass
·        EventSenderSelectorServiceImpl class stores the fully-qualified name of the EventSender
implementationintheappConfig.propertiesfile
·        FixedDepositServiceImpl class reads the fully-qualified name of the EventSender
implementationfromtheappConfig.propertiesfile,createstheEventSenderobjectandusesitfor
storingfixeddepositeventsinthedatabase
The above approach suggests that the FixedDepositServiceImpl instance wont work correctly if
EventSenderSelectorServiceImpl fails to save the fully-qualified name of the EventSender
implementation in the appConfig.properties file. This means that the FixedDepositServiceImpl class is
implicitlydependentontheEventSenderSelectorServiceImplclass.
Lets now look at the implication of implicit dependence of FixedDepositServiceImpl instance on the
EventSenderSelectorServiceImplinstance.
Implicitdependencyproblem
Consider the following application context XML file that contains bean definitions for
FixedDepositServiceImplandEventSenderSelectorServiceImplclasses:
Examplelisting4-4–applicationContext.xml-Implicitdependencyexample
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/resources/META-INF/spring
<beans.....>
<beanid="service"
class="sample.spring.chapter04.bankapp.service.FixedDepositServiceImpl">
.....
<constructor-argindex="0"value="META-INF/config/appConfig.properties"/>
</bean>
<beanid="eventSenderSelectorService"
class="sample.spring.chapter04.bankapp.service.EventSenderSelectorServiceImpl">
<constructor-argindex="0"value="META-INF/config/appConfig.properties"/>
</bean>
</beans>
The above application context XML file shows that both FixedDepositServiceImpl and
EventSenderSelectorServiceImplclasssconstructoracceptlocationoftheappConfig.propertiesfile.The
EventSenderSelectorServiceImplinstanceusestheappConfig.propertiesfileforcommunicatingthefully-
qualifiednameoftheEventSenderimplementationclasstotheFixedDepositServiceImplinstance.Asan
explicit dependence doesn’t exist between service and eventSenderSelectorService beans, Spring
containercreates theirinstancesintheorder inwhich theyare defined intheapplicationcontextXML
file. As the service bean is defined before the eventSenderSelectorService bean,
FixedDepositServiceImplinstance is created before EventSenderSelectorServiceImpl instance. We’ll
soon see that if FixedDepositServiceImplinstance is created before EventSenderSelectorServiceImpl
instance,theFixedDepositServiceImplinstancewillnotbeabletoreadthenameofthefully-qualified
EventSenderimplementationclassfromtheappConfig.propertiesfile.
Lets now take an in-depth look at the EventSenderSelectorServiceImpl and FixedDepositServiceImpl
classes,andtheappConfig.propertiesfile.
EventSenderSelectorServiceImplthewriter
ThefollowingexamplelistingshowstheEventSenderSelectorServiceImplclass:
Examplelisting4-5–EventSenderSelectorServiceImplclass
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importorg.springframework.core.io.ClassPathResource;
importsample.spring.chapter04.bankapp.Constants;
publicclassEventSenderSelectorServiceImpl{
publicEventSenderSelectorServiceImpl(StringconfigFile)throwsException{
ClassPathResourceresource=newClassPathResource(configFile);
OutputStreamos=newFileOutputStream(resource.getFile());
Propertiesproperties=newProperties();
properties
.setProperty(Constants.EVENT_SENDER_CLASS_PROPERTY,
"sample.spring.chapter04.bankapp.event.DatabaseEventSender");
properties.store(os,null);
.....
}
}
TheaboveexamplelistingshowsthatthelocationofappConfig.propertiesfileispassedasaconstructor
argument to the EventSenderSelectorServiceImpl classs constructor. The
EventSenderSelectorServiceImpl class’sconstructorwritesa property namedeventSenderClass (which
is the value of EVENT_SENDER_CLASS_PROPERTYconstant defined in the Constants class) to the
appConfig.properties file. The eventSenderClass property specifies the fully-qualified name of the
EventSender implementation to be used by the FixedDepositServiceImpl instance for directly or
indirectly saving events in the database. For the sake of simplicity, EventSenderSelectorServiceImpl
classs constructor sets the fully-qualified name of the DatabaseEventSender class as the value of
eventSenderClassproperty.
appConfig.properties
The following is the entry that gets added to the appConfig.propertiesfile by
EventSenderSelectorServiceImplclass:
eventSenderClass=sample.spring.chapter04.bankapp.event.DatabaseEventSender
FixedDepositServiceImplthereader
The eventSenderClass property written by the EventSenderSelectorServiceImpl instance is read by the
FixedDepositServiceImplinstance,asshowninthefollowingexamplelisting:
Examplelisting4-6–FixedDepositServiceImplclass
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importorg.springframework.core.io.ClassPathResource;
importsample.spring.chapter04.bankapp.Constants;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
privateFixedDepositDaofixedDepositDao;
privateEventSendereventSender;
publicFixedDepositServiceImpl(StringconfigFile)throwsException{
ClassPathResourceconfigProperties=newClassPathResource(configFile);
if(configProperties.exists()){
InputStreaminStream=configProperties.getInputStream();
Propertiesproperties=newProperties();
properties.load(inStream);
StringeventSenderClassString=
properties.getProperty(Constants.EVENT_SENDER_CLASS_PROPERTY);
if(eventSenderClassString!=null){
Class<?>eventSenderClass=Class.forName(eventSenderClassString);
eventSender=(EventSender)eventSenderClass.newInstance();
logger.info("CreatedEventSenderclass");
}else{
logger.info("appConfig.propertiesfiledoesn'tcontaintheinformation"+
"aboutEventSenderclass");
}
}
}
publicvoidcreateFixedDeposit(FixedDepositDetailsfixedDepositDetails)throwsException{
.....
eventSender.sendEvent(event);
}
}
The above example listing shows following sequence of actions are performed by the constructor of
FixedDepositServiceImplclass:
·        loads properties from the appConfig.properties file. The configFile constructor argument
representsthelocationoftheappConfig.propertiesfile.
·        obtains property named eventSenderClass (represented by
EVENT_SENDER_CLASS_PROPERTY constant defined in the Constants class) from the
properties loaded fromtheappConfig.propertiesfile. The value of eventSenderClass property is
the fully-qualified name of the EventSender implementation class that FixedDepositServiceImpl
needstouse.ThevalueofeventSenderClasspropertyisstoredintheeventSenderClassStringlocal
variable.
·        creates an instance of the EventSender implementation class whose fully-qualified name is
stored in the eventSenderClassString variable, and stores the newly created instance into an
instance variable named eventSender. The eventSender variable is later used by the
FixedDepositServiceImplscreateFixedDepositmethod(refertothecreateFixedDepositmethodin
theaboveexamplelisting)todirectlyorindirectlystoreeventsinthedatabase.
YoushouldnotethatifapropertynamedeventSenderClassisnotfoundintheappConfig.propertiesfile,
theeventSenderClassStringvariableisnot set. In this case, the FixedDepositServiceImpls constructor
printsthefollowingmessageontheconsole:‘appConfig.propertiesfiledoesn'tcontaintheinformation
aboutEventSenderclass’.
In example listing 4-4, we looked at bean definitions for EventSenderSelectorServiceImpl and
FixedDepositServiceImplclasses, and concluded that the FixedDepositServiceImpl instance is created
beforeEventSenderSelectorServiceImplinstancebecauseSpringcontainerinitializesbeansintheorder
inwhichtheyappearintheapplicationcontextXMLfile.Wesawinexamplelisting4-5thatthecreation
of EventSenderSelectorServiceImpl instance results in writing an eventSenderClass property to the
appConfig.properties file. So, if the FixedDepositServiceImpl instance is created before the
EventSenderSelectorServiceImpl instance, the FixedDepositServiceImpl instance willnot find any
eventSenderClasspropertyintheappConfig.propertiesfile.ThisshowsthattheFixedDepositServiceImpl
class isimplicitly dependent on the EventSenderSelectorServiceImpl class; therefore, the
EventSenderSelectorServiceImplinstancemustbecreatedbeforetheFixedDepositServiceImplinstance.
Howtoaddressimplicitdependencyproblem?
Wecansolvetheimplicitdependencyproblemintwoways:
·        we change the order in which bean definitions for EventSenderSelectorServiceImpl and
FixedDepositServiceImpl classes are defined in the application context XML file. If the bean
definitionfortheEventSenderSelectorServiceImplclassappearsbeforethebeandefinitionforthe
FixedDepositServiceImpl class, the EventSenderSelectorServiceImpl instance will be created
beforetheFixedDepositServiceImplinstance.
·        use <bean> elements depends-on attribute to explicitly specify that the service bean
(corresponding to the FixedDepositServiceImpl class) is dependent on the
eventSenderSelectorServicebean(correspondingtotheEventSenderSelectorServiceImplclass).
Thefollowingexamplelistingshowstheusageof<bean>element’sdepends-onattribute:
Examplelisting4-7–<bean>elementsdepends-onattribute
<beans.....>
<beanid="service"
class="sample.spring.chapter04.bankapp.service.FixedDepositServiceImpl"
depends-on="eventSenderSelectorService">
.....
</bean>
<beanid="eventSenderSelectorService"
class="sample.spring.chapter04.bankapp.service.EventSenderSelectorServiceImpl">
.....
</bean>
</beans>
In the above example listing, the service bean uses depends-on attribute to explicitly specify that it is
dependentontheeventSenderSelectorServicebean.Thedepends-onattributespecifiestheidsornames
of the beans on which the bean is dependent. As the service bean specifies that it is dependent on the
eventSenderSelectorService bean, Spring container creates eventSenderSelectorService bean
(corresponding to the EventSenderSelectorServiceImpl class) instance before service bean
(correspondingtotheFixedDepositServiceImplclass)instance.
NOTE If you execute the main method of the BankApp class of ch04-bankapp-dependencies project,
you’ll find that the FixedDepositServiceImpl instance is created before EventSenderSelectServiceImpl
instance. For this reason, the following message is printed on the console:‘appConfig.properties file
doesn'tcontaintheinformationaboutEventSenderclass’.
Multipleimplicitdependencies
Ifabeanhasmultipleimplicitdependencies,youcanspecifyidsornamesofallthosedependenciesas
thevalueofdepends-onattribute,asshownhere:
Examplelisting4-8–depends-onattributeexample-multipleimplicitdependencies
<beans.....>
<beanid="abean".....depends-on="bBean,cBean">
.....
</bean>
.....
</beans>
Theaboveexamplelistingshowsthatyoucanspecifymultiplebeanidsornamesasthevalueofdepends-
onattribute.
depends-onattributeandbeandefinitioninheritance
It is important to note that the depends-on attribute isnot inherited by child bean definitions. The
following example listing shows anabstract serviceTemplate parent bean definition that uses the
depends-onattributetospecifybaseServicebeanasadependency:
Examplelisting4-9–depends-onattribute–beandefinitioninheritance
<beanid="serviceTemplate"class=".....ServiceTemplate"depends-on="baseService"
abstract="true"/>

<beanid="someService"class=".....SomeServiceImpl"parent="serviceTemplate"/>
<beanid="someOtherService"class=".....SomeOtherServiceImpl"parent="serviceTemplate"/>
<beanid="baseService"class=".....BaseServiceImpl"/>
Intheaboveexamplelisting,someServiceandsomeOtherServicechildbeandefinitionsdon’tinheritthe
depends-on attribute from the serviceTemplate parent bean definition. As the Spring container creates
beansintheorderinwhichtheyaredefinedintheapplicationcontextXMLfile,thebaseServicebeanis
createdafterthecreationofsomeServiceandsomeOtherServicebeans.
Lets now look at how the Spring container manages dependencies of singleton- and prototype-scoped
beans.
4-4Singleton-andprototype-scopedbeansdependencies
Asingleton-scopedbean(anditssingleton-scopeddependencies)iscreatedwhentheApplicationContext
instance is created. And, a prototype-scoped bean (and its prototype-scoped dependencies) is created
eachtimeApplicationContextsgetBeanmethodisinvokedtoobtaintheprototype-scopedbean.
If a singleton-scoped bean is dependent on a prototype-scoped bean, or vice versa, things get a bit
complicated.Forinstance,ifasingleton-scopedbeanisdependentonaprototype-scopedbean,youmight
ask the question whether the Spring container will create the prototype-scoped bean (the dependency)
beforethesingleton-scopedbean(thedependentbean)?ortheSpringcontainerwillcreateandinjectthe
prototype-scopedbeaninstanceonlywhenyoucalltheApplicationContextsgetBeanmethodtoretrieve
the singleton-scoped bean instance? The answers to these questions lies in the way singleton- and
prototype-scopeddependenciesofabeanaremanagedbytheSpringcontainer,asexplainednext.
Singleton-scopedbean’sdependencies
The following example listing shows the singleton-scoped customerRequestService bean of MyBank
application,anditsdependencies:
Examplelisting4-10–applicationContext.xml-DependenciesofcustomerRequestServicebean
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRequestService"
class="sample.spring.chapter04.bankapp.service.CustomerRequestServiceImpl">
<constructor-argname="customerRequestDetails"ref="customerRequestDetails"/>
<constructor-argname="customerRequestDao"ref="customerRequestDao"/>
</bean>
<beanid="customerRequestDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRequestDetails"
scope="prototype"/>
<beanid="customerRequestDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRequestDaoImpl"/>
TheaboveexamplelistingshowsthatthecustomerRequestService (singleton-scoped)beandepends on
customerRequestDetails (prototype-scoped) and customerRequestDao (singleton-scoped) beans.
CustomerRequestServiceobject(representedbythecustomerRequestServicebean)representsaservice
that is invoked when a bank customer creates a new request, like a cheque book request.
CustomerRequestServiceputsthedetailsofthecustomerrequestintoaCustomerRequestDetails object
(represented by the customerRequestDetails bean) and saves it in the data store using
CustomerRequestDaoobject(representedbythecustomerRequestDaobean).
ThefollowingexamplelistingshowsthemainmethodofBankAppclassthatloadsthebeandefinitions
showninexamplelisting4-10:
Examplelisting4-11–BankAppclass
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp
packagesample.spring.chapter04.bankapp;
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[])throwsException{
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
.....
logger.info("BeginningwithaccessingCustomerRequestService");
CustomerRequestServicecustomerRequestService_1
=context.getBean(CustomerRequestService.class);
.....
CustomerRequestServicecustomerRequestService_2
=context.getBean(CustomerRequestService.class);
.....
logger.info("DonewithaccessingCustomerRequestService");
}
}
The above example listing shows that after the ApplicationContext instance is created,
ApplicationContextsgetBeanmethodisinvokedtwicetoobtainreferencetothecustomerRequestService
bean.
IfyouexecutethemainmethodoftheBankAppclass,you’llseethefollowingoutput:
CreatedCustomerRequestDetailsinstance
CreatedCustomerRequestDaoImplinstance
CreatedCustomerRequestServiceImplinstance
.....
BeginningwithaccessingCustomerRequestService
DonewithaccessingCustomerRequestService
TheCreated.....’messagesshownintheaboveoutputareprintedbytheconstructorsoftherespective
bean classes. The above output shows that the customerRequestDetails (prototype-scoped) and
customerRequestDao(singleton-scoped)dependenciesofthecustomerRequestService(singleton-scoped)
bean are created and injected into the customerRequestService instance when the Spring container is
created.AsnoCreated.....’message was printed on the console betweenBeginning.....’ and ‘Done
.....’ messages, no bean instances were created by the Spring container when ApplicationContext’s
getBeanmethodwasinvokedtoretrievethecustomerRequestServicebean.
Figure4-2showsthesequencediagramthatdepictsthesequenceofeventsthatoccurwhenBankApp’s
main method (refer example listing 4-11) is executed. Figure 4-2 shows that when Spring container is
created, the customerRequestDetails (prototype-scoped) and customerRequestDao (singleton-scoped)
beansarefirstcreated,followedbycreationofcustomerRequestService(singleton-scoped).Constructor-
based DI is used to inject the customerRequestDetails and customerRequestDao beans into the
customerRequestServicebean.Asasingleton-scopedbeaniscreatedonlyoncebytheSpringcontainer,
theSpringcontainerhasonlyoneopportunitytoinjectcustomerRequestServicebeansdependencies.For
thisreason,theSpringcontainerinjectsprototype-scopedcustomerRequestDetailsbeaninstanceintothe
customerRequestService beanonly once. The implication of this behavior is that the
customerRequestServicebeanendsupholdingreferencetothesamecustomerRequestDetailsbeanduring
itslifetime.
Figure 4-2 -The sequence of events that occur when the Spring container is created and the
customerRequestServicebeanisretrievedfromtheSpringcontainer
It is important to note that even if setter-based DI was used to inject the prototype-scoped
customerRequestDetails dependency of the customerRequestService bean, the Spring container would
have called the setter method onlyonce during the lifetime of the customerRequestService bean. This
meansthatirrespectiveofwhethersetter-orconstructor-basedDIisused,asingletonbeaniscreatedand
configuredonlyonceduringitslifetime.
Now,oncetheSpringcontaineriscreated,anyrequestforthesingleton-scopedcustomerRequestService
beanreturnsthesamecachedinstanceofthecustomerRequestServicebean.Forthisreason,no‘Created
.....’messagewaswrittenouttotheconsolebetweenBeginning.....’andDone.....’messageswhenwe
executedBankApp’smainmethod(referexamplelisting4-11).
As the singleton-scoped customerRequestService bean always holds reference to the same prototype-
scopedcustomerRequestDetailsbean, itmay adversely affectthe behavior ofMyBank application.For
instance, if multiple customers simultaneously submit request to the CustomerRequestServiceImpl
instance,alltherequestswillresultinmodifyingthesameinstanceoftheCustomerRequestDetailsobject
heldbytheCustomerRequestService.Ideally,CustomerRequestServiceImplshouldcreateanewinstance
ofCustomerRequestDetailsobjectoneveryrequest.Insection4-5,we’llseewhatmodificationsweneed
tomaketothebeanclassofasingleton-scopedbeansothatitcanretrieveanewinstanceofaprototype-
scopedbeanoneverymethodcall.
LetsnowlookathowtheSpringcontainermanagesprototype-andsingleton-scopeddependenciesofa
prototype-scopedbean.
Prototype-scopedbean’sdependencies
In MyBank, a customer registers with the MyBank application by following a sequence of steps. For
instance, a customer first enters personal information and his account details, and if the MyBank
application finds a matching record, the customer is asked for his debit card details. The
CustomerRegistrationServiceImplclassofMyBankapplicationcontainsthenecessarybusinesslogicto
registercustomers.AsthecustomersfollowasequenceofstepstoregisterwiththeMyBankapplication,
theCustomerRegistrationServiceImplobjectmaintainsconversationalstatebetweenmethodcalls.
The following example listing shows the prototype-scoped customerRegistrationService bean
(representingtheCustomerRegistrationServiceImplclass)ofMyBankapplication,anditsdependencies:
Examplelisting4-12–applicationContext.xml-customerRegistrationServicebeananditsdependencies
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRegistrationService"
class="sample.spring.chapter04.bankapp.service.CustomerRegistrationServiceImpl"
scope="prototype">
<constructor-argname="customerRegistrationDetails"ref="customerRegistrationDetails"/>
<constructor-argname="customerRegistrationDao"ref="customerRegistrationDao"/>
</bean>
<beanid="customerRegistrationDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRegistrationDetails"
scope="prototype"/>
<beanid="customerRegistrationDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRegistrationDaoImpl"/>
TheaboveexamplelistingshowsthatthecustomerRegistrationService(prototype-scoped)beandepends
on customerRegistrationDetails (prototype-scoped) and customerRegistrationDao (singleton-scoped)
beans.
CustomerRegistrationServiceImpl instance maintains progress of the registration process, and stores
information provided by the customer during the registration process in a CustomerRegistrationDetails
object(representedbythecustomerRegistrationDetailsbean).AsbothCustomerRegistrationServiceImpl
and CustomerRegistrationDetails objects are stateful in nature, both customerRegistrationService and
customerRegistrationDetailsbeansaredefinedasprototype-scopedbeans.
ThefollowingexamplelistingshowsthemainmethodofBankAppclassthatloadscustomerregistration
relatedbeans(referexamplelisting4-12)andperformsregistrationsfor2customers:
Examplelisting4-13–BankAppclass
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp
packagesample.spring.chapter04.bankapp;
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[])throwsException{
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
.....
logger.info("BeginningwithaccessingCustomerRegistrationService");
CustomerRegistrationServicecustomerRegistrationService_1=context
.getBean(CustomerRegistrationService.class);
customerRegistrationService_1.setAccountNumber("account_1");
customerRegistrationService_1.setAddress("address_1");
customerRegistrationService_1.setDebitCardNumber("debitCardNumber_1");
customerRegistrationService_1.register();
logger.info("registeredcustomerwithidaccount_1");
CustomerRegistrationServicecustomerRegistrationService_2=context
.getBean(CustomerRegistrationService.class);

.....
logger.info("registeredcustomerwithidaccount_2");
logger.info("DonewithaccessingCustomerRegistrationService");
}
}
The above example listing shows that the BankApp’smain method calls ApplicationContexts getBean
method twice to obtain reference to customerRegistrationService bean. Once the
customerRegistrationService bean instance is retrieved, the setAccountNumber, setAddress,
setDebitCardNumber and register methods are invoked on it. If you execute BankApp’s main method,
you’llseethefollowingoutputontheconsole:
CreatedCustomerRegistrationDaoImplinstance
.....
BeginningwithaccessingCustomerRegistrationService
CreatedCustomerRegistrationDetailsinstance
CreatedCustomerRegistrationServiceImplinstance
registeredcustomerwithidaccount_1
CreatedCustomerRegistrationDetailsinstance
CreatedCustomerRegistrationServiceImplinstance
registeredcustomerwithidaccount_2
DonewithaccessingCustomerRegistrationService
TheCreated.....’messagesshownintheaboveoutputareprintedbytheconstructorsoftherespective
bean classes. The above output shows that the singleton-scoped customerRegistrationDao bean
(representingtheCustomerRegistrationDaoImplclass)iscreatedonlyoncewhentheApplicationContext
instance is created. TheCreated.....’ messages between‘Beginning.....’ and Done.....’ messages
indicatethateachtimeApplicationContextsgetBeanmethod isinvokedto obtaintheprototype-scoped
customerRegistrationService bean, a new instance of the customerRegistrationService bean and its
prototype-scopeddependency(thecustomerRegistrationDetailsbean)iscreatedbytheSpringcontainer.
Figure4-3showsthesequencediagramthatdepictsthesequenceofeventsthatoccurwhenBankApp’s
main method (refer example listing 4-13) is executed. The figure shows that the singleton-scoped
customerRegistrationDaobeaniscreatedonlyoncewhenApplicationContextinstanceiscreated.When
theprototype-scopedcustomerRegistrationServicebeanisrequestedfromtheSpringcontainer,theSpring
container first creates an instance of customerRegistrationDetails bean (which is the prototype-scoped
dependency of the customerRegistrationService bean), followed by the creation of the
customerRegistrationServicebean.Thisshowsthatifaprototype-scopedbeanXisdependentonanother
prototype-scopedbeanY,SpringcontainerwillcreateanewinstanceofXandYeachtimeyourequest
beanXfromtheSpringcontainer.
Figure 4-3 – The sequence of events that occur when the Spring container is created and the
customerRegistrationServicebeanisretrievedfromtheSpringcontainer
Earlierinthissection,wesawthatifasingleton-scopedbeanisdependentonaprototype-scopedbean,
then throughout its lifetime the singleton-scoped bean is associated with the same instance of the
prototype-scopedbean.Letsnowlookatdifferentwaysinwhichasingleton-scopedbeancanretrievea
newinstanceofaprototype-scopedbeanfromtheSpringcontainer.
4-5Obtainingnewinstancesofprototypebeansinsidesingletonbeans
In the previous section, we saw that the prototype-scoped dependency of a singleton-scoped bean is
injectedatthetimeofcreationofthesingleton-scopedbean(referfigure4-2).Springcontainercreates
instanceofasingleton-scopedbeanonlyonce;therefore,thesingleton-scopedbeanholdsreferencetothe
sameprototype-scopedbeaninstanceduringitslifetime.Asingleton-scopedbean’smethodscanretrieve
a new instance of their prototype-scoped dependency from the Spring container using any one of the
followingapproaches:
·makethesingleton-scopedbeansclassimplementSpringsApplicationContextAwareinterface
·usethe<lookup-method>elementofSpringsbeansschema
·usethe<replaced-method>elementofSpringsbeansschema
NOTEItispossibletousethenewkeywordtocreateaninstanceoftheprototype-scopedbeansclassin
asingleton-scopedbeansmethodanduseit.Astheresponsibilityofcreatingabeaninstanceiswiththe
Springcontainer,weshouldnotattempttodirectlycreateabeaninstanceusingthenewkeyword.
IMPORTchapter4/ch04-bankapp-context-aware(Thisprojectshowsascenarioinwhichasingleton-
scopedbeanimplementsSpringsApplicationContextAwareinterfacetoobtaininstancesofaprototype-
scopedbeanfromtheSpringcontainer.Toruntheapplication,executethemainmethodoftheBankApp
classofthisproject)
LetsfirstbeginbylookingattheApplicationContextAwareinterface.
ApplicationContextAwareinterface
Springs ApplicationContextAware interface is implemented by beans that require access to the
ApplicationContext instance in which they are running. ApplicationContextAware interface defines a
single method, setApplicationContext, which provides the implementing beans with an instance of the
ApplicationContextobject.
ApplicationContextAwareinterfaceisalifecycleinterface,whichmeansthattheSpringcontainercalls
thebeansimplementingtheApplicationContextAwareinterfaceatappropriatetimesduringtheirlifetime.
Forinstance,ApplicationContextAware’ssetApplicationContextmethodiscalledbytheSpringcontainer
afterthebeaninstanceiscreatedbutbeforethebeaninstanceiscompletelyinitialized.Abeaninstanceis
consideredcompletelyinitializedonlyafteritsinitializationmethod(refersection5-2ofchapter5)is
calledbytheSpringcontainer.Itisimportanttonotethatafterabeaninstanceiscompletelyinitialized,it
is injected into the dependent bean instances by the Spring container. In chapter 5, we’ll look at some
morelifecycleinterfacesinSpring.
AbeanthatimplementstheApplicationContextAwareinterfacecanaccessotherbeansregisteredwiththe
ApplicationContextinstancebycallingApplicationContextsgetBeanmethod.Thismeansthatifthebean
class of a singleton-scoped bean implements ApplicationContextAware interface, it can fetch a new
instanceofaprototype-scopedbeanfromtheSpringcontainerbycallingApplicationContextsgetBean
method.Asthesingleton-scopedbeanexplicitlyobtainsitsprototype-scopeddependencyfromtheSpring
containerbycallingApplicationContext’sgetBeanmethod,youdontneedtodefinetheprototype-scoped
beanasadependencyofthesingleton-scopedbeanintheapplicationcontextXMLfile.
ThefollowingexamplelistingshowstheCustomerRequestServiceImplclassthatneedsanewinstanceof
CustomerRequestDetails object each time CustomerRequestServiceImpls submitRequest method is
called:
Examplelisting4-14–CustomerRequestServiceImplclass
Project–ch04-bankapp-context-aware
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importsample.spring.chapter04.bankapp.dao.CustomerRequestDao;
importsample.spring.chapter04.bankapp.domain.CustomerRequestDetails;
publicclassCustomerRequestServiceImplimplementsCustomerRequestService{
privateCustomerRequestDetailscustomerRequestDetails;
privateCustomerRequestDaocustomerRequestDao;
@ConstructorProperties({"customerRequestDetails","customerRequestDao"})
publicCustomerRequestServiceImpl(CustomerRequestDetailscustomerRequestDetails,
CustomerRequestDaocustomerRequestDao){
this.customerRequestDetails=customerRequestDetails;
this.customerRequestDao=customerRequestDao;
}
publicvoidsubmitRequest(StringrequestType,StringrequestDescription){
//--populateCustomerRequestDetailsobjectandsaveit
customerRequestDetails.setType(requestType);
customerRequestDetails.setDescription(requestDescription);
customerRequestDao.submitRequest(customerRequestDetails);
}
}
TheaboveexamplelistingshowsthattheCustomerRequestDetailsandCustomerRequestDaoobjectsare
passedasargumentstotheCustomerRequestServiceImplclasssconstructor.ThesubmitRequestmethod
populates the CustomerRequestDetails instance and saves it into the database by calling
CustomerRequestDao’ssubmitRequest method.Ifmultiplecustomers simultaneouslysubmitrequest, the
submitRequest method will end up modifying the same instance of the CustomerRequestDetails object,
resulting in undesired behavior of MyBank application. To address this issue, the submitRequest must
obtainanewinstanceoftheCustomerRequestDetailsobjectfromtheSpringcontaineroneachinvocation.
The following example listing shows the CustomerRequestServiceContextAwareImpl class (a modified
versionofCustomerRequestServiceImplclassthatwesawinexamplelisting4-14)thatimplementsthe
ApplicationContextAwareinterface:
Example listing 4-15 – CustomerRequestServiceContextAwareImpl class that implements Springs
ApplicationContextAwareinterface
Project–ch04-bankapp-context-aware
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ApplicationContextAware;
publicclassCustomerRequestServiceContextAwareImplimplements
CustomerRequestService,ApplicationContextAware{

privateCustomerRequestDaocustomerRequestDao;
privateApplicationContextapplicationContext;
@ConstructorProperties({"customerRequestDao"})
publicCustomerRequestServiceContextAwareImpl(CustomerRequestDaocustomerRequestDao)
{
this.customerRequestDao=customerRequestDao;
}
publicvoidsetApplicationContext(ApplicationContextapplicationContext)
throwsBeansException{
this.applicationContext=applicationContext;
}

publicvoidsubmitRequest(StringrequestType,StringrequestDescription){
CustomerRequestDetailscustomerRequestDetails=applicationContext
.getBean(CustomerRequestDetails.class);
customerRequestDetails.setType(requestType);
customerRequestDetails.setDescription(requestDescription);
customerRequestDao.submitRequest(customerRequestDetails);
}
}
In the above example listing, setApplicationContext method provides
CustomerRequestServiceContextAwareImpl with an instance of ApplicationContext object. The
ApplicationContext instance is later used by the submitRequest method to obtain an instance of
CustomerRequestDetailsobjectfromtheSpringcontainer.
As the CustomerRequestServiceContextAwareImpl class explicitly obtains CustomerRequestDetails
object from the Spring container, youdon’t need to use Springs DI mechanism to inject
CustomerRequestDetails instance intotheCustomerRequestServiceContextAwareImpl instance. For this
reason, CustomerRequestServiceContextAwareImpl classs constructor (refer example listing 4-15)
doesntspecifyCustomerRequestDetailsobjectasanargument.Ifyounowgotoch04-bankapp-context-
awareprojectandexecuteBankApp’smainmethod,youllfindthatoneachinvocationofsubmitRequest
methodanewinstanceofCustomerRequestDetailsobjectisfetchedfromtheSpringcontainer.
InthecontextofMyBank,wesawthattheApplicationContextAwareinterfaceisusefulifabeanrequires
access to other beans. The downside of implementing the ApplicationContextAware interface is that it
couples your bean class to Spring Framework. You can avoid coupling your bean classes with Spring
FrameworkandstillaccessotherbeansfromtheSpringcontainerbyusingmethodinjectiontechniques
offeredby<lookup-method>and<replaced-method>elementsofSpringsbeansschema.
Letsfirstlookatthe<lookup-method>element.
IMPORT chapter 4/ch04-bankapp-lookup-method (This project shows the MyBank application that
uses<lookup-method>elementofSpringsbeansschema.Toruntheapplication,executethemainmethod
oftheBankAppclassofthisproject)
<lookup-method>element
Ifabeanclassdefinesabeanlookupmethodwhosereturntyperepresentsabean,the<lookup-method>
element instructs the Spring container to provide implementation for this method. The method
implementationprovidedbytheSpringcontainerisresponsibleforretrievingthebeaninstancefromthe
Springcontainerandreturningit.
The <lookup-method> element’s bean attribute specifies the name of the bean to be looked-up and
returnedbythemethodimplementation,andthenameattribute specifies the nameof themethodwhose
implementation is to be provided by the Spring container. It is important to note that the bean lookup
methoddefinedbythebeanclasscanbeanabstractoraconcretemethod.
NOTETheuseof<lookup-method>elementtoinstructtheSpringcontainertoprovideimplementation
forabeanlookupmethodisreferredtoasaMethodInjectiontechinique’becausethe<lookup-method>
elementinjectsabeanlookupmethodimplementationintothebeanclass.
The following example listing shows CustomerRequestServiceImpls getCustomerRequestDetails
abstractmethodthatreturnsaninstanceofCustomerRequestDetailsinstance:
Examplelisting4-16–CustomerRequestServiceImplclass–definingabeanlookupmethod
Project–ch04-bankapp-lookup-method
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
publicabstractclassCustomerRequestServiceImplimplementsCustomerRequestService{
privateCustomerRequestDaocustomerRequestDao;
@ConstructorProperties({"customerRequestDao"})
publicCustomerRequestServiceImpl(CustomerRequestDaocustomerRequestDao){
this.customerRequestDao=customerRequestDao;
}
publicabstractCustomerRequestDetailsgetCustomerRequestDetails();
@Override
publicvoidsubmitRequest(StringrequestType,StringrequestDescription){
//--populateCustomerRequestDetailsobjectandsaveit
CustomerRequestDetailscustomerRequestDetails=getCustomerRequestDetails();
.....
}
}
The above example listing shows that the CustomerRequestServiceImpl class is defined as abstract
becauseitcontainsanabstractbeanlookupmethod,getCustomerRequestDetails.Insteadofabstract,we
could have very well defined the getCustomerRequestDetails method as a concrete method. The
submitRequest method invokes the getCustomerRequestDetails method to access a
CustomerRequestDetailsinstance.
The following example listing shows bean definitions for CustomerRequestServiceImpl and
CustomerRequestDetailsclasses:
Examplelisting4-17–applicationContext.xml-<lookup-method>elementusage
Project–ch04-bankapp-lookup-method
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRequestService"
class="sample.spring.chapter04.bankapp.service.CustomerRequestServiceImpl">
<constructor-argname="customerRequestDao"ref="customerRequestDao"/>
<lookup-methodbean="customerRequestDetails"name="getCustomerRequestDetails"/>
</bean>
<beanid="customerRequestDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRequestDetails"
scope="prototype"/>
The above example listing shows that the bean definition for the CustomerRequestServiceImpl class
contains a <lookup-method> element. The value of <lookup-method> elements name attribute is
getCustomerRequestDetails, which instructs the Spring container to provide implementation for the
getCustomerRequestDetailslookupmethod(referexamplelisting4-16)ofCustomerRequestServiceImpl
class.Thevalueof<lookup-method> elements beanattributeiscustomerRequestDetails, which means
that the implementation of getCustomerRequestDetails method retrieves a bean with id (or name) as
customerRequestDetails from the Spring container and returns it to the calling method. As the
customerRequestDetails bean represents a CustomerRequestDetails object (refer to the
customerRequestDetails bean definition in example listing 4-17), the implementation of
getCustomerRequestDetailsmethodreturnsaCustomerRequestDetailsobject.
In example listing 4-16, the CustomerRequestServices submitRequest method invokes the
getCustomerRequestDetails bean lookup method to obtain a CustomerRequestDetails instance. As
CustomerRequestDetailsclassisrepresentedasaprototype-scopedbeanintheapplicationcontextXML
file (refer example listing4-17), each invocation of thesubmitRequest methodresultsin retrieval ofa
newinstanceofCustomerRequestDetailsobjectfromtheSpringcontainer.
To check that the <lookup-method> element provides correct implementation for the
CustomerRequestServices getCustomerRequestDetails bean lookup method, the main method of
BankAppclassobtainsaninstanceofCustomerRequestServicefromtheSpringcontainerandinvokesits
submitRequestmethodmultipletimes.IfeachinvocationofthesubmitRequestmethodresultsinretrieval
of a fresh instance of CustomerRequestDetails object from the Spring container, then it means that the
<lookup-method> element provides correct implementation for the CustomerRequestService’s
getCustomerRequestDetailsmethod.
ThefollowingexamplelistingshowstheBankApp’smainmethodthatinvokesCustomerRequestServices
submitRequestmethodmultipletimes:
Examplelisting4-18–BankAppclass
Project–ch04-bankapp-lookup-method
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp
packagesample.spring.chapter04.bankapp;
.....
publicclassBankApp{
privatestaticLoggerlogger=Logger.getLogger(BankApp.class);
publicstaticvoidmain(Stringargs[])throwsException{
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
.....
logger.info("BeginningwithaccessingCustomerRequestService");
CustomerRequestServicecustomerRequestService_1=context
.getBean(CustomerRequestService.class);
customerRequestService_1.submitRequest("checkBookRequest",
"Requesttosenda50-leafcheckbook");
customerRequestService_1.submitRequest("checkBookRequest",
"Requesttosenda100-leafcheckbook");
.....
logger.info("DonewithaccessingCustomerRequestService");
}
}
IfyouexecutetheBankApp’smainmethod,you’llseethefollowingoutputontheconsole:
BeginningwithaccessingCustomerRequestService
CreatedCustomerRequestDetailsinstance
CreatedCustomerRequestDetailsinstance
.....
DonewithaccessingCustomerRequestService
TheCreated.....’messagesshownintheaboveoutputareprintedbytheconstructorsoftherespective
beanclasses.TheaboveoutputshowsthateachinvocationofCustomerRequestServicessubmitRequest
methodresultedinretrievalofanewCustomerRequestDetailsinstancefromtheSpringcontainer.
AstheimplementationofthebeanlookupmethodisprovidedbytheSpringcontainer,somerestrictions
applytothesignatureofthebeanlookupmethods.Forinstance,thebeanlookupmethodmustbedefined
aspublicorprotected,anditmustnotacceptanyarguments.Asthebeanclasscontainingthebeanlookup
methodissubclassedatruntimebytheSpringcontainertoprovidetheimplementationforthebeanlookup
method,thebeanclassandthebeanlookupmethodmustnotbedefinedasfinal.
NOTE As the bean class containing the bean lookup method needs to be subclassed at runtime by the
Springcontainertoprovideimplementationforthebeanlookupmethod,theSpringcontainerusesCGLIB
(http://cglib.sourceforge.net/)librarytoperformsubclassingofthebeanclass.StartingwithSpring3.2,
the CGLIB classes are packaged within the spring-core JAR file itself; therefore, you dont need to
explicitlyspecifythatyourprojectisdependentonCGLIBJARfile.
The<lookup-method> element provides a method injection technique in which a bean class defines a
beanlookupmethodwhoseimplementationisprovidedbytheSpringcontainer.Insteadofusing<lookup-
method> element, you can consider using <replaced-method> element of Springs beans schema to
performmethodinjection.
IMPORTchapter4/ch04-bankapp-replaced-method(ThisprojectshowstheMyBankapplicationthat
uses <replaced-method> element of Springs beans schema. To run the application, execute the main
methodoftheBankAppclassofthisproject)
<replaced-method>element
The<replaced-method>elementallowsyoutoreplaceanyarbitrarymethodinabeanclass
with a different implementation. The following example listing shows the
CustomerRequestServiceImpl class that we’ll be using as an example to demonstrate use of
<replaced-method>element:
Examplelisting4-19–CustomerRequestServiceImplclass
Project–ch04-bankapp-replaced-method
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
.....
publicclassCustomerRequestServiceImplimplementsCustomerRequestService{
privateCustomerRequestDaocustomerRequestDao;
.....
publicObjectgetMyBean(StringbeanName){
returnnull;
}
@Override
publicvoidsubmitRequest(StringrequestType,StringrequestDescription){
//--populateCustomerRequestDetailsobjectandsaveit
CustomerRequestDetailscustomerRequestDetails=
(CustomerRequestDetails)getMyBean("customerRequestDetails");
customerRequestDetails.setType(requestType);
customerRequestDetails.setDescription(requestDescription);
customerRequestDao.submitRequest(customerRequestDetails);
}
}
The above example listing shows that the CustomerRequestServiceImpl class defines a getMyBean
method.ThegetMyBeanmethodacceptsnameofabeanasanargument,andinsteadofreturningthebean
instance corresponding to the bean name argument, the getMyBean method returns null. The
submitRequestmethodpassescustomerRequestDetailsstringasargumenttothegetMyBeanmethodand
assumes that the getMyBean method returns an instance of customerRequestDetails bean. Using
<replaced-method>element,youcanoverridethegetMyBeanmethodwithamethodthatreturnsthebean
instancecorrespondingtothebeannameargument.
The <replaced-method> element needs information about the overridden method (which is
CustomerRequestServiceImpl getMyBean method in our example scenario) and theoverriding method.
TheoverridingmethodisprovidedbytheclassthatimplementsSpringsMethodReplacerinterface.The
following example listing shows MyMethodReplacer class that implements the MethodReplacer
interface:
Examplelisting4-20–MyMethodReplacerclass
Project–ch04-bankapp-replaced-method
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importorg.springframework.beans.factory.support.MethodReplacer;
importorg.springframework.context.ApplicationContextAware;
publicclassMyMethodReplacerimplementsMethodReplacer,ApplicationContextAware{
privateApplicationContextapplicationContext;
@Override
publicObjectreimplement(Objectobj,Methodmethod,Object[]args)throwsThrowable{
returnapplicationContext.getBean((String)args[0]);
}
@Override
publicvoidsetApplicationContext(ApplicationContextapplicationContext)
throwsBeansException{
this.applicationContext=applicationContext;
}
}
SpringsMethodReplacerinterfacedefinesareimplementmethodwhoseimplementationisprovidedby
the MyMethodReplacer class. The reimplement method represents the overriding method.
MyMethodReplacer class also implements Springs ApplicationContextAware interface so that the
reimplement method can access the ApplicationContext instance. The reimplement method uses the
ApplicationContextsgetBeanmethodtoretrievebeansfromtheSpringcontainer.
Thereimplementmethodacceptsthefollowingarguments:
·Objectobj–identifiestheobjectwhosemethodweareoverriding.Inourexamplescenario,the
objobjectistheCustomerRequestServiceImplobject.
·        Methodmethod – identifies the bean class’s method that is overridden by the reimplement
method.Inourexamplescenario,thisisCustomerRequestServiceImplsgetMyBeanmethod.
·Object[]args–identifiesargumentspassedtothemethodthatweareoverriding.Inourexample
scenario,args represents the arguments passed to the CustomerRequestServiceImpls getMyBean
method.Inexamplelisting4-20,args[0]inthereimplementmethodrefersthebeannameargument
passedtotheCustomerRequestServiceImplsgetMyBeanmethod.
IfyounowlookatMyMethodReplacersreimplementmethodinexamplelisting4-20,youcaninferthatit
usesargs argument to first obtain bean name passed to the CustomerRequestServiceImpls getMyBean
method,andthencallsApplicationContext’sgetBeanmethodtoobtainthecorrespondingbeaninstance.
As MyMethodReplacers reimplement method overrides CustomerRequestServiceImpls getMyBean
method,calltogetMyBeanmethod at runtime returns thebeaninstance whose name was passed tothe
getMyBeanmethod.
The <replaced-method> element informs the Spring container that MyMethodReplacers reimplement
methodoverridesCustomerRequestServiceImplsgetMyBeanmethod,asshowninthefollowingexample
listing:
Examplelisting4-21–applicationContext.xml-<replaced-method>elementusage
Project–ch04-bankapp-replaced-method
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRequestService"
class="sample.spring.chapter04.bankapp.service.CustomerRequestServiceImpl">
<constructor-argname="customerRequestDao"ref="customerRequestDao"/>
<replaced-methodname="getMyBean"replacer="methodReplacer"/>
</bean>
<beanid="methodReplacer"
class="sample.spring.chapter04.bankapp.service.MyMethodReplacer"/>
The above example listing shows bean definitions for MyMethodReplacer and
CustomerRequestServiceImplclasses.The<replace-method>elementsnameattributespecifiesnameof
the method that you want to override, and the replacer attribute specifies reference to the bean that
implementstheMethodReplacerinterface.Themethodspecifiedbythenameattributeisoverriddenby
thereimplementmethodofthebeanreferencedbythereplacerattribute.
As in case of <lookup-method> element, the main method of the BankApp class of ch04-bankapp-
replaced-methodproject validates whether or not the <replaced-method> element overrides the
CustomerRequestServices getMyBean method with the MyMethodReplacers reimplement method.
BankAppclassofch04-bankapp-replaced-methodprojectissameastheonewesawinexamplelisting
4-18 for ch04-bankapp-lookup-methodproject. If you execute the main method of the BankApp class,
you’llfindthat<replaced-method>elementoverridesCustomerRequestServiceImplsgetMyBeanmethod
withMyMethodReplacersreimplement method; therefore, a fresh instance of CustomerRequestDetails
instanceisretrievedfromtheSpringcontainereachtimeCustomerRequestServiceImplssubmitRequest
method(referexamplelisting4-19)isinvoked.
It is important to note that you can use <replaced-method> element to replace an abstract or concrete
method of a bean class with a different method implementation. For instance, we could have defined
getMyBeanmethodasanabstractmethodandusedthe<replaced-method>elementinthesamewayas
describedinthissection.
NOTEAsthebeanclassneedstobesubclassedatruntimebytheSpringcontainertoreplaceabean
methodwithadifferentmethod,theSpringcontainerusesCGLIB(http://cglib.sourceforge.net/)libraryto
performsubclassingofthebeanclass.StartingwithSpring3.2,theCGLIBclassesarepackagedwithin
thespring-coreJARfileitself;therefore,youdon’tneedtoexplicitlyspecifythatyourprojectis
dependentonCGLIBJARfile.
Letsnowlookathow<replaced-method>elementuniquelyidentifiesthebeanmethodtobeoverridden.
Uniquelyidentifyingthebeanmethod
You may come across scenarios in which the bean method that you want to replace using <replaced-
method>elementcan’tbeuniquelyidentifiedbyname.Forinstance,thefollowingexamplelistingshows
abeanclassthatcontainsoverloadedperformmethods:
Examplelisting4-22–Overloadedmethodsinabeanclass
publicclassMyBean{
publicvoidperform(Stringtask1,Stringtask2){.....}
publicvoidperform(Stringtask){.....}
publicvoidperform(my.Tasktask){.....}
}
In theabove examplelisting, theMyBean class contains multiplemethods named perform. To uniquely
identifythebeanmethodtobeoverridden,the<replaced-method>elementuses<arg-type>sub-elements
to specify method argument types. For instance, the following example listing shows how <replaced-
method>elementspecifiesthattheperform(String,String)methodofMyBeanclassshouldbereplaced:
Examplelisting4-23–<replaced-method>elementwith<arg-type>sub-element
<beanid="mybean"class="MyBean">
<replaced-methodname="perform"replacer=".....">
<arg-type>java.lang.String</arg-type>
<arg-type>java.lang.String</arg-type>
</replaced-method>
</bean>
Insteadofusingthefully-qualifiednameasthevalueof<arg-type>element,youcanuseasubstringofthe
fully-qualifiednameasthevalue.Forinstance,insteadofusingjava.lang.String,youcanspecifyStror
Stringasthevalueof<arg-type>elementintheaboveexamplelisting.
LetsnowlookatSpringsautowiringfeaturethatsavesyoutheeffortofspecifyingbeandependenciesin
theapplicationcontextXMLfile.
4-6Autowiringdependencies
In Spring, you have the option to either explicitly specify bean dependencies using <property> and
<constructor-arg>elementsorletSpringautomaticallyresolvebeandependencies.Theprocessinwhich
dependenciesareautomaticallyresolvedbySpringisreferredtoas‘autowiring.
IMPORTchapter4/ch04-bankapp-autowiring(This project shows the MyBank application that uses
Springsautowiringfeaturefordependencyinjection.Toruntheapplication,executethemainmethodof
theBankAppclassofthisproject)
The<bean>element’sautowireattributespecifieshowabeansdependenciesareautomaticallyresolved
by Spring. The autowire attribute can take any one of the following values: default, byName, byType,
constructorandno.Let’snowlookateachoftheseattributevaluesindetail.
NOTEYoushouldnotethatthe<bean>element’sautowireattributeisnotinheritedbychildbean
definitions.
byType
Ifyouspecifyautowireattribute’svalueasbyType,Springautowiresbeanpropertiesbasedontheirtype.
For instance, if a bean A defines a property of type X, Spring finds a bean of type X in the
ApplicationContextandinjectsitintobeanA.LetslookatanexampleusageofbyTypeautowiringinthe
MyBankapplication.
ThefollowingexamplelistingshowstheMyBankapplicationsCustomerRegistrationServiceImplclass:
Examplelisting4-24–CustomerRegistrationServiceImplclass
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
publicclassCustomerRegistrationServiceImplimplementsCustomerRegistrationService{
privateCustomerRegistrationDetailscustomerRegistrationDetails;
privateCustomerRegistrationDaocustomerRegistrationDao;
....
publicvoidsetCustomerRegistrationDetails(
CustomerRegistrationDetailscustomerRegistrationDetails){
this.customerRegistrationDetails=customerRegistrationDetails;
}
publicvoidsetCustomerRegistrationDao(
CustomerRegistrationDaocustomerRegistrationDao){
this.customerRegistrationDao=customerRegistrationDao;
}
.....
}
The above example listing shows that the CustomerRegistrationServiceImpl class defines properties
namedcustomerRegistrationDetails(oftypeCustomerRegistrationDetails)andcustomerRegistrationDao
(of type CustomerRegistrationDao). This means that the CustomerRegistrationDetails and
CustomerRegistrationDaoobjectsaredependenciesofCustomerRegistrationServiceImplobject.
The following example listing shows bean definitions for CustomerRegistrationServiceImpl,
CustomerRegistrationDetails and CustomerRegistrationDaoImpl (an implementation of
CustomerRegistrationDaointerface)classes:
Examplelisting4-25–applicationContext.xml-autowiringbyTypeconfiguration
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRegistrationService"
class="sample.spring.chapter04.bankapp.service.CustomerRegistrationServiceImpl"
scope="prototype"autowire="byType"/>
<beanid="customerRegistrationDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRegistrationDetails"
scope="prototype"/>
<beanid="customerRegistrationDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRegistrationDaoImpl"/>
Intheaboveexamplelisting,thecustomerRegistrationServicebeandefinitiondoesn’tcontain<property>
elementsforsettingcustomerRegistrationDetailsandcustomerRegistrationDaoproperties(referexample
listing4-24).Instead,the<bean>elementspecifiesautowireattribute’svalueasbyTypetoinstructSpring
to automatically resolve dependencies of the customerRegistrationService bean based on theirtype.
Spring looks for beans of types CustomerRequestDetails and CustomerRegistrationDao in the
ApplicationContext, and injects them into the customerRegistrationService bean. As
customerRegistrationDetails and customerRegistrationDao beans represent beans of types
CustomerRegistrationDetails and CustomerRegistrationDao, the Spring container injects
customerRegistrationDetailsandcustomerRegistrationDaobeansintocustomerRegistrationServicebean.
It may happen that Spring doesnt find any bean registered with the ApplicationContext whose type
matches the property type. In such cases, no exception is thrown and the bean property is not set. For
instance, if a bean defines a property x of type Y, and there is no bean of type Y registered with the
ApplicationContext instance, the property x is not set. If Spring finds multiple beans in the
ApplicationContextthatmatchthepropertytype,anexceptionisthrown.Insuchcases,insteadofusing
autowiringfeature,use<property>elementstoexplicitlyidentifybeandependenciesorsetabeanasthe
primarycandidateforautowiringbysettingthevalueofprimaryattributeof<bean>elementtotrue.
constructor
If you specify autowire attribute’s value as constructor, Spring autowires bean classs constructor
argumentsbasedontheirtype.Forinstance,ifbeanAsconstructoracceptsargumentsoftypeXandY,
SpringfindsbeansoftypesXandYintheApplicationContextandinjectsthemasargumentstobeanA’s
constructor.Let’slookatanexampleusageofconstructorautowiringintheMyBankapplication.
ThefollowingexamplelistingshowstheMyBankapplicationsCustomerRequestServiceImplclass:
Examplelisting4-26–CustomerRequestServiceImplclass
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
publicclassCustomerRequestServiceImplimplementsCustomerRequestService{
privateCustomerRequestDetailscustomerRequestDetails;
privateCustomerRequestDaocustomerRequestDao;
@ConstructorProperties({"customerRequestDetails","customerRequestDao"})
publicCustomerRequestServiceImpl(
CustomerRequestDetailscustomerRequestDetails,
CustomerRequestDaocustomerRequestDao){
this.customerRequestDetails=customerRequestDetails;
this.customerRequestDao=customerRequestDao;
}
.....
}
The CustomerRequestServiceImpl class defines a constructor that accepts arguments of type
CustomerRequestDetailsandCustomerRequestDao.
The following example listing shows bean definitions for CustomerRequestServiceImpl,
CustomerRequestDetails and CustomerRequestDaoImpl (an implementation of CustomerRequestDao
interface)classes:
Examplelisting4-27–applicationContext.xml-constructorautowiring
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRequestService"
class="sample.spring.chapter04.bankapp.service.CustomerRequestServiceImpl"
autowire="constructor">
</bean>
<beanid="customerRequestDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRequestDetails"scope="prototype"/>
<beanid="customerRequestDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRequestDaoImpl"/>
In theaboveexamplelisting,thecustomerRequestServicebeandefinitionspecifiesautowire attribute’s
value as constructor, which means that Spring locates beans of types CustomerRequestDetails and
CustomerRequestDao in the ApplicationContext, and passes them as arguments to
CustomerRequestServiceImpl classs constructor. As customerRequestDetails and customerRequestDao
beans are of type CustomerRequestDetails and CustomerRequestDao, Spring automatically injects
instancesofthesebeansintocustomerRequestServicebean.
IfSpringdoesntfindanybeanintheApplicationContextwhosetypematchestheconstructorargument
type, the constructor argument is not set. If Spring finds multiple beans in the ApplicationContext that
match the constructor argument type, an exception is thrown; therefore, in such scenarios use
<constructor-arg> elements to explicitly identify bean dependencies or set a bean as theprimary
candidateforautowiringbysettingvalueofprimaryattributeof<bean>elementtotrue.
byName
If you specify autowire attribute’s value as byName, Spring autowires bean properties based on their
names. For instance, if a bean A defines a property named x, Spring finds a bean named x in the
ApplicationContextandinjectsitintobeanA.Let’slookatanexampleusageofbyNameautowiringinthe
MyBankapplication.
ThefollowingexamplelistingshowstheMyBankapplicationsFixedDepositServiceImplclass:
Examplelisting4-28–FixedDepositServiceImplclass
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importsample.spring.chapter04.bankapp.dao.FixedDepositDao;
importsample.spring.chapter04.bankapp.domain.FixedDepositDetails;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
privateFixedDepositDaomyFixedDepositDao;
publicvoidsetMyFixedDepositDao(FixedDepositDaomyFixedDepositDao){
this.myFixedDepositDao=myFixedDepositDao;
}
.....
}
The above example listing shows that FixedDepositServiceImpl class defines a property named
myFixedDepositDaooftypeFixedDepositDao.
The following example listing shows bean definitions for FixedDepositServiceImpl and
FixedDepositDaoImpl(animplementationofFixedDepositDaointerface)classes:
Examplelisting4-29–applicationContext.xml-byNameautowiring
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/resources/META-INF/spring
<beanid="FixedDepositService"
class="sample.spring.chapter04.bankapp.service.FixedDepositServiceImpl"
autowire="byName"/>
<beanid="myFixedDepositDao"
class="sample.spring.chapter04.bankapp.dao.FixedDepositDaoImpl"/>
Intheaboveexamplelisting,FixedDepositServicebeandefinitionspecifiesautowireattribute’svalueas
byName, which means properties of FixedDepositService bean are automatically resolved by Spring
basedontheirnames.Inlisting4-28,wesawthattheFixedDepositServiceImplclassdefinesaproperty
named myFixedDepositDao; therefore, Spring looks for a bean named myFixedDepositDao in the
ApplicationContext and injects it into FixedDepositService bean. In the above example listing,
myFixedDepositDao bean definition represents the FixedDepositDaoImpl class, which means that an
instance of FixedDepositDaoImpl is injected for property named myFixedDepositDao in the
FixedDepositServicebean.
default/no
Ifyouspecifyautowireattribute’svalueasdefaultorno,autowiringfeatureisdisabledforthebean.As
Springs default behavior is to use no autowiring for beans, specifying autowire attribute’s value as
defaultmeansnoautowiringwillbeperformedforthebean.Youcanexplicitlyspecifythatabeanmust
notuseSpringsautowiringfeaturebyspecifyingautowireattribute’svalueasno.
NOTEYoucanchangethedefaultautowiringbehaviorofbeansbysettingthedefault-autowireattribute
of<beans>element.For instance, if you set default-autowire attribute’s value tobyType, it effectively
meanssettingvalueofautowireattributeofallthe<bean>elementsintheapplicationcontextXMLfileto
byType.Youshouldnotethatifa<bean>elementsautowireattributespecifiesadifferentvaluethanthe
<beans>elementsdefault-autowireattribute,the<bean>element’sautowireattributevalueappliestothe
bean.
The following example listing shows the bean definition for the MyBank applications
CustomerRegistrationServiceImplclassthatspecifiesautowireattribute’svalueasno:
Examplelisting4-30–applicationContext.xml-noautowiring
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRegistrationService_"
class="sample.spring.chapter04.bankapp.service.CustomerRegistrationServiceImpl"
scope="prototype"autowire="no"/>
Example listing 4-24 showed that the CustomerRegistrationServiceImpl class defines
customerRegistrationDetails(oftypeCustomerRegistrationDetails)andcustomerRegistrationDao(oftype
CustomerRegistrationDao) properties. As the autowire attributes value is specified as no for
customerRegistrationService_bean,autowiringisdisabledforcustomerRegistrationService_bean.This
means that the customerRegistrationDetails and customerRegistrationDao properties of
customerRegistrationService_beanarenotsetbySpring.
So far in this section we have seen different ways in which bean dependencies can be autowired by
Spring.Letsnowlookathowwecanmakeabeanunavailableforautowiringpurposesusing<bean>
element’sautowire-candidateattribute.
Makingbeansunavailableforautowiring
ThedefaultbehavioroftheSpringcontaineristomakebeansavailableforautowiring.Youcanmakea
beanunavailabletootherbeansforautowiringpurposesbysettingautowire-candidateattribute’svalueto
false.
In MyBank application, the AccountStatementServiceImpl class defines a property of type
AccountStatementDao.ThefollowingexamplelistingshowstheAccountStatementServiceImplclass:
Examplelisting4-31–AccountStatementServiceImplclass
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importsample.spring.chapter04.bankapp.dao.AccountStatementDao;
importsample.spring.chapter04.bankapp.domain.AccountStatement;
publicclassAccountStatementServiceImplimplementsAccountStatementService{
privateAccountStatementDaoaccountStatementDao;

publicvoidsetAccountStatementDao(AccountStatementDaoaccountStatementDao){
this.accountStatementDao=accountStatementDao;
}
.....
}
The following example listing shows bean definitions for AccountStatementServiceImpl and
AccountStatementDaoImpl(animplementationofAccountStatementDaointerface)classes:
Examplelisting4-32–applicationContext.xml-autowire-candidateattribute
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/resources/META-INF/spring
<beanid="accountStatementService"
class="sample.spring.chapter04.bankapp.service.AccountStatementServiceImpl"
autowire="byType"/>
<beanid="accountStatementDao"
class="sample.spring.chapter04.bankapp.dao.AccountStatementDaoImpl"
autowire-candidate="false"/>
Intheaboveexamplelisting,theaccountStatementServicebeandefinitionspecifiesautowireattribute’s
valueas byType, which means AccountStatementDaopropertytype ofaccountStatementService bean is
autowiredbytype.AsaccountStatementDaobeanisoftypeAccountStatementDao,you mightthink that
Spring will inject accountStatementDao bean instance into accountStatementService bean. But, Spring
won’t consider accountStatementDao bean for autowiring purposes because the accountStatementDao
beandefinitionspecifiesautowire-candidateattribute’svalueasfalse.
NOTEYoushouldnotethatabeanthatisunavailabletootherbeansforautowiringpurposescanitself
makeuseofSpringsautowiringfeaturetoautomaticallyresolveitsdependencies.
As mentioned earlier, the default behavior of the Spring container is to make beans available for
autowiring purposes. To make only only a select set of beans available for autowiring purposes, set
<beans> elements default-autowire-candidates attribute. The default-autowire-candidates attribute
specifies a bean name pattern, and only beans whose names match the specified pattern are made
available for autowiring. The followingexamplelisting shows anexample usageof default-autowire-
candidatesattribute:
Examplelisting4-33–default-autowire-candidatesattributeexample
<beansdefault-autowire-candidates="*Dao">
.....
<beanid="customerRequestDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRequestDetails"
scope="prototype"autowire-candidate="true"/>
<beanid="customerRequestDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRequestDaoImpl"/>
<beanid="customerRegistrationDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRegistrationDaoImpl"/>
.....
</beans>
Intheaboveexamplelisting,default-autowire-candidatesvalueissetto*Dao,whichmeansthatbeans
whose names end with Dao (like customerRequestDao and customerRegistrationDao beans) will be
available for autowiring purposes. If a bean name doesnt match the pattern specified by the default-
autowire-candidates attribute (like customerRequestDetails bean), you can still make it available for
autowiringpurposesbysettingtheautowire-candidateattributeofthecorresponding<bean>elementto
true.
Letsnowlookatlimitationsofusingautowiringinapplications.
Autowiringlimitations
Wesawthatautowiringfeaturesavestheefforttoexplicitlyspecifybeandependenciesusing<property>
and<constructor-arg>elements.Thedownsidesofusingautowiringfeatureare:
·Youcan’tuseautowiringtosetpropertiesorconstructorargumentsthatareofsimpleJavatypes
(likeint,long,boolean,String,Date, and so on). You canautowire arrays, typed collections and
mapsiftheautowireattribute’svalueissettobyTypeorconstructor.
·        As bean dependencies are automatically resolved by Spring, it results in hiding the overall
structureoftheapplication.Ifyouuse<property>and<constructor-arg>elementstospecifybean
dependencies,itresultsinexplicitlydocumentingtheoverallstructureoftheapplication.Youcan
easily understand and maintain an application in which bean dependencies are explicitly
documented.Forthisreason,itisnotrecommendedtouseautowiringinlargeapplications.
4-7Summary
Inthischapter,welookedathowSpringcaterstodifferentdependencyinjectionscenarios.Welookedat
how you can use ApplicationContextAware interface, <replaced-method> and <lookup-method> sub-
elementsof<bean> element toprogrammaticallyretrieve abean instance from the ApplicationContext.
We also looked at how Spring’s autowiring feature can save the effort for explicitly specifying bean
dependencies in the application context XML file. In the next chapter, we’ll look at how to customize
beansandbeandefinitions.
Chapter5-Customizingbeansandbeandefinitions
5-1Introduction
SofarinthisbookwehaveseenexamplesinwhichtheSpringcontainercreatedabeaninstancebasedon
thebeandefinitionspecifiedintheapplicationcontextXMLfile.Inthischapter,we’llgoastepfurther
andlookat:
·howtoincorporatecustominitializationanddestructionlogicforabean
·howtointeractwithanewlycreatedbeaninstancebyimplementingSpringsBeanPostProcessor
interface
·howtomodifybeandefinitionsbyimplementingSpringsBeanFactoryPostProcessorinterface
5-2Customizingbean’sinitializationanddestructionlogic
We saw in earlier chapters that the Spring container is responsible for creating a bean instance and
injectingitsdependencies.Aftercreatingabeaninstancebyinvokingtheconstructorofthebeanclass,the
Springcontainersetsbeanpropertiesbyinvokingbeanssettermethods.Ifyouwanttoexecutecustom
initialization logic (like opening a file, creating a database connection, and so on)after the bean
propertiesaresetbutbeforethebeaniscompletelyinitializedbytheSpringcontainer,youcandosoby
specifyingthenameoftheinitializationmethodasthevalueofinit-methodattributeof<bean>element.
Similarly,ifyou wantto executecustomcleanuplogic before the Spring container containingthe bean
instance is destroyed, you can specify the name of the cleanup method as the value of destroy-
methodattributeof<bean>element.
IMPORT chapter 5/ch05-bankapp-customization (This project shows the MyBank application that
uses <bean> element’s init-method and destroy-method elements to specify custom initialization and
destructionmethods.Totestwhethertheinitializationmethodisexecuted,executethemainmethodofthe
BankApp class of this project. To test whether the destruction method is executed, execute the main
methodoftheBankAppWithHookclassofthisproject.)
The following example listing shows the MyBanks FixedDepositDaoImpl class that defines an
initializationmethodnamedinitializeDbConnectionforobtainingconnectiontoMyBanksdatabase,anda
destructionmethodnamedreleaseDbConnectionforreleasingtheconnection:
Examplelisting5-1–FixedDepositDaoImplclass-Custominitializationanddestructionlogic
Project–ch05-bankapp-customization
Sourcelocation-src/main/java/sample/spring/chapter05/bankapp/dao
packagesample.spring.chapter05.bankapp.dao;
publicclassFixedDepositDaoImplimplementsFixedDepositDao{
privatestaticLoggerlogger=Logger.getLogger(FixedDepositDaoImpl.class);
privateDatabaseConnectionconnection;
publicFixedDepositDaoImpl(){
logger.info("FixedDepositDaoImpl'sconstructorinvoked");
}
publicvoidinitializeDbConnection(){
logger.info("FixedDepositDaoImpl’sinitializeDbConnectionmethodinvoked");
connection=DatabaseConnection.getInstance();
}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
logger.info("FixedDepositDaoImpl’screateFixedDepositmethodinvoked");
//--savethefixeddepositsandthenreturntrue
returntrue;
}
publicvoidreleaseDbConnection(){
logger.info("FixedDepositDaoImpl’sreleaseDbConnectionmethodinvoked");
connection.releaseConnection();
}
}
In the above example listing, the DatabaseConnection object is used for interacting with the MyBanks
database. FixedDepositDaoImpl class defines an initializeDbConnection method that initializes the
DatabaseConnection object, which is later used by the createFixedDeposit method for saving fixed
depositdetailsintheMyBanksdatabase.
The following example listing shows the MyBank’s FixedDepositServiceImpl class that uses
FixedDepositDaoImplinstancetocreatenewfixeddeposits:
Examplelisting5-2–FixedDepositServiceImplclass
Project–ch05-bankapp-customization
Sourcelocation-src/main/java/sample/spring/chapter05/bankapp/service
packagesample.spring.chapter05.bankapp.service;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
privatestaticLoggerlogger=Logger.getLogger(FixedDepositServiceImpl.class);
privateFixedDepositDaomyFixedDepositDao;
publicvoidsetMyFixedDepositDao(FixedDepositDaomyFixedDepositDao){
logger.info("FixedDepositServiceImpl'ssetMyFixedDepositDaomethodinvoked");
this.myFixedDepositDao=myFixedDepositDao;
}
@Override
publicvoidcreateFixedDeposit(FixedDepositDetailsfixedDepositDetails)throwsException{
//--createfixeddeposit
myFixedDepositDao.createFixedDeposit(fixedDepositDetails);
}
}
The above example listing shows that the FixedDepositDaoImpl instance is a dependency of
FixedDepositServiceImpl, and is passed as an argument to the setMyFixedDepositDao setter-method.
And, if FixedDepositServiceImpls createFixedDeposit method is invoked, it results in invocation of
FixedDepositDaoImplscreateFixedDepositmethod.
The following example listing shows bean definitions for FixedDepositDaoImpl and
FixedDepositServiceImplclasses:
Examplelisting5-3–applicationContext.xml–usageofinit-methodanddestroy-methodattributes
Project–ch05-bankapp-customization
Sourcelocation-src/main/resources/META-INF/spring
<beans.....>
<beanid="FixedDepositService"
class="sample.spring.chapter05.bankapp.service.FixedDepositServiceImpl">
<propertyname="myFixedDepositDao"ref="myFixedDepositDao"/>
</bean>
<beanid="myFixedDepositDao"
class="sample.spring.chapter05.bankapp.dao.FixedDepositDaoImpl"
init-method="initializeDbConnection"destroy-method="releaseDbConnection"/>
</beans>
The above example listing shows that the <bean> element corresponding to the FixedDepositDaoImpl
class specifies initializeDbConnection and releaseDbConnection as the values of init-method and
destroy-methodattributes,respectively.
NOTEItisimportanttonotethattheinitializationanddestructionmethodsspecifiedbytheinit-method
anddestroy-methodattributesof<bean>elementmustnotacceptanyarguments,butcanbedefinedto
throwexceptions.
The following example listing shows BankApp class whose main method retrieves
FixedDepositServiceImplinstancefromtheApplicationContextandinvokesFixedDepositServiceImpls
createFixedDepositmethod:
Examplelisting5-4–BankAppclass
Project–ch05-bankapp-customization
Sourcelocation-src/main/java/sample/spring/chapter05/bankapp
packagesample.spring.chapter05.bankapp;
publicclassBankApp{
publicstaticvoidmain(Stringargs[])throwsException{
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
FixedDepositServiceFixedDepositService=context.getBean(FixedDepositService.class);
FixedDepositService.createFixedDeposit(newFixedDepositDetails(1,1000,
12,"someemail@somedomain.com"));
}
}
IfyounowexecutetheBankApp’smainmethod,youllseethefollowingoutputontheconsole:
FixedDepositDaoImpl'sconstructorinvoked
FixedDepositDaoImplsinitializeDbConnectionmethodinvoked
FixedDepositServiceImpl'ssetMyFixedDepositDaomethodinvoked
FixedDepositDaoImplscreateFixedDepositmethodinvoked
TheaboveoutputshowsthattheSpringcontainerfirstcreatesFixedDepositDaoImplsinstance,andthen
invokes initializeDbConnection method. After the invocation of initializeDbConnection method, the
FixedDepositDaoImplinstanceisinjectedintotheFixedDepositServiceImplinstance.Thisshowsthatthe
Springcontainerinjectsadependency(theFixedDepositDaoImplinstance)intothedependentbean(the
FixedDepositServiceImpl instance)after the initialization method of the dependency is invoked by the
Springcontainer.
YoumayhavenoticedthattheoutputfromexecutingBankApp’smainmethoddidn’tcontainthefollowing
message:FixedDepositDaoImpl’sreleaseDbConnectionmethodinvoked(referFixedDepositDaoImpls
releaseDbConnection method in example listing 5-1). This means that the FixedDepositDaoImpls
releaseDbConnection method was not called by the Spring container when BankApp’s main method
exited.Inarealworldapplicationdevelopmentscenario,thismeansthatthedatabaseconnectionheldby
FixedDepositDaoImpl instance is never released. Let’s now see how you can make Spring gracefully
destroysingleton-scopedbeaninstancesbycallingthecleanupmethodspecifiedbythe<bean>element’s
destroy-methodattribute.
MakingSpringinvokecleanupmethodspecifiedbythedestory-methodattribute
The web version of ApplicationContext implementation is represented by Springs
WebApplicationContextobject.WebApplicationContextimplementationhasthenecessarylogictoinvoke
thecleanupmethod(specifiedbythedestroy-methodattribute)ofsingleton-scopedbeaninstancesbefore
thewebapplicationisshutdown.
NOTETheapproachdescribedinthissectiononmakingSpringgracefullydestroysingleton-scopedbean
instancesbycallingthecleanupmethodisspecifictostandaloneapplications.
Thefollowingexa