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 .
Page Count: 517 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Preface
- Chapter 1 – Introduction to Spring Framework
- Chapter 2 – Spring Framework basics
- Chapter 3 - Configuring beans
- Chapter 4 - Dependency injection
- Chapter 5 - Customizing beans and bean definitions
- Chapter 6- Annotation-driven development with Spring
- Chapter 7 - Database interaction using Spring
- Chapter 8 - Messaging, emailing, asynchronous method execution, and caching using Spring
- Chapter 9 - Aspect-oriented programming
- Chapter 10 – Spring Web MVC basics
- Chapter 11 – Validation and data binding in Spring Web MVC
- Chapter 12 –Developing RESTful web services using Spring Web MVC
- Chapter 13 – More Spring Web MVC – internationalization, file upload and asynchronous request processing
- Chapter 14 – Securing applications using Spring Security
- Appendix A – Importing and deploying sample projects in Eclipse IDE (or IntelliJ IDEA)

GettingstartedwithSpringFramework
SecondEdition
AshishSarin,JSharma

Tableofcontents
Preface
Howtousethisbook
Conventionsusedinthisbook
Feedbackandquestions
Abouttheauthors
Chapter1–IntroductiontoSpringFramework
1-1Introduction
1-2SpringFrameworkmodules
1-3SpringIoCcontainer
1-4BenefitsofusingSpringFramework
Consistentapproachtomanaginglocalandglobaltransactions
Declarativetransactionmanagement
Security
JMX(JavaManagementExtensions)
JMS(JavaMessageService)
Caching
1-5AsimpleSpringapplication
Identifyingapplicationobjectsandtheirdependencies
CreatingPOJOclassescorrespondingtoidentifiedapplicationobjects
Creatingtheconfigurationmetadata
CreatinganinstanceofSpringcontainer
AccessbeansfromtheSpringcontainer
1-6FrameworksbuiltontopofSpring
1-7Summary
Chapter2–SpringFrameworkbasics
2-1Introduction
2-2Programmingtointerfacesdesignprinciple
Scenario:Dependentclasscontainsreferencetotheconcreteclassofdependency
Scenario:Dependentclasscontainsreferencetotheinterfaceimplementedbythe
dependency
Spring’ssupportfor‘programmingtointerfaces’designapproach

2-3DifferentapproachestoinstantiatingSpringbeans
Instantiatingbeansviastaticfactorymethods
Instantiatingbeansviainstancefactorymethods
2-4Dependencyinjectiontechniques
Setter-basedDI
Constructor-basedDI
2-5Beanscopes
Singleton
Prototype
Choosingtherightscopeforyourbeans
2-6Summary
Chapter3-Configuringbeans
3-1Introduction
3-2Beandefinitioninheritance
MyBank–Beandefinitioninheritanceexample
Whatgetsinherited?
3-3Constructorargumentmatching
Passingsimplevaluesandbeanreferencesusing<constructor-arg>element
Constructorargumentmatchingbasedontype
Constructorargumentmatchingbasedonname
3-4Configuringdifferenttypesofbeanpropertiesandconstructorarguments
Built-inpropertyeditorsinSpring
Specifyingvaluesfordifferentcollectiontypes
Specifyingvaluesforarrays
Defaultcollectionimplementationfor<list>,<set>and<map>elements
3-5Built-inpropertyeditors
CustomCollectionEditor
CustomMapEditor
CustomDateEditor
3-6RegisteringpropertyeditorswiththeSpringcontainer
CreatingaPropertyEditorRegistrarimplementation
ConfiguringtheCustomEditorConfigurerclass
3-7Concisebeandefinitionswithpandcnamespaces
p-namespace
c-namespace
3-8Spring’sutilschema

<list>
<map>
<set>
<properties>
<constant>
<property-path>
3-9FactoryBeaninterface
MyBankapplication–Storingeventsinthedatabase
MyBank–FactoryBeanexample
AccessingtheFactoryBeaninstance
3-10Summary
Chapter4-Dependencyinjection
4-1Introduction
4-2Innerbeans
4-3Explicitlycontrollingthebeaninitializationorderwithdepends-onattribute
MyBank–implieddependenciesbetweenbeans
Implicitdependencyproblem
4-4Singleton-andprototype-scopedbean’sdependencies
Singleton-scopedbean’sdependencies
Prototype-scopedbean’sdependencies
4-5Obtainingnewinstancesofprototypebeansinsidesingletonbeans
ApplicationContextAwareinterface
<lookup-method>element
<replaced-method>element
4-6Autowiringdependencies
byType
constructor
byName
default/no
Makingbeansunavailableforautowiring
Autowiringlimitations
4-7Summary
Chapter5-Customizingbeansandbeandefinitions
5-1Introduction
5-2Customizingbean’sinitializationanddestructionlogic

MakingSpringinvokecleanupmethodspecifiedbythedestory-methodattribute
Cleanupmethodsandprototype-scopedbeans
Specifyingdefaultbeaninitializationanddestructionmethodsforallbeans
InitializingBeanandDisposableBeanlifecycleinterfaces
JSR250’s@PostConstructand@PreDestroyannotations
5-3InteractingwithnewlycreatedbeaninstancesusingBeanPostProcessor
BeanPostProcessorexample–Validatingbeaninstances
BeanPostProcessorexample–Resolvingbeandependencies
BeanPostProcessorbehaviorforFactoryBeans
RequiredAnnotationBeanPostProcessor
DestructionAwareBeanPostProcessor
5-4ModifyingbeandefinitionsusingBeanFactoryPostProcessor
BeanFactoryPostProcessorexample
PropertySourcesPlaceholderConfigurer
PropertyOverrideConfigurer
5-5Summary
Chapter6-Annotation-drivendevelopmentwithSpring
6-1Introduction
6-2IdentifyingSpringcomponentswith@Component
6-3@Autowired-autowiringdependenciesbytype
6-4@Qualifier–autowiringdependenciesbyname
6-5JSR330’s@Injectand@Namedannotations
6-6JSR250’s@Resourceannotation
6-7@Scope,@Lazy,@DependsOnand@Primaryannotations
6-8Simplifyingcomponentconfigurationusing@Valueannotation
6-9ValidatingobjectsusingSpring’sValidatorinterface
6-10SpecifyingconstraintsusingJSR303annotations
JSR303supportinSpring
6-11ProgrammaticallyconfiguringSpringbeansusing@Configurationand@Bean
annotations
6-12Summary
Chapter7-DatabaseinteractionusingSpring
7-1Introduction
7-2MyBankapplication’srequirements

7-3DevelopingtheMyBankapplicationusingSpring’sJDBCmodule
Configuringadatasource
CreatingDAOsthatuseSpring’sJDBCmoduleclasses
7-4DevelopingtheMyBankapplicationusingHibernate
ConfiguringSessionFactoryinstance
CreatingDAOsthatuseHibernateAPIfordatabaseinteraction
7-5TransactionmanagementusingSpring
MyBank’stransactionmanagementrequirements
Programmatictransactionmanagement
Declarativetransactionmanagement
Spring’ssupportforJTA
7-6Summary
Chapter8-Messaging,emailing,asynchronousmethodexecution,andcachingusing
Spring
8-1Introduction
8-2MyBankapplication’srequirements
8-3SendingJMSmessages
ConfiguringActiveMQbrokertoruninembeddedmode
ConfiguringaJMSConnectionFactory
SendingJMSmessagesusingJmsTemplate
SendingJMSmessageswithinatransaction
DynamicJMSdestinationsandJmsTemplateconfiguration
JmsTemplateandmessageconversion
8-4ReceivingJMSmessages
SynchronouslyreceivingJMSmessagesusingJmsTemplate
AsynchronouslyreceivingJMSmessagesusingmessagelistenercontainers
8-5Sendingemails
8-6Taskschedulingandasynchronousexecution
TaskExecutorinterface
TaskSchedulerinterface
@Asyncand@Scheduledannotations
8-7Caching
ConfiguringaCacheManager
Cachingannotations-@Cacheable,@CacheEvictand@CachePut
8-8RunningtheMyBankapplication
8-9Summary

Chapter9-Aspect-orientedprogramming
9-1Introduction
9-2AsimpleAOPexample
9-3SpringAOPframework
Proxycreation
expose-proxyattribute
9-4Pointcutexpressions
@Pointcutannotation
executionandargspointcutdesignators
beanpointcutdesignator
Annotations-basedpointcutdesignators
9-5Advicetypes
Beforeadvice
Afterreturningadvice
Afterthrowingadvice
Afteradvice
Aroundadvice
9-6SpringAOP-XMLschema-style
ConfiguringanAOPaspect
Configuringanadvice
Associatingapointcutexpressionwithanadvice
9-7Summary
Chapter10–SpringWebMVCbasics
10-1Introduction
10-2Directorystructureofsamplewebprojects
10-3Understandingthe‘HelloWorld’webapplication
HelloWorldController.java–HelloWorldwebapplication’scontrollerclass
helloworld.jsp–JSPpagethatshowsthe‘HelloWorld!!’message
myapp-config.xml–WebapplicationcontextXMLfile
web.xml–Webapplicationdeploymentdescriptor
10-4DispatcherServlet–thefrontcontroller
AccessingServletContextandServletConfigobjects
10-5Developingcontrollersusing@Controllerand@RequestMappingannotations
Developinga‘HelloWorld’webapplicationusinganannotatedcontroller
10-6MyBankwebapplication’srequirements

10-7SpringWebMVCannotations-@RequestMappingand@RequestParam
Mappingrequeststocontrollersorcontrollermethodsusing@RequestMapping
@RequestMappingannotatedmethodsarguments
@RequestMappingannotatedmethodsreturntypes
Passingrequestparameterstocontrollermethodsusing@RequestParam
10-8Validation
10-9Handlingexceptionsusing@ExceptionHandlerannotation
10-11LoadingrootwebapplicationcontextXMLfile(s)
10-12Summary
Chapter11–ValidationanddatabindinginSpringWebMVC
11-1Introduction
11-2Addingandretrievingmodelattributesusing@ModelAttributeannotation
Addingmodelattributesusingmethod-level@ModelAttributeannotation
Retrievingmodelattributesusing@ModelAttributeannotation
Requestprocessingand@ModelAttributeannotatedmethods
Behaviorof@ModelAttributeannotatedmethodarguments
RequestToViewNameTranslator
11-3Cachingmodelattributesusing@SessionAttributesannotation
11-4DatabindingsupportinSpring
WebDataBinder–databinderforwebrequestparameters
ConfiguringaWebDataBinderinstance
Allowingordisallowingfieldsfromdatabindingprocess
InspectingdatabindingandvalidationerrorsusingBindingResultobject
11-5ValidationsupportinSpring
ValidatingmodelattributesusingSpring’sValidatorinterface
SpecifyingconstraintsusingJSR303annotations
ValidatingobjectsthatuseJSR303annotations
11-6Spring’sformtaglibrary
HTML5supportinSpring’sformtaglibrary
11-7Summary
Chapter12–DevelopingRESTfulwebservicesusingSpringWebMVC
12-1Introduction
12-2Fixeddepositwebservice
12-3ImplementingaRESTfulwebserviceusingSpringWebMVC

JSON(JavaScriptObjectNotation)
FixedDepositWSwebserviceimplementation
12-4AccessingRESTfulwebservicesusingRestTemplate
12-5ConvertingJavaobjectstoHTTPrequestsandresponsesandviceversausing
HttpMessageConverter
12-6@PathVariableand@MatrixVariableannotations
12-7Summary
Chapter13–MoreSpringWebMVC–internationalization,fileuploadand
asynchronousrequestprocessing
13-1Introduction
13-2Pre-andpost-processingrequestsusinghandlerinterceptors
Implementingandconfiguringahandlerinterceptor
13-3Internationalizingusingresourcebundles
MyBankwebapplication’srequirements
InternationalizingandlocalizingMyBankwebapplication
13-4Asynchronouslyprocessingrequests
Asynchronousrequestprocessingconfiguration
ReturningCallablefrom@RequestMappingmethods
ReturningDeferredResultfrom@RequestMappingmethods
Settingdefaulttimeoutvalue
Interceptingasynchronousrequests
13-5TypeconversionandformattingsupportinSpring
CreatingacustomConverter
ConfiguringandusingacustomConverter
CreatingacustomFormatter
ConfiguringacustomFormatter
CreatingAnnotationFormatterFactorytoformatonly@AmountFormatannotated
fields
ConfiguringAnnotationFormatterFactoryimplementation
13-6FileuploadsupportinSpringWebMVC
UploadingfilesusingCommonsMultipartResolver
UploadingfilesusingStandardServletMultipartResolver
13-7Summary
Chapter14–SecuringapplicationsusingSpringSecurity
14-1Introduction

14-2SecurityrequirementsoftheMyBankwebapplication
14-3SecuringMyBankwebapplicationusingSpringSecurity
Webrequestsecurityconfiguration
Authenticationconfiguration
SecuringJSPcontentusingSpringSecurity’sJSPtablibrary
Securingmethods
14-4MyBankwebapplication-securingFixedDepositDetailsinstancesusingSpring
Security’sACLmodule
Deployingandusingch14-bankapp-db-securityproject
DatabasetablestostoreACLanduserinformation
Userauthentication
Webrequestsecurity
JdbcMutableAclServiceconfiguration
Method-levelsecurityconfiguration
Domainobjectinstancesecurity
ManagingACLentriesprogrammatically
MutableAclandsecurity
14-5Summary
AppendixA–ImportinganddeployingsampleprojectsinEclipseIDE(orIntelliJ
IDEA)
A-1Settingupthedevelopmentenvironment
A-2ImportingasampleprojectintoEclipseIDE(orIntelliJIDEA)
Importingasampleproject
ConfiguringtheM2_REPOclasspathvariableintheEclipseIDE
A-3ConfiguringEclipseIDEwithTomcat7server
A-4DeployingawebprojectonTomcat7server
RunningtheTomcat7serverinembeddedmode

Preface
Howtousethisbook
Downloadsampleprojects
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/.Youcandownloadthe
sampleprojectsasasingleZIPfileoryoucancheckoutthesampleprojectsusingSVN.Formoredetails,
refertotheaboveURL.
ImportsampleprojectsintoyourEclipseorIntelliJIDEAIDE
IfyouseeIMPORTchapter<chapter-number>/<projectname>at anypoint while reading the book,
youshouldimportthespecifiedprojectintoyourEclipseorIntelliJIDEAIDE(oranyotherIDEthatyou
areusing).ThesampleprojectsuseMaven3.xbuildtoolforbuildingtheproject;therefore,you’llfinda
pom.xmlfileinsideeachoftheprojects.Apom.xmlfileisalsoprovidedattherootofthesourcecode
distribution,whichbuildsalltheprojects.
ReferappendixAtoseethestepsrequiredforimportingandrunningthesampleprojects.
Refertocodeexamples
Each example listing specifies the sample project name (using Project label) and the location of the
sourcefile(usingSourcelocationlabel).IftheProjectandSourcelocationlabelsarenotspecified,you
canassumethatthecodeshownintheexamplelistingisnotbeingusedanywhereinthesampleprojects,
andithasbeenshownpurelytosimplifyunderstanding.
Conventionsusedinthisbook
Italicshasbeenusedforemphasizingterms
Comic Sans MS has been used for example listings, Java code, configuration details in XML and
propertiesfiles
Comic Sans MS has been used in example listings to highlight important parts of the code or
configuration
ANOTEhighlightsanimportaintpoint.
Feedbackandquestions
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
AshishSarinisaSunCertifiedEnterpriseArchitectwithmorethan14yearsofexperienceinarchitecting
applications.HeistheauthorofSpringRoo1.1Cookbook(byPacktPublishing)andPortletsinAction
(byManningPublications)
JSharmaisafreelanceJavadeveloperwithextensiveexperienceindevelopingSpringapplications.

Chapter1–IntroductiontoSpringFramework

1-1Introduction
InthetraditionalJavaenterpriseapplicationdevelopmentefforts,itwasadeveloper’sresponsibilityto
createwell-structured,maintainableandeasilytestableapplications.Thedevelopersusedmyriaddesign
patternstoaddressthesenon-businessrequirementsofanapplication.Thisnotonlyledtolowdeveloper
productivity,butalsoadverselyaffectedthequalityofdevelopedapplications.
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
infrastructurefordevelopingwell-structured,maintainableandeasilytestableapplications.Whenusing
Spring Framework, a developer only needs to focus on writing the business logic of the application,
resultinginimproveddeveloperproductivity.YoucanuseSpringFrameworktodevelopstandaloneJava
applications,webapplications,applets,oranyothertypeofJavaapplication.
ThischapterstartsoffwithanintroductiontoSpringFrameworkmodulesanditsbenefits.Attheheartof
SpringFrameworkisitsInversionofControl(IoC)container,whichprovidesdependencyinjection(DI)
feature. This chapter introduces Spring’s DIfeature 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’sprojectsthatuseSpringFrameworkastheirfoundation.Thischapterwillsetthestagefor
theremainingchaptersthatdelvedeeperintotheSpringFramework.
NOTEInthisbook,we’lluseanexampleInternetBankingapplication,MyBank,tointroduceSpring
Frameworkfeatures.

1-2SpringFrameworkmodules
SpringFrameworkconsistsofmultiplemodulesthataregroupedbasedontheapplicationdevelopment
featurestheyaddress.ThefollowingtabledescribesthedifferentmodulegroupsinSpringFramework:
Modulegroup Description
Corecontainer
ContainsmodulesthatformthefoundationofSpringFramework.Themodulesinthisgroup
provideSpring’sDIfeatureandIoCcontainerimplementation.
AOPand
instrumentation
Contains modules that support AOP (Aspect-oriented Programming) and class
instrumentation.
DataAccess/Integration
Contains modules that simplify interaction with databases and messaging providers. This
modulegroupalsocontainsmodulesthatsupportprogrammaticanddeclarativetransaction
management,andobject/XM Lmappingimplementations,likeJAXBandCastor.
Web Containsmodulesthatsimplifydevelopingwebandportletapplications.
Test Containsasinglemodulethatsimplifiescreatingunitandintegrationtests.
TheabovetableshowsthatSpringcoverseveryaspectofenterpriseapplicationdevelopment;youcan
useSpringfordevelopingwebapplications,accessingdatabases,managingtransactions,creatingunitand
integration tests, and so on. The Spring Framework modules are designed in such a way that you only
needtoincludethemodulesthatyourapplicationneeds.Forinstance,touseSpring’sDIfeatureinyour
application,youonlyneedtoincludethemodulesgroupedunderCorecontainer.Asyouprogressthrough
thisbook,you’llfinddetailsofsomeofthemodulesthatarepartofSpring,andexamplesthatshowhow
theyareusedindevelopingapplications.
Thefollowingfigureshowstheinter-dependenciesofdifferentmodulesofSpring:
Figure1-1Springmodulesinter-dependencies
YoucaninferfromtheabovefigurethatthemodulescontainedintheCorecontainergrouparecentralto
theSpringFramework,andothermodulesdependonit.Equallyimportantarethemodulescontainedin
theAOPandinstrumentationgroupbecausetheyprovideAOPfeaturestoothermodulesintheSpring
Framework.
Now,thatyouhavesomebasicideaabouttheareasofapplicationdevelopmentcoveredbySpring,let’s
lookattheSpringIoCcontainer.

1-3SpringIoCcontainer
AJavaapplicationconsistsofobjectsthatinteractwitheachothertoprovideapplicationbehavior.The
objectswithwhichanobjectinteractsarereferredtoasitsdependencies.Forinstance,ifanobjectX
interactswithobjectsYandZ,thenYandZaredependenciesofobjectX.DIisadesignpatterninwhich
thedependenciesofanobjectaretypicallyspecifiedasargumentstoitsconstructorandsettermethods.
And,thesedependenciesareinjectedintotheobjectwhenit’screated.
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
containercreatesandmanagesarereferredasbeans.AstheSpringcontainerisresponsibleforputting
togetherapplicationobjects,youdon’tneedtoimplementdesignpatterns,likeFactory,ServiceLocator,
andsoon,tocomposeyourapplication.DIisalsoreferredtoasInversionofControl(IoC)becausethe
responsibilityofcreatingandinjectingdependenciesisnotwiththeapplicationobjectbutwiththeSpring
container.
Let’ssaythattheMyBankapplication(whichisthenameofoursampleapplication)containstwoobjects,
FixedDepositController and FixedDepositService. The following example listing shows that the
FixedDepositControllerobjectdependsonFixedDepositServiceobject:
Examplelisting1-1:FixedDepositControllerclass
publicclassFixedDepositController{
privateFixedDepositServicefixedDepositService;
publicFixedDepositController(){
fixedDepositService=newFixedDepositService();
}
publicbooleansubmit(){
//--savethefixeddepositdetails
fixedDepositService.save(.....);
}
}
In the above example listing, FixedDepositController’s constructor creates an instance of
FixedDepositService which is later used in FixedDepositController’s submit method. As
FixedDepositController interacts with FixedDepositService, FixedDepositService represents a
dependencyofFixedDepositController.
To configure FixedDepositController as a Spring bean, you first need to modify the
FixedDepositControllerclassofexamplelisting1-1suchthatitacceptsFixedDepositServicedependency
as a constructor argument or as a setter method argument. The following example listing shows the
modifiedFixedDepositControllerclass:
Example listing 1-2: FixedDepositController class – FixedDepositService is passed as a constructor
argument

publicclassFixedDepositController{
privateFixedDepositServicefixedDepositService;
publicFixedDepositController(FixedDepositServicefixedDepositService){
this.fixedDepositService=fixedDepositService;
}
publicbooleansubmit(){
//--savethefixeddepositdetails
fixedDepositService.save(.....);
}
}
TheaboveexamplelistingshowsthattheFixedDepositServiceinstanceisnowpassedasaconstructor
argumenttotheFixedDepositControllerinstance.Now,theFixedDepositServiceclasscanbeconfigured
as a Spring bean. Notice that the FixedDepositController class doesn’t implement or extend from any
Springinterfaceorclass.
Foragivenapplication,informationaboutapplicationobjectsandtheirdependenciesisspecifiedusing
configurationmetadata. Spring IoC container reads application’s configuration metadata to instantiate
applicationobjectsandinjecttheirdependencies.Thefollowingexamplelistingshowstheconfiguration
metadata(inXMLformat)foranapplicationthatconsistsofMyControllerandMyServiceclasses:
Examplelisting1-3:Configurationmetadata
<beans.....>
<beanid="myController"class="sample.spring.controller.MyController">
<constructor-argindex="0"ref="myService"/>
</bean>
<beanid="myService"class="sample.spring.service.MyService"/>
</beans>
Intheaboveexamplelisting,each<bean>elementdefinesanapplicationobjectthatismanagedbythe
Springcontainer,andthe<constructor-arg>elementspecifiesthataninstanceofMyServiceispassedas
anargumenttoMyController’sconstructor.The<bean>elementisdiscussedindetaillaterinthischapter,
andthe<constructor-arg>elementisdiscussedinchapter2.
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 of Java Reflection API
(http://docs.oracle.com/javase/tutorial/reflect/index.html) to create application objects and inject their
dependencies.ThefollowingfiguresummarizeshowtheSpringcontainerworks:

Figure 1-2 Spring container reads application’s configuration metadata and creates a fully-configured
application
TheconfigurationmetadatacanbesuppliedtotheSpringcontainerviaXML(asshowninexamplelisting
1-3),Javaannotations(referchapter6)andalsothroughtheJavacode(referchapter6).
AstheSpringcontainerisresponsibleforcreatingandmanagingapplicationobjects,enterpriseservices
(like transaction management, security, remote access, and so on) can be transparently applied to the
objectsbytheSpringcontainer.TheabilityoftheSpringcontainertoenhancetheapplicationobjectswith
additional functionality makes it possible for you to model your application objects as simple Java
objects(alsoreferredtoasPOJOsorPlainOldJavaObjects).JavaclassescorrespondingtoPOJOs
are referred to as POJO classes, which are nothing but Java classes that don’t implement or extend
framework-specificinterfacesorclasses.Theenterpriseservices,liketransactionmanagement,security,
remoteaccess,andsoon,requiredbythesePOJOsaretransparentlyprovidedbytheSpringcontainer.
Now,thatweknowhowSpringcontainerworks,let’slookatsomeexamplesthatdemonstratebenefitsof
developingapplicationsusingSpring.

1-4BenefitsofusingSpringFramework
Intheprevioussection,wediscussedthefollowingbenefitsofusingSpring:
§Springsimplifiescomposing Javaapplications bytakingcare ofcreating applicationobjects and
injectingtheirdependencies
§SpringpromotesdevelopingapplicationsasPOJOs
SpringalsosimplifiesinteractionwithJMSproviders,JNDI,MBeanservers,emailservers,databases,
andsoon,byprovidingalayerofabstractionthattakescareoftheboilerplatecode.
Let’s take a quick look at a few examples to better understand the benefits of developing applications
usingSpring.
Consistentapproachtomanaginglocalandglobaltransactions
If you are using Spring for developing transactional applications, you can use Spring’s declarative
transactionmanagementsupporttomanagetransactions.
ThefollowingexamplelistingshowstheFixedDepositServiceclassofMyBankapplication:
Examplelisting1-4–FixedDepositServiceclass
publicclassFixedDepositService{
publicFixedDepositDetailsgetFixedDepositDetails(.....){.....}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){.....}
}
TheFixedDepositService class is a POJO class that defines methods to create and retrieve details of
fixeddeposits.Thefollowingfigureshowstheformforcreatinganewfixeddeposit:
Figure1-3HTMLformforcreatinganewfixeddeposit
Acustomerentersthefixeddepositamount,tenureandemailidinformationintheaboveformandclicks
theSave button to create a new fixed deposit. The FixedDepositService’s createFixedDeposit method
(referexamplelisting1-1)isinvokedtocreatethefixeddeposit.ThecreateFixedDepositmethoddebits
theamountenteredbythecustomerfromhisbankaccount,andcreatesafixeddepositofthesameamount.
Let’ssaythatinformationaboutthebankbalanceofcustomersisstoredinBANK_ACCOUNT_DETAILS
databasetable,andthefixeddepositdetailsarestoredinFIXED_DEPOSIT_DETAILSdatabasetable.If

a customer creates a fixed deposit of amount x, amount x is subtracted from the
BANK_ACCOUNT_DETAILStable,andanewrecordisinsertedinFIXED_DEPOSIT_DETAILStable
toreflectthenewlycreatedfixeddeposit.IfBANK_ACCOUNT_DETAILStableisnotupdatedoranew
recordisnotinsertedinFIXED_DEPOSIT_DETAILStable,it’llleavethesysteminaninconsistentstate.
ThismeansthecreateFixedDepositmethodmustbeexecutedwithinatransaction.
The database used by the MyBank application represents a transactional resource. In the traditional
approachtoperforma setof databasemodificationsasasingleunitof work,you’llfirstdisableauto-
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
createFixedDepositmethodusingthetraditionalapproach:
Examplelisting1-5–ProgrammaticallymanagingdatabasetransactionusingJDBCConnectionobject
importjava.sql.Connection;
importjava.sql.SQLException;
publicclassFixedDepositService{
publicFixedDepositDetailsgetFixedDepositDetails(.....){.....}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
Connectioncon=.....;
try{
con.setAutoCommit(false);
//--executeSQLstatementsthatmodifydatabasetables
con.commit();
}catch(SQLExceptionsqle){
if(con!=null){
con.rollback();
}
}
.....
}
}
TheaboveexamplelistingshowsthatthecreateFixedDepositmethodprogrammaticallymanagesdatabase
transactionusingJDBCConnectionobject.Thisapproachissuitableforapplicationscenariosinwhicha
singledatabaseisinvolved.Transactionsthatareresource-specific,likethetransactionassociatedwitha
JDBCConnection,arereferredtoaslocaltransactions.
When multiple transactional resources are involved, JTA (Java Transaction API) is used for managing
transactions.Forinstance,ifyouwanttosendaJMSmessagetoamessagingmiddleware(atransactional
resource)andupdateadatabase(anothertransactionalresource)inthesametransaction,youmustusea
JTA transaction manager to manage transactions. JTA transactions are also referred to as global (or
distributed)transactions.TouseJTA,youfetchUserTransactionobject(whichispartofJTAAPI)from
JNDIandprogrammaticallystartandcommit(orrollback)transactions.
As you can see, you can either useJDBC Connection (for local transactions) or UserTransaction (for

globaltransactions)objecttoprogrammaticallymanage transactions.Itisimportanttonotethatalocal
transaction cannot run within a global transaction. This means that if you want database updates in
createFixedDepositmethod(referexamplelisting1-5)tobepartofaJTAtransaction,youneedtomodify
thecreateFixedDepositmethodtousetheUserTransactionobjectfortransactionmanagement.
Spring simplifies transaction management by providing a layer of abstraction that gives a consistent
approach to managing both local and global transactions. This means that if you write the
createFixedDepositmethod(referexamplelisting1-5)usingSpring’stransactionabstraction,youdon’t
needtomodifythemethodwhenyouswitchfromlocaltoglobaltransactionmanagement,orviceversa.
Spring’stransactionabstractionisexplainedinchapter7.
Declarativetransactionmanagement
Springgivesyoutheoptiontousedeclarativetransactionmanagement.Youcanannotateamethodwith
Spring’s@TransactionalannotationandletSpringhandletransactions,asshownhere:
Examplelisting1-6–@Transactionalannotationusage
importorg.springframework.transaction.annotation.Transactional;
publicclassFixedDepositService{
publicFixedDepositDetailsgetFixedDepositDetails(.....){.....}
@Transactional
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){.....}
}
TheaboveexamplelistingshowsthattheFixedDepositServiceclassdoesn’timplementorextendfrom
any Spring-specific interface or class to use Spring’s 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 doesn’t
require your application objects to be dependent upon Spring-specific classes or interfaces. Also, you
don’tneedtodirectlyworkwithtransactionmanagementAPIstomanagetransactions.
Security
Security is an important aspect of any Java application. Spring Security
(http://static.springsource.org/spring-security/site/) is a SpringSource’s project that is built on top of
SpringFramework.SpringSecurityprovidesauthenticationandauthorizationfeaturesthatyoucanusefor
securingJavaapplications.
Let’s say that the following 3 user roles have been identified for the MyBank application:
LOAN_CUSTOMER, SAVINGS_ACCOUNT_CUSTOMER and APPLICATION_ADMIN. A customer
mustbeassociatedwiththeSAVINGS_ACCOUNT_CUSTOMERortheAPPLICATION_ADMINroleto
invokethecreateFixedDepositmethod of FixedDepositService class (refer example listing 1-6). Using
Spring Security youcan easily address this requirementby annotating createFixedDeposit method with
SpringSecurity’s@Securedannotation,asshowninthefollowingexamplelisting:
Examplelisting1-7–SecuredcreateFixedDepositmethod

importorg.springframework.transaction.annotation.Transactional;
importorg.springframework.security.access.annotation.Secured;
publicclassFixedDepositService{
publicFixedDepositDetailsgetFixedDepositDetails(.....){.....}
@Transactional
@Secured({"SAVINGS_ACCOUNT_CUSTOMER","APPLICATION_ADMIN"})
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){.....}
}
If you annotate a method with Spring Security’s @Secured annotation, security feature is transparently
applied to the method by the Spring Security framework. The above example listing shows that for
implementingmethod-levelsecurityyoudon’tneedtoextendorimplementanySpring-specificclassesor
interfaces.Also,youdon’tneedtowritesecurity-relatedcodeinyourbusinessmethods.
SpringSecurityframeworkisdiscussedindetailinchapter14.
JMX(JavaManagementExtensions)
Spring’sJMXsupportsimplifiesincorporatingJMXtechnologyinyourapplications.
Let’ssaythatthefixeddepositfacilityofMyBankapplicationshouldonlybeavailabletocustomersfrom
9:00 AM to 6:00 PM everyday. To address this requirement, a variable is added to the
FixedDepositServiceclass,whichactsasaflagindicatingwhetherthefixeddepositserviceisactiveor
inactive.ThefollowingexamplelistingshowstheFixedDepositServiceclassthatusessuchaflag:
Examplelisting1-8–FixedDepositServicewithactivevariable
publicclassFixedDepositService{
privatebooleanactive;
publicFixedDepositDetailsgetFixedDepositDetails(.....){
if(active){.....}
}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
if(active){.....}
}
publicvoidactivateService(){
active=true;
}
publicvoiddeactivateService(){
active=false;
}
}
TheaboveexamplelistingshowsthatavariablenamedactiveisaddedtotheFixedDepositServiceclass.

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.TheactivateServiceanddeactivateServicemethodssetthevalueofactivevariabletotrueand
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
ManagementExtensions)APItoremotelyinteractwithFixedDepositServiceinstance.
NOTE Refer to the following article to learn more about JMX:
http://docs.oracle.com/javase/tutorial/jmx/index.html.
AsBankAppSchedulerusesJMXtochangethevalueoftheactivevariableoftheFixedDepositService
instance,youneedtoregistertheFixedDepositServiceinstanceasamanagedbean(orMBean)withan
MBean server, and expose FixedDepositService’s activateService and deactivateService methods as
JMXoperations.InSpring,youregisterinstancesofaclasswiththeMBeanserverbyannotatingtheclass
withSpring’s @ManagedResource annotation, and expose the methods of the class as JMX operations
usingSpring’s@ManagedOperationannotation.
Thefollowingexamplelistingshowsusageof@ManagedResourceand@ManagedOperationannotations
to register instances of the FixedDepositService class with the MBean server, and to expose its
activateServiceanddeactivateServicemethodsasJMXoperations:
Examplelisting1-9–FixedDepositServiceclassthatusesSpring’sJMXsupport
importorg.springframework.jmx.export.annotation.ManagedOperation;
importorg.springframework.jmx.export.annotation.ManagedResource;
@ManagedResource(objectName="fixed_deposit_service:name=FixedDepositService")
publicclassFixedDepositService{
privatebooleanactive;
publicFixedDepositDetailsgetFixedDepositDetails(.....){
if(active){.....}
}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
if(active){.....}
}
@ManagedOperation
publicvoidactivateService(){
active=true;
}
@ManagedOperation

publicvoiddeactivateService(){
active=false;
}
}
The above example listing shows that the FixedDepositService class doesn’t directly use JMX API to
registeritsinstanceswiththeMBeanserverandtoexposeitsmethodsasJMXoperations.
JMS(JavaMessageService)
Spring’sJMSsupportsimplifiessendingandreceivingmessagesfromJMSproviders.
InMyBankapplication,whenacustomersubmitsarequesttoreceivedetailsoftheirfixeddepositsvia
email, the FixedDepositService sends the request details to a JMS messaging middleware (like
ActiveMQ).Therequestislaterprocessedbyamessagelistener.SpringsimplifiesinteractionwithJMS
providers by providing a layer of abstraction. The following example listing shows how
FixedDepositServiceclasssendsrequestdetailstoaJMSproviderusingSpring’sJmsTemplate:
Examplelisting1-10–FixedDepositServicethatsendsJMSmessages
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.jms.core.JmsTemplate;
publicclassFixedDepositService{
@Autowired
privatetransientJmsTemplatejmsTemplate;
.....
publicbooleansubmitRequest(Requestrequest){
jmsTemplate.convertAndSend(request);
}
}
TheaboveexamplelistingshowsthattheFixedDepositServicedefinesavariableoftypeJmsTemplate,
andisannotatedwithSpring’s@Autowiredannotation.Fornow,youcanassumethatthe@Autowired
annotationprovidesaccesstoaJmsTemplateinstance.TheJmsTemplateinstanceknowsabouttheJMS
destinationtowhichtheJMSmessageistobesent.HowtheJmsTemplateisconfiguredisdescribedin
detail in chapter 8. The FixedDepositService’s submitRequest method invokes JmsTemplate’s
convertAndSend method to send request details (represented by Request argument of submitRequest
method)asaJMSmessagetotheJMSprovider.
Onceagain,theaboveexamplelistingshowsthatifyouareusingSpringFrameworktosendmessagesto
JMSproviders,thenyoudon’tneedtodirectlydealwithJMSAPI.
Caching
Spring’scacheabstractionprovidesaconsistentapproachtousecachinginyourapplication.
It’scommontousecachingsolutionstoimprovetheperformanceofanapplication.MyBankapplication
usesacachingproducttoimprovetheperformanceofreadoperationsforfixeddepositdetails.Spring
Frameworksimplifiesinteractingwithdifferentcachingsolutionsbyabstractingcaching-relatedlogic.

ThefollowingexamplelistingshowsthattheFixedDepositService’sgetFixedDepositDetailsmethoduses
Spring’scacheabstractionfeaturetocachefixeddepositdetails:
Examplelisting1-11–FixedDepositServicethatcachesfixeddepositdetails
importorg.springframework.cache.annotation.Cacheable;
publicclassFixedDepositService{
@Cacheable("FixedDeposits")
publicFixedDepositDetailsgetFixedDepositDetails(.....){.....}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){.....}
}
In the above example listing, Spring’s @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
fixeddepositdetailsarereturnedfromthecache.ThisshowsthatifyouareusingSpringFrameworkyou
don’tneedtowritecaching-relatedlogicinyourclasses.Spring’scacheabstractionisexplainedindetail
inchapter8.
In this section, we saw that Spring Framework simplifies developing enterprise applications by
transparentlyprovidingservicestoPOJOs,thereby shieldingdevelopersfrom lowerlevelAPIdetails.
Spring also provides easy integration with standard frameworks, like Hibernate, iBATIS, Quartz, JSF,
Struts,EJB,andsoon,whichmakesSpringanidealchoiceforenterpriseapplicationdevelopment.
Now,thatwehavelookedatsomeofthebenefitsofusingSpringFramework,let’stakealookathowto
developasimpleSpringapplication.

1-5AsimpleSpringapplication
Inthissection,we’lllookatasimpleSpringapplicationthatusesSpring’sDIfeature.TouseSpring’sDI
featureinanapplication,followthesesteps:
1.identifyapplicationobjectsandtheirdependencies
2.createPOJOclassescorrespondingtotheapplicationobjectsidentifiedinstep1
3.createconfigurationmetadatathatdepictsapplicationobjectsandtheirdependencies
4.createaninstanceofSpringIoCcontainerandpasstheconfigurationmetadatatoit
5.accessapplicationobjectsfromtheSpringIoCcontainerinstance
Let’snowlookatabovementionedstepsinthecontextofMyBankapplication.
Identifyingapplicationobjectsandtheirdependencies
WediscussedearlierthattheMyBankapplicationshowsaformforcreatingafixeddeposit(referfigure
1-3) to its users for creating a fixed deposit. The following sequence diagram shows the application
objects(andtheirinteraction)thatcomeintopicturewhentheusersubmitstheform:
Figure1-4MyBank’sapplicationobjectsandtheirdependencies
In the above sequence diagram, FixedDepositController represents a web controller that receives the
requestwhentheformissubmitted.ThefixeddepositdetailsarecontainedintheFixedDepositDetails
object.TheFixedDepositController invokes the createFixedDeposit method of FixedDepositService (a
servicelayerobject).Then,FixedDepositServiceinvokesFixedDepositDaoobject(adataaccessobject)
to save the fixed deposit details in the application’s data store. So, we can interpret from the above
diagram that FixedDepositService is a dependency of FixedDepositController object, and
FixedDepositDaoisadependencyofFixedDepositServiceobject.
IMPORT chapter 1/ch01-bankapp-xml (This project shows a simple Spring application that uses
Spring’s DI feature. To run the application, execute the main method of the MyBankApp class of this
project)
CreatingPOJOclassescorrespondingtoidentifiedapplicationobjects
Onceyouhaveidentifiedapplicationobjects,thenextstep istocreatePOJOclassescorresponding to
these application objects. POJO classes corresponding to the FixedDepositController,

FixedDepositService and FixedDepositDao application objects are available in ch01-bankapp-xml
project.Thech01-bankapp-xmlprojectrepresentsasimplifiedversionofMyBankapplicationthatuses
Spring’sDIfeature.Youshouldimportthech01-bankapp-xmlprojectintoyourIDEasintheremaining
stepswe’llbelookingatthefilescontainedinthisproject.
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(adependencyofFixedDepositController)ispassedasasettermethodargumentto
theFixedDepositControllerobject:
Examplelisting1-12–FixedDepositControllerclass
Project–ch01-bankapp-xml
Sourcelocation-src/main/java/sample/spring/chapter01/bankapp
packagesample.spring.chapter01.bankapp;
.....
publicclassFixedDepositController{
.....
privateFixedDepositServicefixedDepositService;
.....
publicvoidsetFixedDepositService(FixedDepositServicefixedDepositService){
logger.info("SettingfixedDepositServiceproperty");
this.fixedDepositService=fixedDepositService;
}
.....
publicvoidsubmit(){
fixedDepositService.createFixedDeposit(newFixedDepositDetails(1,10000,
365,"someemail@something.com"));
}
.....
}
In the above example listing, FixedDepositService dependency is passed to FixedDepositController
throughsetFixedDepositServicemethod.We’llsoonseethatthesetFixedDepositServicesettermethodis
invokedbySpring.
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-specificclass.
Let’s now look at how application objects and their dependencies are specified in the configuration
metadata.
Creatingtheconfigurationmetadata
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’llfirstlookatwhatotherinformationiscontainedintheconfiguration

metadata,followedbyanin-depthlookathowconfigurationmetadataisspecifiedinXMLformat.
The configuration metadata specifies information about the enterprise services (like transaction
management,securityandremoteaccess)thatarerequiredbytheapplication.Forinstance,ifyouwant
Spring to manage transactions, you need to configure an implementation of Spring’s
PlatformTransactionManager interface in the configuration metadata. The PlatformTransactionManager
implementation is responsible for managing transactions (refer chapter 7 to know more about Spring’s
transactionmanagementfeature).
Ifyourapplicationinteractswithmessagingmiddlewares(likeActiveMQ),databases(likeMySQL),e-
mailservers,andsoon,thenSpring-specificobjectsthatsimplifyinteractingwiththeseexternalsystems
arealsodefinedintheconfigurationmetadata.Forinstance,ifyourapplicationsendsorreceivesJMS
messages from ActiveMQ, then you can configure Spring’s JmsTemplate class in the configuration
metadata to simplify interaction with ActiveMQ. We saw in example listing 1-10 that if you use
JmsTemplateforsendingmessagestoaJMSprovider,thenyoudon’tneedtodealwithlower-levelJMS
API(referchapter8toknowmoreaboutSpring’ssupportforinteractingwithJMSproviders).
YoucansupplytheconfigurationmetadatatotheSpringcontainerviaanXMLfileorthroughannotations
inPOJOclasses.StartingwithSpring3.0,youcanalsosupplytheconfigurationmetadatatotheSpring
containerthroughJavaclassesannotatedwithSpring’s@Configurationannotation.Inthissection,we’ll
seehow configurationmetadata is specifiedinXMLformat.In chapter 6,we’ll see how configuration
metadataissuppliedviaannotationsinPOJOclassesandthrough@ConfigurationannotatedJavaclasses.
You provide the configuration metadata for an application in XML format by creating an application
contextXMLfilethatcontainsinformationabouttheapplicationobjectsandtheirdependencies.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
witheachother):
Examplelisting1-13–applicationContext.xml-MyBank’sapplicationcontextXMLfile
Project–ch01-bankapp-xml
Sourcelocation-src/main/resources/META-INF/spring
<?xmlversion="1.0"encoding="UTF-8"standalone="no"?>
<beansxmlns="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">
<beanid="controller"
class="sample.spring.chapter01.bankapp.FixedDepositController">
<propertyname="fixedDepositService"ref="service"/>
</bean>
<beanid="service"class="sample.spring.chapter01.bankapp.FixedDepositService">
<propertyname="fixedDepositDao"ref="dao"/>

</bean>
<beanid="dao"class="sample.spring.chapter01.bankapp.FixedDepositDao"/>
</beans>
ThefollowingaretheimportantpointstonoteabouttheapplicationcontextXMLfileshownabove:
·The<beans>elementistherootelementoftheapplicationcontextXMLfile,andisdefinedin
spring-beans-4.0.xsdschema(alsoreferredtoasSpring’sbeansschema).Thespring-beans-4.0.xsd
schema is contained in spring-beans-4.0.0.RELEASE.jar JAR file that comes with the Spring
Frameworkdistribution.
·Each<bean>elementconfiguresanapplicationobjectthatismanagedbytheSpringcontainer.In
SpringFramework’sterminology,a<bean>elementrepresentsabeandefinition.Theobjectthat
theSpringcontainercreatesbasedonthebeandefinitionisreferredtoasabean.Theidattribute
specifiesauniquenameforthebean,andtheclassattributespecifiesthefully-qualifiedclassname
ofthebean.Youcanalsousethenameattributeof<bean>elementtospecifyaliasesforthebean.
InMyBankapplication,theapplicationobjectsareFixedDepositController, FixedDepositService
andFixedDepositDao;therefore,wehave3<bean>elements-oneforeachapplicationobject.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.
Insteadofdirectlycreatinginstancesofapplicationobjectsdefinedby<bean>elements,youshould
obtainthemfromtheSpringcontainer.Laterinthissection,we’lllookathowtoobtainapplication
objectsmanagedbySpringcontainer.
· No<bean>element is defined corresponding to the FixedDepositDetails domain object of
MyBank application. This is because domain objects are not typically managed by the Spring
container;theyarecreatedbytheORMframework(likeHibernate)usedbytheapplication,oryou
createthemprogrammaticallyusingthenewoperator.
· The <property> element specifies a dependency (or a configuration property) of the bean
configuredbythe<bean>element.The<property>elementcorrespondstoaJavaBean-stylesetter
method in the bean class which is invoked by the Spring container to set a dependency (or a
configurationproperty)ofthebean.
Let’snowlookathowdependenciesareinjectedviasettermethods.
Injectingdependenciesviasettermethods
To understand how dependencies are injected via setter methods defined in the bean class, let’s once
againlookattheFixedDepositControllerclassofMyBankapplication:
Examplelisting1-14–FixedDepositControllerclass
Project–ch01-bankapp-xml
Sourcelocation-src/main/java/sample/spring/chapter01/bankapp
packagesample.spring.chapter01.bankapp;

importorg.apache.log4j.Logger;
publicclassFixedDepositController{
privatestaticLoggerlogger=Logger.getLogger(FixedDepositController.class);
privateFixedDepositServicefixedDepositService;
publicFixedDepositController(){
logger.info("initializing");
}
publicvoidsetFixedDepositService(FixedDepositServicefixedDepositService){
logger.info("SettingfixedDepositServiceproperty");
this.fixedDepositService=fixedDepositService;
}
.....
}
The above example listing shows that the FixedDepositController class declares an instance variable
namedfixedDepositServiceoftypeFixedDepositService.ThefixedDepositServicevariableissetbythe
setFixedDepositServicemethod-aJavaBean-stylesettermethodforfixedDepositServicevariable.This
isanexampleofsetter-basedDI,whereinasettermethodsatisfiesadependency.
The following figure describes the bean definition for the FixedDepositController class in the
applicationContext.xmlfile(referexamplelisting1-13):
Figure1-5Definingdependenciesusing<property>elements
The above bean definition shows that the FixedDepositController bean defines its dependence on
FixedDepositServicebeanvia<property>element.The<property>element’snameattributecorresponds
totheJavaBean-stylesettermethodinthebeanclassthatisinvokedbytheSpringcontaineratthetimeof
beancreation.The<property>element’srefattributeidentifiestheSpringbeanwhoseinstanceneedsto
becreatedandpassedtotheJavaBean-stylesettermethod.Thevalueofrefattributemustmatchtheid
attribute’s value (or one of the names specified by the name attribute) of a <bean> element in the
configurationmetadata.
Infigure1-5,thevalueof<property>element’snameattributeisfixedDepositService,whichmeansthat

the <property> element corresponds to the setFixedDepositService setter method of
FixedDepositController class (refer example listing 1-14). As the value of <property> element’s ref
attribute is service, the <property> element refers to the <bean> element whose id attribute’s value is
service.Now,the<bean>elementwhoseidattribute’svalueisserviceistheFixedDepositServicebean
(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
FixedDepositServiceinstance.
InthecontextofFixedDepositControllerapplicationobject,thefollowingfiguresummarizesthepurpose
ofnameandrefattributesof<property>element:
Figure 1-6 <property> element’s name attribute corresponds to a JavaBean-style setter method that
satisfiesabeandependency,andrefattributereferstoanotherbean.
The above figure shows that fixedDepositService value of name attribute corresponds to the
setFixedDepositServicemethodofFixedDepositControllerclass,andservicevalueofrefattributerefers
tothebeanwhoseidisservice.
NOTEItisfairlycommontorefertoabeandefinitionbyitsname(whichisidattribute’svalue)ortype
(whichisclassattribute’svalue)ortheinterfaceimplementedbythebeanclass.Forinstance,youcan
refer to ‘FixedDepositController bean’ as ‘controller bean’. And, if the FixedDepositController class
implements FixedDepositControllerIntf interface, you can refer to ‘FixedDepositController bean’ as
‘FixedDepositControllerIntfbean’.
ThefollowingdiagramsummarizeshowtheSpringcontainercreatesbeansandinjectstheirdependencies
basedontheconfigurationmetadatasuppliedbytheapplicationContext.xmlfile(referexamplelisting1-
13)ofMyBankapplication:

Figure1-7-ThesequenceinwhichSpringIoCcontainercreatesbeansandinjectstheirdependencies.
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
dependentonFixedDepositServicebean;therefore,SpringcontainerconfigurestheFixedDepositService
beanbeforeinvokingthesetFixedDepositServicemethodofFixedDepositControllerbean.
The bean definitions that we have seen so far, instruct Spring container to create bean instances by
invokingtheno-argumentconstructorofthebeanclass,andinjectdependenciesusingsetter-basedDI.In
chapter 2, we’ll look at bean definitions that instruct Spring container to create a bean instance via a
factorymethod defined in a class. Also, we’ll look at how to inject dependencies through constructor
arguments(referredtoasconstructor-basedDI),throughargumentstothefactorymethodthatcreatesthe
beaninstance,andbyusingsetter-basedDIonthebeaninstancereturnedbythefactorymethod.
Let’snowlookathowtocreateaninstanceofSpringcontainerandpassconfigurationmetadatatoit.
CreatinganinstanceofSpringcontainer
Spring’s 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 for standalone 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 for web applications in which configuration
metadataissuppliedthroughJavacode,andsoon.

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
contextXMLfilefromthespecifiedclasspathlocation,andtheFileSystemXmlApplicationContextclass
loadsanapplicationcontextXMLfilefromthespecifiedlocationonthefilesystem.
The following BankApp class of MyBank application shows that an instance of Spring container is
createdusingtheClassPathXmlApplicationContextclass:
Examplelisting1-15–BankAppclass
Project–ch01-bankapp-xml
Sourcelocation-src/main/java/sample/spring/chapter01/bankapp
packagesample.spring.chapter01.bankapp;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassBankApp{
.....
publicstaticvoidmain(Stringargs[]){
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
.....
}
}
TheaboveexamplelistingshowstheBankApp’smainmethod,whichisresponsibleforbootstrappingthe
Springcontainer.TheclasspathlocationoftheapplicationcontextXMLfileispassedtotheconstructor
of ClassPathXmlApplicationContext class. The creation of ClassPathXmlApplicationContext instance
resultsincreationofthosebeansintheapplicationcontextXMLfilethataresingleton-scopedandsetto
bepre-instantiated.Inchapter 2,we’ll discussbean scopes, andwhatitmeanstohave 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
ClassPathXmlApplicationContextiscreated.
Now,thatwehaveseenhowtocreateaninstanceoftheSpringcontainer,let’slookathowtoretrieve
beaninstancesfromtheSpringcontainer.
AccessbeansfromtheSpringcontainer
Theapplicationobjectsdefinedvia<bean>elementsarecreatedandmanagedbytheSpringcontainer.
You can access instances of these application objects by calling one of the getBean methods of the
ApplicationContextinterface.
The following example listing shows the main method of BankApp class that retrieves an instance of
FixedDepositControllerbeanfromtheSpringcontainerandinvokesitsmethods:

Examplelisting1-16–BankAppclass
Project–ch01-bankapp-xml
Sourcelocation-src/main/java/sample/spring/chapter01/bankapp
packagesample.spring.chapter01.bankapp;
importorg.apache.log4j.Logger;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassBankApp{
privatestaticLoggerlogger=Logger.getLogger(BankApp.class);
publicstaticvoidmain(Stringargs[]){
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
FixedDepositControllerfixedDepositController=
(FixedDepositController)context.getBean("controller");
logger.info("Submissionstatusoffixeddeposit:"+fixedDepositController.submit());
logger.info("Returnedfixeddepositinfo:"+fixedDepositController.get());
}
}
At first, the ApplicationContext’s getBean method is invoked to retrieve an instance of
FixedDepositController bean from the Spring container, followed by invocation of submit and get
methodsofFixedDepositControllerbean.TheargumentpassedtothegetBeanmethodisthenameofthe
beanwhoseinstanceyouwanttoretrievefromtheSpringcontainer.Thenameofthebeanpassedtothe
getBeanmethodmustbethevalueoftheidornameattributeofthebeanthatyouwanttoretrieve.Ifno
bean with the specified name is registered with the Spring container, an exception is thrown by the
getBeanmethod.
In example listing 1-16, to configure the FixedDepositController instance, we didn’t programmatically
createaninstanceofFixedDepositService and set it on the FixedDepositController instance. Also, we
didn’t create an instance of FixedDepositDao and set it on the FixedDepositService instance. This is
becausethetaskofcreatingdependencies,andinjectingthemintothethedependentobjectsishandledby
theSpringcontainer.
If you go to ch01-bankapp-xml project and execute the main method of BankApp class, you’ll see the
followingoutputontheconsole:
INFOsample.spring.chapter01.bankapp.FixedDepositController-initializing
INFOsample.spring.chapter01.bankapp.FixedDepositService-initializing
INFOsample.spring.chapter01.bankapp.FixedDepositDao-initializing
INFOsample.spring.chapter01.bankapp.FixedDepositService-SettingfixedDepositDaoproperty
INFOsample.spring.chapter01.bankapp.FixedDepositController-SettingfixedDepositServiceproperty
INFOsample.spring.chapter01.bankapp.BankApp-Submissionstatusoffixeddeposit:true

INFOsample.spring.chapter01.bankapp.BankApp-Returnedfixeddepositinfo:id:1,depositamount: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.xmlfileofMyBankapplication.Also,Springcontainerusessetter-basedDItoinject
an instance of FixedDepositService into FixedDepositController instance, and an instance of
FixedDepositDaointotheFixedDepositServiceinstance.
Let’snowlookatsomeoftheframeworksthatarebuiltontopofSpringFramework.

1-6FrameworksbuiltontopofSpring
Though there are many frameworks from SpringSource that use Spring Framework as the foundation,
we’lllook atsomeofthewidelypopular ones.Foramorecomprehensivelistofframeworks,andfor
moredetailsaboutanindividualframework,it’srecommendedthatyouvisittheSpringSourcewebsite
(www.springsource.org).
Thefollowingtableprovidesahigh-leveloverviewoftheframeworksfromSpringSourcethatarebuilt
ontopofSpringFramework:
Framework Description
SpringSecurity
Authenticationandauthorizationframeworkforenterpriseapplications.Youneedto
configure a few beans in your application context XM L file to incorporate
authenticationandauthorizationfeaturesintoyourapplication.
SpringData
Provides a consistent programming model to interact with different types of
databases.Forinstance,youcanuseittointeractwithnon-relationaldatabases,like
MongoDBorNeo4j,andyoucanalsouseitforaccessingrelationaldatabasesusing
JPA.
SpringBatch Ifyourapplicationrequiresbulkprocessing,thisframeworkisforyou.
SpringIntegration ProvidesEnterpriseApplicationIntegration(EAI)capabilitiestoapplications.
SpringSocial If your application requires interaction with social media websites, like Facebook
andTwitter,thenyou’llfindthisframeworkhighlyuseful.
SpringBlazeDS
Integration
IfyouaredevelopinganAdobeFlexbasedapplication,youcanusethisframework
toconnectFlexfrontendwithSpring-basedbusinesstier.
AstheframeworksmentionedintheabovetablearebuiltontopofSpringFramework,beforeusingany
oftheseframeworksmakesurethattheyarecompatiblewiththeSpringFrameworkversionthatyouare
using.
1-7Summary
Inthischapter,welookedatthebenefitsofusingSpringFramework.WealsolookedatasimpleSpring
applicationthatshowedhowtospecifyconfigurationmetadatainXMLformat,createtheSpringcontainer
instanceandretrievebeansfromit.Inthenextchapter,we’lllookatsomeofthefoundationconceptsof
SpringFramework.

Chapter2–SpringFrameworkbasics
2-1Introduction
Inthepreviouschapter,wesawthattheSpringcontainerinvokestheno-argumentconstructorofabean
classtocreateabeaninstance,andsetter-basedDIisusedtosetbeandependencies.Inthischapter,we’ll
goastepfurtherandlookat:
§Spring’ssupportfor‘programmingtointerfaces’designprinciple
§differentapproachestoinstantiatingSpringbeans
§constructor-basedDIforpassingbeandependenciesasconstructorarguments
§constructor-andsetter-basedDIforpassingsimpleStringvaluestobeans,and
§beanscopes
Let’s begin this chapter with looking at how Spring improves testability of applications by supporting
‘programmingtointerfaces’designprinciple.

2-2Programmingtointerfacesdesignprinciple
Insection1-5ofchapter1,wesawthatadependentPOJOclasscontainedreferencetotheconcreteclass
of the dependency. For example, the FixedDepositController class contained reference to the
FixedDepositService class, and the FixedDepositService class contained reference to the
FixedDepositDaoclass.Ifadependentclasshasdirectreferencetotheconcreteclassofthedependency,
it results in tight coupling between the classes. This means that if you want to substitute a different
implementationofthedependency,it’drequirechangingthedependentclass.
Let’snowlookatascenarioinwhichadependentclasscontainsdirectreferencetotheconcreteclassof
thedependency.
Scenario:Dependentclasscontainsreferencetotheconcreteclassofdependency
Let’s 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,
whichusesHibernateORMfordatabaseinteraction.Now,toswitchfromplainJDBCtoHibernateORM
implementation,you’llneedtochangeFixedDepositServiceclasstouseFixedDepositHibernateDaoclass
insteadofFixedDepositDao,asshowninthefollowingexamplelisting:
Examplelisting2-1–FixedDepositServiceclass
publicclassFixedDepositService{
privateFixedDepositHibernateDaofixedDepositDao;
publicvoidsetFixedDepositDao(FixedDepositHibernateDaofixedDepositDao){
this.fixedDepositDao=fixedDepositDao;
}
publicFixedDepositDetailsgetFixedDepositDetails(longid){
returnfixedDepositDao.getFixedDepositDetails(id);
}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
returnfixedDepositDao.createFixedDeposit(fixedDepositDetails);
}
}
The above example listing shows that reference to FixedDepositDao class was replaced by
FixedDepositHibernateDaosothatHibernateORMcanbeusedfordatabaseinteraction.Thisshowsthat
if a dependent class refers to the concrete implementation class of the dependency, then substituting a
differentimplementationrequireschangesinthedependentclass.
Let’snowlookatascenarioinwhichadependentclasscontainsreferencetotheinterfaceimplemented
bythedependency.

Scenario:Dependentclasscontainsreferencetotheinterfaceimplementedbythe
dependency
WeknowthataJavainterfacedefinesacontracttowhichtheimplementationclassesconform.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’.Theinterfaceimplementedbythedependencyclassisreferredtoasadependencyinterface.
Asitisagooddesignpracticeto‘programtointerfaces’thanto‘programtoclasses’,thefollowingclass
diagramshowsthatitisagooddesignifABeanclassdependsonBBeaninterfaceandnotonBBeanImpl
classthatimplementsBBeaninterface:
Figure2-1-‘Programtointerfaces’isagooddesignpracticethanto‘programtoclasses’
The following class diagram shows how FixedDepositService class can make use of ‘programming to
interfaces’designapproachtoeasilyswitchthestrategyusedfordatabaseinteraction:
Figure2-2–TheFixedDepositServicedependsonFixedDepositDaointerface,whichisimplementedby
FixedDepositJdbcDaoandFixedDepositHibernateDaoclasses.
The above figure shows that the FixedDepositService class is not directly dependent on the
FixedDepositJdbcDaoorFixedDepositHibernateDaoclass.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
FixedDepositHibernateDaototheFixedDepositServiceinstance.
As FixedDepositService depends on FixedDepositDao interface, you can support other database
interactionstrategies inthe future. Let’s say that you decidetouse 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
FixedDepositServiceinstance.
Sofarwehaveseenthat‘programmingtointerfaces’designapproachresultsinloosecouplingbetweena
dependentclassanditsdependencies.Let’snowlookathowthisdesignapproachimprovestestabilityof
thedependentclasses.
Improvedtestabilityofdependentclasses
In figure 2-2, we saw that the FixedDepositService class holds reference to the FixedDepositDao
interface.FixedDepositJdbcDaoandFixedDepositHibernateDaoareconcreteimplementationclassesof
FixedDepositDaointerface.Now,tosimplifyunittestingofFixedDepositServiceclass,youcansubstitute
amockimplementationofFixedDepositDaointerfacethatdoesn’trequireadatabase.
If the FixedDepositService class had direct reference to FixedDepositJdbcDao or
FixedDepositHibernateDao class, testing FixedDepositService class would have required setting up a
databasefortestingpurposes.Thisshowsthatbyusingamockimplementationofdependencyinterface,
youcansavetheefforttosetuptheinfrastructureforunittestingyourdependentclasses.
Let’snowseehowSpringsupports‘programmingtointerfaces’designapproachinapplications.
Spring’ssupportfor‘programmingtointerfaces’designapproach
Touse‘programmingtointerfaces’designapproach inyour Springapplication,youneedtoensurethe
followingthings:
§the<bean>elementsintheconfigurationmetadataspecifytheconcreteclassesofthedependency
§thedependentbean classes refer tothedependency interface insteadof the concrete class ofthe
dependency
Let’s 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’
designapproachisusedincreatingSpringapplications.Toruntheapplication,executethemainmethod
oftheBankAppclassofthisproject)
MyBankapplicationthatuses‘programmingtointerfaces’designapproach

The following class diagram depicts the modified MyBank application that uses ‘programming to
interfaces’designapproach:
Figure2-3-MyBankapplicationthatuses‘programtointerfaces’designapproach
Theabovefigureshowsthatadependentclassdependsontheinterfaceimplementedbythedependency,
and not on the concrete implementation class of the dependency. For instance, the
FixedDepositControllerImpl class depends on the FixedDepositService interface, and the
FixedDepositServiceImplclassdependsontheFixedDepositDaointerface.
ThefollowingexamplelistingshowstheFixedDepositServiceImpl class based onthedesignshownin
figure2-3:
Examplelisting2-2–FixedDepositServiceclass
Project–ch02-bankapp-interfaces
Sourcelocation-src/main/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
privateFixedDepositDaofixedDepositDao;
.....
publicvoidsetFixedDepositDao(FixedDepositDaofixedDepositDao){
this.fixedDepositDao=fixedDepositDao;
}
publicFixedDepositDetailsgetFixedDepositDetails(longid){
returnfixedDepositDao.getFixedDepositDetails(id);
}
publicbooleancreateFixedDeposit(FixedDepositDetailsfdd){
returnfixedDepositDao.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
FixedDepositServiceImplinstanceisspecifiedintheapplicationcontextXMLfile.Asshowninfigure2-
3, you can inject any one of the following concrete implementations of FixedDepositDao interface:
FixedDepositIbatisDao,FixedDepositJdbcDaoandFixedDepositHibernateDao.
ThefollowingexamplelistingshowstheapplicationContext.xmlfilethat caters tothe design shown in
figure2-3:
Examplelisting2-3–applicationContext.xml-MyBank’sapplicationcontextXMLfile
Project–ch02-bankapp-interfaces
Sourcelocation-src/main/resources/META-INF/spring
<?xmlversion="1.0"encoding="UTF-8"standalone="no"?>
<beans.....>
<beanid="controller"
class="sample.spring.chapter02.bankapp.controller.FixedDepositControllerImpl">
<propertyname="fixedDepositService"ref="service"/>
</bean>
<beanid="service"class="sample.spring.chapter02.bankapp.service.FixedDepositServiceImpl">
<propertyname="fixedDepositDao"ref="dao"/>
</bean>
<beanid="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
decidetouseiBATISinsteadofHibernateforpersistence,thenallyouneedtodoistochangetheclass
attributeofthedaobeandefinitionintheapplicationContext.xmlfiletorefertothefully-qualifiednameof
theFixedDepositIbatisDaoclass.
Let’snowlookatdifferentwaysinwhichSpringcontainercaninstantiatebeans.

2-3DifferentapproachestoinstantiatingSpringbeans
SofarwehaveseenbeandefinitionexamplesthatinstructSpringcontainertocreatebeaninstancesby
invokingtheno-argumentconstructorofthebeanclass.Considerthefollowingbeandefinition:
<beanid=”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
classthatprovidesano-argumentconstructor.
NOTE It is important to note that the Spring container can create and manage instance of any class,
irrespectiveofwhethertheclassprovidesano-argumentconstructorornot.Insection2-4,we’lllookat
beandefinitionsinwhichtheconstructorofthebeanclassacceptsoneormorearguments.
Ifyouhaveanexistingprojectthatusesfactoryclassestocreateobjectinstances,youcanstilluseSpring
containertomanageobjectscreatedbythesefactories.Let’snowlookathowSpringcontainerinvokesa
staticoraninstancefactorymethodofaclasstomanagethereturnedobjectinstance.
Instantiatingbeansviastaticfactorymethods
Infigure2-3,wesawthattheFixedDepositDaointerfaceisimplementedbyFixedDepositHibernateDao,
FixedDepositIbatisDao and FixedDepositJdbcDao classes. The following example listing shows a
FixedDepositDaoFactoryclassthatdefinesastaticfactorymethodforcreatingandreturninganinstance
ofFixedDepositDaobasedontheargumentpassedtothestaticmethod:
Examplelisting2-4–FixedDepositDaoFactoryclass
publicclassFixedDepositDaoFactory{
privateFixedDepositDaoFactory(){}
publicstaticFixedDepositDaogetFixedDepositDao(StringdaoType){
FixedDepositDaofixedDepositDao=null;
if("jdbc".equalsIgnoreCase(daoType)){
fixedDepositDao=newFixedDepositJdbcDao();
}
if("hibernate".equalsIgnoreCase(daoType)){
fixedDepositDao=newFixedDepositHibernateDao();
}
.....
returnfixedDepositDao;
}
}
TheaboveexamplelistingshowsthattheFixedDepositDaoFactoryclassdefinesagetFixedDepositDao
staticmethodthatcreatesandreturnsaninstanceofFixedDepositJdbcDao,FixedDepositHibernateDao

orFixedDepositIbatisDaoclass,dependingonthevalueofthedaoTypeargument.
ThefollowingbeandefinitionfortheFixedDepositDaoFactoryclassinstructsSpringcontainertoinvoke
FixedDepositDaoFactory’sgetFixedDepositDao method to obtain an instance of FixedDepositJdbcDao
class:
Examplelisting2-5–BeandefinitionfortheFixedDepositDaoFactoryclass
<beanid="dao"class="sample.spring.FixedDepositDaoFactory"
factory-method="getFixedDepositDao">
<constructor-argindex=”0”value="jdbc"/>
</bean>
Intheabovebeandefinition,classattributespecifiesthefully-qualifiednameoftheclassthatdefinesthe
staticfactorymethod.Thefactory-methodattributespecifiesthenameofthestaticfactorymethodthatthe
SpringcontainerinvokestoobtainaninstanceofFixedDepositDaoobject.The<constructor-arg>element
is defined in Spring’s beansschema and is used for passing arguments to constructors, and static and
instancefactorymethods.Theindexattributereferstothelocationoftheargumentintheconstructor,orin
thestaticorinstancefactorymethod.Intheabovebeandefinition,thevalue0ofindexattributemeans
that the <constructor-arg> element is supplying value for the first argument, which is daoType, of the
getFixedDepositDaofactorymethod.Thevalueattributespecifiestheargumentvalue.Ifafactorymethod
acceptsmultiplearguments,youneedtodefinea<constructor-arg>elementforeachofthearguments.
ItisimportanttonotethatcallingApplicationContext’sgetBeanmethodtoobtaindaobean(referexample
listing 2-5) will result in invocation of the FixedDepositDaoFactory’s getFixedDepositDao factory
method. This means that calling getBean("dao") returns the FixedDepositDao instance created by the
getFixedDepositDaofactorymethod,andnotaninstanceofFixedDepositDaoFactoryclass.
Now,thatwehaveseentheconfigurationofthefactoryclassthatcreatesaninstanceofFixedDepositDao,
the following example listing shows how to inject an instance of FixedDepositDao into
FixedDepositServiceImplclass:
Examplelisting2-6–Injectingobjectinstancescreatedbystaticfactorymethod
<beanid="service"class="sample.spring.chapter02.bankapp.FixedDepositServiceImpl">
<propertyname=“fixedDepositDao"ref="dao"/>
</bean>
<beanid="dao"class="sample.spring.chapter02.basicapp.FixedDepositDaoFactory"
factory-method="getFixedDepositDao">
<constructor-argindex=”0”value="jdbc"/>
</bean>
In the above example listing, <property> element injects an instance of FixedDepositDao returned by
FixedDepositDaoFactory’sgetFixedDepositDao factory methodintoFixedDepositServiceImpl instance.
If you compare the bean definition for the FixedDepositServiceImpl class shown above with the one
shown in example listing 2-3, you’ll notice that they are exactly the same. This shows that the bean
dependencies are specifiedthe same way irrespective of how (using no-argumentconstructor or static

factorymethod)theSpringcontainercreatesbeaninstances.
Let’snowlookathowSpringcontainerinstantiatebeansbyinvokinganinstancefactorymethod.
Instantiatingbeansviainstancefactorymethods
ThefollowingexamplelistingshowstheFixedDepositDaoFactoryclassthatdefinesaninstancefactory
methodforcreatingandreturninganinstanceofFixedDepositDao:
Examplelisting2-7–FixedDepositDaoFactoryclass
publicclassFixedDepositDaoFactory{
publicFixedDepositDaoFactory(){
}
publicFixedDepositDaogetFixedDepositDao(StringdaoType){
FixedDepositDaoFixedDepositDao=null;
if("jdbc".equalsIgnoreCase(daoType)){
FixedDepositDao=newFixedDepositJdbcDao();
}
if(“hibernate”.equalsIgnoreCase(daoType)){
FixedDepositDao=newFixedDepositHiberateDao();
}
.....
returnfixedDepositDao;
}
}
Ifaclassdefinesaninstancefactorymethod,theclassmustdefineapublicconstructorsothattheSpring
containercancreateaninstanceofthatclass.Intheaboveexamplelisting,theFixedDepositDaoFactory
class defines a public no-argument constructor. The FixedDepositDaoFactory’s getFixedDepositDao
methodisaninstancefactorymethodthatcreatesandreturnsaninstanceofFixedDepositDao.
The following example listing shows how to instruct Spring container to invoke
FixedDepositDaoFactory’sgetFixedDepositDaomethodtoobtainaninstanceofFixedDepositDao:
Examplelisting2-8–ConfigurationtoinvokeFixedDepositDaoFactory’sgetFixedDepositDaomethod
<beanid="daoFactory"class="sample.spring.chapter02.basicapp.FixedDepositDaoFactory"/>
<beanid="dao"factory-bean="daoFactory"factory-method="getFixedDepositDao">
<constructor-argindex="0"value="jdbc"/>
</bean>
<beanid="service"class="sample.spring.chapter02.bankapp.FixedDepositServiceImpl">
<propertyname=“fixedDepositDao"ref="dao"/>
</bean>
TheaboveexamplelistingshowsthattheFixedDepositDaoFactoryclass(aclassthatcontainsinstance
factory method) is configured like a regular Spring bean, and a separate <bean> element is used to
configuretheinstancefactorymethoddetails.Toconfiguredetailsofaninstancefactorymethod,factory-
beanandfactory-methodattributesof<bean>elementareused.Thefactory-bean attribute referstothe
beanthatdefinestheinstancefactorymethod,andthefactory-methodattributespecifiesthenameofthe
instance factory method. In the above example listing, <property> element injects an instance of
FixedDepositDao returned by FixedDepositDaoFactory’s getFixedDepositDao factory method into
FixedDepositServiceImplinstance.
Aswithstaticfactorymethods,youcanpassargumentstoinstancefactorymethodsusing<constructor-
arg> element. It is important to note that invoking ApplicationContext’sgetBean method to obtain dao
bean in the above example listing will result in invocation of the FixedDepositDaoFactory’s
getFixedDepositDaofactorymethod.
So far we have looked at bean definition examples in which dependencies are injected into beans via
settermethods.Let’snowlookatdifferentDImechanismsthatyoucanuseforinjectingdependencies.

2-4Dependencyinjectiontechniques
In Spring, dependency injection is performed by passing arguments to a bean’s constructor and setter
methods.Ifyouareusingastaticorinstancefactorymethodtocreatebeaninstances,youcanpassbean
dependencies to the factory method or you can set them on the bean instance returned by the factory
method.
We’llnowlookatexamplesthatdemonstratedifferentDItechniques.
Setter-basedDI
Sofarinthisbook,we’veseenexamplesofsetter-basedDI.Insetter-basedDI,<property>elementsare
used to specify bean dependencies. The <property> element is also used to pass configuration
information(ifany)requiredbythebean.
Let’ssaythattheMyBankapplicationcontainsaPersonalBankingServiceservicethatallowscustomers
toretrievebankaccountstatement,checkbankaccountdetails,updatecontactnumber,changepassword,
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 toaccomplish it’s intended functionality. The following example listing
showsthePersonalBankingServiceclass:
Examplelisting2-9–PersonalBankingServiceclass
publicclassPersonalBankingService{
privateJmsMessageSenderjmsMessageSender;
privateEmailMessageSenderemailMessageSender;
privateWebServiceInvokerwebServiceInvoker;
.....
publicvoidsetJmsMessageSender(JmsMessageSenderjmsMessageSender){
this.jmsMessageSender=jmsMessageSender;
}
publicvoidsetEmailMessageSender(EmailMessageSenderemailMessageSender){
this.emailMessageSender=emailMessageSender;
}
publicvoidsetWebServiceInvoker(WebServiceInvokerwebServiceInvoker){
this.webServiceInvoker=webServiceInvoker;
}
.....
}
The above example listing shows that a setter method is defined for JmsMessageSender,
EmailMessageSenderandWebServiceInvokerdependenciesofPersonalBankingServiceclass.
We can use setter-based DI to inject the dependencies of the PersonalBankingService class, as shown
here:

Examplelisting2-10–BeandefinitionsforPersonalBankingServiceclassanditsdependencies
<beanid="personalBankingService"class="PersonalBankingService">
<propertyname="emailMessageSender"ref="emailMessageSender"/>
<propertyname="jmsMessageSender"ref="jmsMessageSender"/>
<propertyname="webServiceInvoker"ref="webServiceInvoker"/>
</bean>
<beanid="jmsMessageSender"class="JmsMessageSender">
.....
</bean>
<beanid="webServiceInvoker"class="WebServiceInvoker"/>
.....
</bean>
<beanid="emailMessageSender"class="EmailMessageSender"/>
.....
</bean>
The personalBankingService bean definition shows that a <property> element is specified for each
dependencyofPersonalBankingServiceclass.
PersonalBankingServiceusesEmailMessageSenderbeantosendanemailnotificationtothecustomer’s
emailaddressincasecustomerchangeshiscontactnumber.EmailMessageSenderrequiresemailserver
address, and username and password for authenticating with the email server. The following example
listingshowsthatthe<property>elementcanalsobeusedforsettingbeanpropertiesoftypeString:
Examplelisting2-11EmailMessageSenderclassandthecorrespondingbeandefinition
publicclassEmailMessageSender{
privateStringhost;
privateStringusername;
privateStringpassword;
.....
publicvoidsetHost(Stringhost){
this.host=host;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
.....
}

<beanid="emailMessageSender"class="EmailMessageSender">
<propertyname="host"value="smtp.gmail.com"/>
<propertyname="username"value="myusername"/>
<propertyname="password"value="mypassword"/>
</bean>
The above example listing shows that <property> elements have been used to set host, username and
passwordpropertiesofEmailMessageSenderbean.ThevalueattributespecifiestheStringvaluetobeset
for the bean property identified by the name attribute. The host, username and password properties
representconfigurationinformationrequiredbyEmailMessageSenderbean.Inchapter3,we’llseehow
the <property> element is used to set primitive type (like int, long, and so on), collection type (like
java.util.List,java.util.Map,andsoon)andcustomtype(likeAddress)properties.
Setter-based DI is also used to inject dependencies into beans created by static and instance factory
methods.Let’slookathowtousesetter-basedDIinconjunctionwithstaticandinstancefactorymethods.
Injectingdependenciesintobeaninstancescreatedbyfactorymethods
Youcanusesetter-basedDItoinjectdependenciesofthebeaninstancereturnedbyastaticorinstance
factorymethod.
ConsiderthefollowingFixedDepositJdbcDaoclassthatdefinesadatabaseInfoproperty:
Examplelisting2-12–FixedDepositJdbcDaoclass
publicclassFixedDepositJdbcDao{
privateDatabaseInfodatabaseInfo;
.....
publicFixedDepositJdbcDao(){}
publicvoidsetDatabaseInfo(DatabaseInfodatabaseInfo){
this.databaseInfo=databaseInfo;
}
.....
}
In the above example listing, the databaseInfo attribute represents a dependency of the
FixedDepositJdbcDaoclassthatisfulfilledbysetDatabaseInfomethod.
The following FixedDepositDaoFactory class defines a factory method responsible for creating and
returninganinstanceofFixedDepositDaoJdbcclass:
Examplelisting2-13–FixedDepositDaoFactoryclass
publicclassFixedDepositDaoFactory{
publicFixedDepositDaoFactory(){
}
publicFixedDepositDaogetFixedDepositDao(StringdaoType){

FixedDepositDaoFixedDepositDao=null;
if("jdbc".equalsIgnoreCase(daoType)){
FixedDepositDao=newFixedDepositJdbcDao();
}
if(“hibernate”.equalsIgnoreCase(daoType)){
FixedDepositDao=newFixedDepositHiberateDao();
}
.....
returnfixedDepositDao;
}
}
Intheaboveexamplelisting,thegetFixedDepositDaomethodisaninstancefactorymethodforcreating
FixedDepositDao instances. The getFixedDepositDao method creates an instance of
FixedDepositJdbcDaoinstanceifthevalueofdaoTypeargumentisjdbc.Itisimportanttonotethatthe
getFixedDepositDaomethoddoesn’tsetthedatabaseInfopropertyoftheFixedDepositJdbcDaoinstance.
Aswesawinexamplelisting2-8,thefollowingbeandefinitionsinstructSpringcontainertocreatean
instance of FixedDepositJdbcDao by invoking the getFixedDepositDao instance factory method of
FixedDepositDaoFactoryclass:
Examplelisting2-14–ConfigurationtoinvokeFixedDepositDaoFactory’sgetFixedDepositDaomethod
<beanid="daoFactory"class="FixedDepositDaoFactory"/>
<beanid="dao"factory-bean="daoFactory"factory-method="getFixedDepositDao">
<constructor-argindex="0"value="jdbc"/>
</bean>
ThedaobeandefinitionresultsininvocationofFixedDepositDaoFactory’sgetFixedDepositDaomethod,
which creates and returns an instance of FixedDepositJdbcDao. But, the FixedDepositJdbcDao’s
databaseInfopropertyisnotset.TosetthedatabaseInfodependency,youcanperformsetter-basedDIon
theFixedDepositJdbcDaoinstancereturnedbythegetFixedDepositDaomethod,asshownhere:
Examplelisting2-15–ConfigurationtoinvokeFixedDepositDaoFactory’sgetFixedDepositDaomethod
andsetdatabaseInfopropertyofreturnedFixedDepositJdbcDaoinstance
<beanid="daoFactory"class="FixedDepositDaoFactory"/>
<beanid="dao"factory-bean="daoFactory"factory-method="getFixedDepositDao">
<constructor-argindex="0"value="jdbc"/>
<propertyname="databaseInfo"ref="databaseInfo"/>
</bean>
<beanid="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
instancefactorymethod,youcanusethe<property>elementtoinjectdependenciesintothebeaninstance
returnedbythestaticfactorymethod.
Let’snowlookathowtoinjectbeandependenciesviaconstructorarguments.
Constructor-basedDI
Inconstructor-basedDI,dependenciesofabeanarepassedasargumentstothebeanclass’sconstructor.
For instance, the following example listing shows PersonalBankingService class whose constructor
acceptsJmsMessageSender,EmailMessageSenderandWebServiceInvokerobjects:
Examplelisting2-16–PersonalBankingServiceclass
publicclassPersonalBankingService{
privateJmsMessageSenderjmsMessageSender;
privateEmailMessageSenderemailMessageSender;
privateWebServiceInvokerwebServiceInvoker;
.....
publicPersonalBankingService(JmsMessageSenderjmsMessageSender,
EmailMessageSenderemailMessageSender,
WebServiceInvokerwebServiceInvoker){
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
PersonalBankingServiceinstancearesuppliedvia<constructor-arg>elements:
Examplelisting2-17–PersonalBankingServicebeandefinition
<beanid="personalBankingService"class="PersonalBankingService">
<constructor-argindex="0"ref="jmsMessageSender"/>
<constructor-argindex="1"ref="emailMessageSender"/>
<constructor-argindex="2"ref="webServiceInvoker"/>
</bean>
<beanid="jmsMessageSender"class="JmsMessageSender">

.....
</bean>
<beanid="webServiceInvoker"class="WebServiceInvoker"/>
.....
</bean>
<beanid="emailMessageSender"class="EmailMessageSender"/>
.....
</bean>
In the above example listing, <constructor-arg> elements specify details of the constructor arguments
passedtothePersonalBankingServiceinstance.Theindexattributespecifiestheindexoftheconstructor
argument.Iftheindexattributevalueis0,itmeansthatthe<constructor-arg>elementcorrespondstothe
firstconstructorargument,andiftheindexattributevalueis1,itmeansthatthe<constructor-arg>element
correspondstothesecondconstructorargument,andsoon.Wesawearlierthatrefattributeof<property>
elementisusedforpassingreferencetoabean.Similarly,refattributeof<constructor-arg>elementis
usedforpassingreferencetoabean.Likethe<property>element,the<constructor-arg>elementisalso
usedtopassconfigurationinformation(ifany)requiredbythebean.
You should note that the <constructor-arg> element is also used for passing arguments to static and
instancefactorymethodsthatcreatebeaninstances(refersection2-3).
NOTE Instead of using ref attribute of <property> and <constructor-arg> elements, you can use <ref>
elementinsidethe<property>and<constructor-arg>elementstosetreferencetobeans.Therefattribute
ispreferredasitmakestheXMLlessverbose.
The following example listing shows the EmailMessageSender class and the corresponding bean
definitionthatdemonstratesuseof<constructor-arg>elementstosupplyvaluesforStringtypeconstructor
arguments:
Examplelisting2-18EmailMessageSenderclassandthecorrespondingbeandefinition
publicclassEmailMessageSender{
privateStringhost;
privateStringusername;
privateStringpassword;
.....
publicEmailMessageSender(Stringhost,Stringusername,Stringpassword){
this.host=host;
this.username=username;
this.password=password;
}
.....
}
<beanid="emailMessageSender"class="EmailMessageSender">
<constructor-argindex="0"value="smtp.gmail.com"/>
<constructor-argindex="1"value="myusername"/>
<constructor-argindex="2"value="mypassword"/>
</bean>

Sofarwehaveseenthat<constructor-arg>elementisusedforinjectingbeandependenciesandpassing
valuesforStringtypeconstructorarguments.Inchapter3,we’llseehowthe<constructor-arg>elementis
usedtosetprimitivetype(likeint,long,andsoon),collectiontype(likejava.util.List,java.util.Map,and
soon)andcustomtype(likeAddress)properties.
Let’snowlookathowwecanuseconstructor-basedDIalongwithsetter-basedDI.
Usingamixofconstructor-andsetter-basedDImechanisms
Ifabeanclassrequiresbothconstructor-andsetter-basedDImechanisms,youcanuseacombinationof
<constructor-arg>and<property>elementstoinjectdependencies.
The following example listing shows a bean class whose dependencies are injected as arguments to
constructorandsettermethods:
Examplelisting2-19–PersonalBankingServiceclass
publicclassPersonalBankingService{
privateJmsMessageSenderjmsMessageSender;
privateEmailMessageSenderemailMessageSender;
privateWebServiceInvokerwebServiceInvoker;
.....
publicPersonalBankingService(JmsMessageSenderjmsMessageSender,
EmailMessageSenderemailMessageSender){
this.jmsMessageSender=jmsMessageSender;
this.emailMessageSender=emailMessageSender;
}
publicvoidsetWebServiceInvoker(WebServiceInvokerwebServiceInvoker){
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>elementsareusedtoinjectdependenciesofPersonalBankingServiceclass:
Examplelisting2-20–Mixingconstructor-andsetter-basedDImechanisms
<beanid="dataSource"class="PersonalBankingService">
<constructor-argindex="0"ref="jmsMessageSender"/>
<constructor-argindex="1"ref="emailMessageSender"/>
<propertyname="webServiceInvoker"ref="webServiceInvoker"/>
</bean>
Now,that we have seenhowtoinstructSpringcontainertocreatebeansand performDI,let’slookat
differentscopesthatyoucanspecifyforbeans.

2-5Beanscopes
Youmaywanttospecifythescopeofabeantocontrolwhetherasharedinstanceofthebeaniscreated
(singletonscope),oranewbeaninstanceiscreatedeverytimethebeanisrequested(prototypescope)
fromtheSpringcontainer.Thescopeofabeanisdefinedbythescopeattributeofthe<bean>element.If
thescopeattributeisnotspecified,itmeansthatthebeanisasingleton-scopedbean.
NOTEInwebapplicationscenarios,Springallowsyoutospecifyadditionalscopes:request,session
and globalSession. These scopes determine the lifetime of the bean instance. For instance, a request-
scoped bean’s lifetimeis limited toasingle HTTP request.Asin this chapter we’ll not be discussing
SpringWebMVCorSpringPortletMVC,we’llrestrictthediscussiontosingletonandprototypescopes.
Therequest,sessionandglobalSessionscopesaredescribedinchapter10.
IMPORTchapter2/ch02-bankapp-scopes(Thisproject shows usageof singletonandprototype bean
scopes.Toruntheapplication,executethemainmethodoftheBankAppclassofthisproject.Theproject
alsocontains2JUnittests,PrototypeTestandSingletonTestthatyoucanexecute)
Singleton
Thesingletonscopeisthedefaultscope for all the beansdefinedintheapplicationcontext XML file.
Instance of a singleton-scoped bean is created when the Spring container is created, and is destroyed
whentheSpringcontainerisdestroyed.Springcontainercreatesasingleinstanceofasingleton-scoped
bean,whichissharedbyallthebeansthatdependonit.
ThefollowingexamplelistingshowstheapplicationContext.xmlfileofch02-bankapp-scopesprojectin
whichallthebeansaresingleton-scoped:
Examplelisting2-21–applicationContext.xml-Singleton-scopedbeans
Project–ch02-bankapp-scopes
Sourcelocation-src/main/resources/META-INF/spring
<beans.....>
<beanid="controller"
class="sample.spring.chapter02.bankapp.controller.FixedDepositControllerImpl">
<propertyname=“fixedDepositService"ref="service"/>
</bean>
<beanid="service"
class="sample.spring.chapter02.bankapp.service.FixedDepositServiceImpl">
<propertyname=“fixedDepositDao"ref="dao"/>
</bean>
<beanid="dao"class="sample.spring.chapter02.bankapp.dao.FixedDepositDaoImpl"/>
.....
</beans>
IntheaboveapplicationContext.xmlfile,controller,serviceanddaobeansaresingleton-scopedbecause
no scope attribute is specified for the <bean> elements. This means that only a single instance of

FixedDepositControllerImpl,FixedDepositServiceImplandFixedDepositDaoImpl classes is createdby
theSpringcontainer.Asthesebeansaresingleton-scoped,Springcontainerreturnsthesameinstanceof
thebeaneverytimeweretrieveoneofthesebeansusingApplicationContext’sgetBeanmethod.
NOTEIfthescopeattributeisnotspecifiedorthevalueofscopeattributeissingleton,itmeansthatthe
beanissingleton-scoped.
ThefollowingexamplelistingshowsthetestInstancesmethodofSingletonTest(aJUnittestclass)classof
ch02-bankapp-scopes project. The testInstances method tests whether multiple invocation of
ApplicationContext’sgetBeanmethodreturnsthesameordifferentinstanceofthecontrollerbean:
Examplelisting2-22–SingletonTestJUnittestclass
Project–ch02-bankapp-scopes
Sourcelocation-src/test/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
importstaticorg.junit.Assert.assertSame;
importorg.junit.BeforeClass;
importorg.junit.Test;
importsample.spring.chapter02.bankapp.controller.FixedDepositController;
publicclassSingletonTest{
privatestaticApplicationContextcontext;
@BeforeClass
publicstaticvoidinit(){
context=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
}
@Test
publicvoidtestInstances(){
FixedDepositControllercontroller1=(FixedDepositController)context.getBean("controller");
FixedDepositControllercontroller2=(FixedDepositController)context.getBean("controller");
assertSame("DifferentFixedDepositControllerinstances",controller1,controller2);
}
.....
}
Intheaboveexamplelisting,JUnit’s@BeforeClassannotationspecifiesthattheinitmethodisinvoked
beforeanyofthetestmethods(thatis,methodsannotatedwithJUnit’s@Testannotation)intheclass.This
means that @BeforeClass annotated method is invoked only once, and @Test annotated methods are
executedonlyaftertheexecutionof@BeforeClassannotatedmethod.Notethattheinitmethodisastatic
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

testInstancesmethodobtains2instancesofcontrollerbeanandcheckswhetherboththeinstancesarethe
samebyusingJUnit’sassertSameassertion.Asthecontrollerbeanissingleton-scoped,controller1and
controller2 bean instances are the same. For this reason, SingletonTest’s testInstances test executes
withoutanyassertionerrors.
ThefollowingfigureshowsthattheSpringcontainerreturnsthesameinstanceofcontrollerbeanwhen
youcalltheApplicationContext’sgetBeanmethodmultipletimes:
Figure2-4Multiplerequestsforasingleton-scopedbeanresultsinthesamebeaninstancereturnedbythe
Springcontainer
The above figure shows that multiple calls to obtain controller bean returns the same instance of the
controllerbean.
NOTEInfigure2-4,thecontrollerbeaninstanceisrepresentedbya2-compartmentrectangle.Thetop
compartmentshowsthenameofthebean(thatis,thevalueoftheidattributeofthe<bean>element)and
thebottomcompartmentshowsthetypeofthebean(thatis,thevalueoftheclassattributeofthe<bean>
element). In the rest of this book, we’ll use this convention to show bean instances inside a Spring
container.
Asingleton-scopedbeaninstanceissharedamongstthebeansthatdependonit.Thefollowingexample
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
obtaineddirectlybycallinggetBeanmethodofApplicationContext:
Examplelisting2-23–testReferencemethodofSingletonTestJUnittestclass
Project–ch02-bankapp-scopes
Sourcelocation-src/test/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
importstaticorg.junit.Assert.assertSame;
importorg.junit.Test;

publicclassSingletonTest{
privatestaticApplicationContextcontext;
.....
@Test
publicvoidtestReference(){
FixedDepositControllercontroller=(FixedDepositController)context.getBean("controller");
FixedDepositDaofixedDepositDao1=
controller.getFixedDepositService().getFixedDepositDao();
FixedDepositDaofixedDepositDao2=(FixedDepositDao)context.getBean("dao");
assertSame("DifferentFixedDepositDaoinstances",fixedDepositDao1,fixedDepositDao2);
}
}
Intheaboveexamplelisting,thetestReferencemethodfirstretrievestheFixedDepositDaoinstance(refer
fixedDepositDao1variableintheaboveexamplelisting)referencedbytheFixedDepositControllerbean,
followed by directly retrieving another instance of FixedDepositDao bean (refer fixedDepositDao2
variable in the above example listing) using ApplicationContext’s getBean method. If you execute the
testReference test, you’ll see that the test completes successfully because the fixedDepositDao1 and
fixedDepositDao2instancesarethesame.
Figure2-5showsthattheFixedDepositDaoinstancereferencedbyFixedDepositControllerinstanceisthe
sameastheonereturnedbyinvokinggetBean("dao")methodonApplicationContext.
Figure2-5Singleton-scopedbeaninstanceissharedbetweenbeansthatdependonit
TheabovefigureshowsthattheFixedDepositDaoinstancereferencedbyFixedDepositController bean
instance and the one retrieved directly by calling ApplicationContext’s getBean are same. If there are
multiple beans dependent on a singleton-scoped bean, then all the dependent beans share the same
singleton-scopedbeaninstance.

Let’s now look at whether or not the same singleton-scoped bean instance is shared between multiple
Springcontainerinstances.
Singleton-scopedbeansandmultipleSpringcontainerinstances
Thescopeofasingleton-scopedbeaninstanceislimitedtotheSpringcontainerinstance.Thismeansthat
if you create 2 instances of the Spring container using the same configuration metadata, each Spring
containerhasitsowninstancesofthesingleton-scopedbeans.
ThefollowingexamplelistingshowsthetestSingletonScopemethodofSingletonTestclass,whichtests
whethertheFixedDepositControllerbeaninstanceretrievedfromtwodifferentSpringcontainerinstances
aresameordifferent:
Examplelisting2-24–testSingletonScopemethodofSingletonTestJUnittestclass
Project–ch02-bankapp-scopes
Sourcelocation-src/test/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
importstaticorg.junit.Assert.assertNotSame;
publicclassSingletonTest{
privatestaticApplicationContextcontext;
.....
@BeforeClass
publicstaticvoidinit(){
context=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
}
@Test
publicvoidtestSingletonScope(){
ApplicationContextanotherContext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
FixedDepositControllerfixedDepositController1=(FixedDepositController)anotherContext
.getBean("controller");
FixedDepositControllerfixedDepositController2=
(FixedDepositController)context.getBean("controller");
assertNotSame("SameFixedDepositControllerinstances",
fixedDepositController1,fixedDepositController2);
}
}

TheSingletonTest’sinitmethod(annotatedwithJUnit’s@BeforeClassannotation)createsaninstanceof
ApplicationContext(identifiedbycontextvariable)beforeany@Testannotatedmethodisexecuted.The
testSingletonScopemethodcreates one more instance ofSpring container (identifiedbyanotherContext
variable) using the same applicationContext.xml file. An instance of FixedDepositController bean is
retrieved from both the Spring containers and checked if they are not the same. If you execute the
testSingletonScope test, you’ll find that the test completes successfully because the
FixedDepositControllerbeaninstanceretrievedfromcontextinstanceisdifferentfromtheoneretrieved
fromanotherContextinstance.
ThefollowingfiguredepictsthebehaviorexhibitedbythetestSingletonScopemethod:
Figure2-6EachSpringcontainercreatesitsowninstanceofasingleton-scopedbean
TheabovefigureshowsthateachSpringcontainercreatesitsowninstanceofcontrollerbean.Thisisthe
reasonwhycontextandanotherContextinstancesreturndifferentinstancesofcontrollerbeanwhenyou
callgetBean("controller")method.
ThetestSingletonScopemethodshowedthateachSpringcontainercreatesitsowninstanceofasingleton-
scopedbean.ItisimportanttonotethatSpringcontainercreatesaninstanceofasingleton-scopedbean
for each bean definition. The following example listing shows multiple bean definitions for the
FixedDepositDaoImplclass:
Examplelisting2-25–applicationContext.xml-Multiplebeandefinitionsforthesameclass
Project–ch02-bankapp-scopes
Sourcelocation-src/main/resources/META-INF/spring
<beanid="dao"class="sample.spring.chapter02.bankapp.dao.FixedDepositDaoImpl"/>
<beanid="anotherDao"
class="sample.spring.chapter02.bankapp.dao.FixedDepositDaoImpl"/>
ThebeandefinitionsshownintheaboveexamplelistingareforFixedDepositDaoImplclass.Asscope
attributeisnotspecified,beandefinitionsshownintheaboveexamplelistingrepresentsingleton-scoped
beans.Evenifmultiplebeandefinitionsaredefinedforaclass,Springcontainercreatesabeaninstance
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:
Examplelisting2-26–testSingletonScopePerBeanDefmethodofSingletonTestJUnittestclass
Project–ch02-bankapp-scopes
Sourcelocation-src/test/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
importstaticorg.junit.Assert.assertNotSame;
publicclassSingletonTest{
privatestaticApplicationContextcontext;
.....
@Test
publicvoidtestSingletonScopePerBeanDef(){
FixedDepositDaofixedDepositDao1=(FixedDepositDao)context.getBean("dao");
FixedDepositDaofixedDepositDao2=(FixedDepositDao)context.getBean("anotherDao");
assertNotSame("SameFixedDepositDaoinstances",fixedDepositDao1,fixedDepositDao2);
}
}
Intheaboveexamplelisting,fixedDepositDao1andfixedDepositDao2variablesrepresentinstancesof
FixedDepositDaoImplclassthatSpringcontainercreatescorrespondingtothedaoandanotherDaobean
definitions, respectively. If you execute the testSingleScopePerBeanDef test, it’ll execute without any
assertion errors because the fixedDepositDao1 instance (corresponding to dao bean definition) and
fixedDepositDao2instance(correspondingtoanotherDaobeandefinition)aredistinct.
Thefollowingfiguresummarizesthatasingleton-scopedbeaniscreatedperbeandefinition:
Figure2-7Thereisonesingleton-scopedbeaninstanceperbeandefinition
Theabovefigureshowsthatthereexistsoneinstanceofsingleton-scopedbeanperbeandefinitioninthe
Springcontainer.
We mentioned earlier that a singleton-scoped bean is pre-instantiated by default, which means an
instanceofasingleton-scopedbeaniscreatedwhenyoucreateaninstanceoftheSpringcontainer.Let’s
nowlookathowyoucanlazilyinitializeasingleton-scopedbean.

Lazilyinitializingasingleton-scopedbean
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
containertolazyinitializelazyBeanbean:
Examplelisting2-27–Lazilyinitializingasingleton-scopedbean
<beanid="lazyBean"class="example.LazyBean"lazy-init=”true”/>
The<bean>element’slazy-initattributespecifieswhetherthebeaninstanceiscreatedlazilyoreagerly.If
thevalueistrue(asincaseofthebeandefinitionshownabove),thebeaninstanceisinitializedbythe
Springcontainerwhenitreceivestherequestforthebeanforthefirsttime.
Thefollowingsequencediagramshowshowlazy-initattributeaffectsthecreationofasingleton-scoped
beaninstance:
Figure2-8Alazily-initializedsingleton-scopedbeaninstanceiscreatedwhenitisrequestedforthefirst
timebytheapplication
In the above diagram, BeanA represents a singleton-scoped bean instance that is not set to be lazily-
initialized,andLazyBeanrepresentsasingleton-scopedbeanthatissettobelazily-initialized.Whenthe
Spring container instance is created, BeanA is also instantiated because it is not set to be lazily-
initialized. On the other hand, LazyBean is instantiated when ApplicationContext’s getBean method is
invokedforthetimefirsttimetoretrieveaninstanceofLazyBeanfromtheSpringcontainer.
NOTEYoucanuse<beans>element’sdefault-lazy-initattributetospecifydefaultinitializationstrategy
forbeansdefinesintheapplicationcontextXMLfile.Ifthe<bean>element’slazy-initattributespecifies
adifferentvaluethanthe<beans>element’sdefault-lazy-init,thevaluespecifiedbythelazy-initattribute
appliestothebean.
Asasingleton-scopedbeancanbelazily-initializedorpre-instantiatedbytheSpringcontainer,youmay
bethinkingatthistimewhetheryoushoulddefineyoursingleton-scopedbeanstobelazily-initializedor
pre-instantiated.Inmostapplicationscenarios,itisbeneficialtopre-instantiatesingleton-scopedbeansto
discover configuration issues at the time of creation of the Spring container. The following example

listingshowsaaBeansingleton-scopedbeanthatissettobelazily-initialized,andthatdependsonbBean
bean:
Examplelisting2-28–Alazily-initializedsingleton-scopedbean
publicclassABean{
privateBBeanbBean;
publicvoidsetBBean(BBeanbBean){
this.bBean=bBean;
}
.....
}
<beanid="aBean"class="ABean"lazy-init="true">
<propertyname="bBean"value="bBean"/>
</bean>
<beanid="bBean"class="BBean"/>
Intheaboveexamplelisting,ABean’sbBeanpropertyreferstotheBBeanbean.Noticethatinsteadofref
attribute, value attribute of <property> element has been used to set ABean’s bBean property. If you
createanApplicationContextinstancebypassingittheXMLfilecontainingtheabovebeandefinition,no
errors will be reported. But, when you try to fetch the aBean bean by invoking ApplicationContext’s
getBeanmethod,you’llgetthefollowingerrormessage:
Causedby:java.lang.IllegalStateException:Cannotconvertvalueoftype[java.lang.String]torequiredtype[BBean]forproperty'bBean:no
matchingeditorsorconversionstrategyfound
The above error message is shown because the Spring container fails to convert the String value of
ABean’sbBeanpropertytoBBeantype.Thishighlightsasimpleconfigurationissueinwhichinsteadof
specifying<bean>element’srefattribute,valueattributewasspecified.IftheaBeanbeanwasdefinedas
pre-instantiated(insteadoflazily-initialized),theaboveconfigurationissuecouldhavebeencaughtatthe
timewecreatedaninstanceofApplicationContext,andnotwhenwetriedtoobtainaninstanceofaBean
beanfromtheApplicationContext.
Let’snowlookatprototype-scopedbeansinSpring.
Prototype
Aprototype-scopedbeanisdifferentfromasingleton-scopedbeaninthesensethattheSpringcontainer
always returns a new instance of a prototype-scoped bean. Another distinctive feature of prototype-
scopedbeansisthattheyarealwayslazily-initialized.
The following FixedDepositDetails bean in the applicationContext.xml file of ch02-bankapp-scopes
projectrepresentsaprototype-scopedbean:
Examplelisting2-29–applicationContext.xml-Aprototype-scopedbeanexample
Project–ch02-bankapp-scopes
Sourcelocation-src/main/resources/META-INF/spring

<beanid="FixedDepositDetails"
class="sample.spring.chapter02.bankapp.domain.FixedDepositDetails"
scope="prototype"/>
Theaboveexamplelistingshowsthatthe<bean>element’sscopeattributevalueissettoprototype.This
meansthattheFixedDepositDetailsbeanisaprototype-scopedbean.
The following testInstances method of PrototypeTest JUnit test class shows that the 2 instances of
FixedDepositDetailsbeanretrievedfromtheSpringcontaineraredifferent:
Examplelisting2-30–testInstancesmethodofPrototypeTestJUnittestclass
Project–ch02-bankapp-scopes
Sourcelocation-src/test/java/sample/spring/chapter02/bankapp
packagesample.spring.chapter02.bankapp;
importstaticorg.junit.Assert.assertNotSame;
publicclassPrototypeTest{
privatestaticApplicationContextcontext;
.....
@Test
publicvoidtestInstances(){
FixedDepositDetailsfixedDepositDetails1=
(FixedDepositDetails)context.getBean("fixedDepositDetails");
FixedDepositDetailsfixedDepositDetails2=
(FixedDepositDetails)context.getBean("fixedDepositDetails");
assertNotSame("SameFixedDepositDetailsinstances",
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
ApplicationContextaredifferent.
Let’snowlookathowtochoosetherightscope(singletonorprototype)forabean.
Choosingtherightscopeforyourbeans
Ifabeandoesn’tmaintainanyconversationalstate(thatis,itisstatelessinnature),itshouldbedefinedas
a singleton-scoped bean. If a bean maintains conversational state, it should be defined as a prototype-
scopedbean.FixedDepositServiceImpl,FixedDepositDaoImplandFixedDepositControllerImplbeansof
MyBank application are stateless in nature; therefore, they are defined as singleton-scoped beans.
FixedDepositDetails bean (a domain object) of MyBank application maintains conversational state;
therefore,itisdefinedasaprototype-scopedbean.

NOTEIfyouareusinganORMframework(likeHibenateoriBATIS)inyourapplication,thedomain
objectsarecreatedeitherbytheORMframeworkoryoucreatethemprogrammaticallyinyour
applicationcodeusingthenewoperator.Itisbecauseofthisreasondomainobjectsarenotdefinedinthe
applicationcontextXMLfileiftheapplicationusesanORMframeworkforpersistence.
2-6Summary
In this chapter,we discussed some ofthe basics ofSpring Framework.We looked at ‘programming to
interfaces’designapproach,differentapproachestocreatebeaninstances,constructor-basedDIandbean
scopes.Inthenextchapter,we’lllookathowtosetdifferenttypes(likeint,long,Map,Set,andsoon)of
beanpropertiesandconstructorarguments.

Chapter3-Configuringbeans
3-1Introduction
Inpreviouschapters,wetoucheduponsomeofthebasicconceptsofSpringFramework.Wesawhow
SpringbeansandtheirdependenciesarespecifiedintheapplicationcontextXMLfile.Wealsolookedat
singleton-andprototype-scopedbeans,anddiscussedtheimplicationsofassigningthesescopestobeans.
Inthischapter,we’lllookat:
§beandefinitioninheritance
§howargumentstoabeanclass’sconstructorareresolved
§howtoconfigurebeanpropertiesandconstructorargumentsofprimitivetype(likeint,float,andso
on),collectiontype(likejava.util.List,java.util.Map,andsoon),customtype(likeAddress),and
soon
§ how you can make the application context XML file less verbose by using p-namespace and c-
namespacetospecifybeanpropertiesandconstructorarguments,respectively
§Spring’sFactoryBeaninterfacethatallowsyoutowriteyourownfactoryclassfor creatingbean
instances

3-2Beandefinitioninheritance
Wesawinchapter1and2thatabeandefinitionintheapplicationcontextXMLfilespecifiesthefully-
qualifiednameofthebeanclassanditsdependencies.Insomescenarios,tomakeabeandefinitionless
verbose,youmaywantabeandefinitiontoinheritconfigurationinformationfromanotherbeandefinition.
Let’slookatonesuchscenarioinMyBankapplication.
IMPORTchapter3/ch03-bankapp-inheritance(Thisproject showstheMyBankapplicationthatuses
beandefinitioninheritance.Toruntheapplication,executethemainmethodoftheBankAppclassofthis
project)
MyBank–Beandefinitioninheritanceexample
Inthepreviouschapter,wesawthattheMyBankapplicationaccessesdatabasethroughDAOs.Let’ssay
that the MyBank application defines a DatabaseOperations class that simplifies interacting with the
database.So,alltheDAOsintheMyBankapplicationdependonDatabaseOperationsclasstoperform
databaseoperations,asshowninthefollowingfigure:
Figure 3-1 - DAO classes in MyBank application make use of DatabaseOperations class to perform
databaseinteraction
TheabovefigureshowsthattheFixedDepositDaoandPersonalBankingDaoclassesaredependentonthe
DatabaseOperations class. The following application context XML file shows the bean definitions for
theseclasses:
Examplelisting3-1–DAObeansaredependentonDatabaseOperationsbean
<beanid="databaseOperations"
class="sample.spring.chapter01.bankapp.utils.DatabaseOperations"/>
<beanid="personalBankingDao"
class="sample.spring.chapter01.bankapp.dao.PersonalBankingDaoImpl">
<propertyname="databaseOperations"ref="databaseOperations"/>
</bean>

<beanid="FixedDepositDao"
class="sample.spring.chapter01.bankapp.dao.FixedDepositDaoImpl">
<propertyname="databaseOperations"ref="databaseOperations"/>
</bean>
Both the personalBankingDao and FixedDepositDao bean definitions use the <property> element to
performdependencyinjectionoftheDatabaseOperationsinstance.Asthenameofthepropertythatrefers
totheDatabaseOperationsinstanceisdatabaseOperationsinboththebeandefinitions,itimpliesthatboth
PersonalBankingDaoImpl and FixedDepositDaoImpl classes define a setDatabaseOperations method to
allowSpringcontainertoinjectDatabaseOperationsinstance.
If multiple beans in your application share a common set of configuration (properties, constructor
arguments,andsoon),youcancreateabeandefinitionthatactsasaparentforotherbeandefinitions.In
case of personalBankingDao and fixedDepositDao bean definitions, the common configuration is the
databaseOperations property. The following example listing shows that the personalBankingDao and
fixedDepositDaobeandefinitionsmakeuseofbeandefinitioninheritance:
Examplelisting3-2–applicationContext.xml-MyBank’sapplicationcontextXMLfile
Project–ch03-bankapp-inheritance
Sourcelocation-src/main/resources/META-INF/spring
<beanid="databaseOperations"
class="sample.spring.chapter03.bankapp.utils.DatabaseOperations"/>
<beanid="daoTemplate"abstract="true">
<propertyname="databaseOperations"ref="databaseOperations"/>
</bean>
<beanid="FixedDepositDao"parent="daoTemplate"
class="sample.spring.chapter03.bankapp.dao.FixedDepositDaoImpl"/>
<beanid="personalBankingDao"parent="daoTemplate"
class="sample.spring.chapter03.bankapp.dao.PersonalBankingDaoImpl"/>
Intheaboveexamplelisting,thedaoTemplatebeandefinitiondefinesthecommonconfigurationsharedby
both the fixedDepositDao and personalBankingDao bean definitions. As both the fixedDepositDao and
personalBankingDaobeandefinitionsrequirethedatabaseOperationsdependency(referexamplelisting
3-1),thedaoTemplatebeandefinitiondefinesthedatabaseOperationsdependencyusingthe<property>
element.The<bean>element’sparentattributespecifiesthenameofthebeandefinitionfromwhichthe
configuration is inherited. As the parent attribute value is daoTemplate for fixedDepositDao and
personalBankingDao bean definitions, they inherit databaseOperations property from the daoTemplate
beandefinition.Theexamplelistings3-1and3-2aresame,exceptthattheexamplelisting3-2makesuse
ofbeandefinitioninheritance.
Ifthe<bean>element’sabstractattributevalueissettotrue,itmeansthatthebeandefinitionisabstract.
It is important to note that the Spring container doesn’t attempt to create a bean corresponding to an
abstractbeandefinition.Itisimportanttonotethatyoucan’tdefineabeantobedependentonanabstract

bean,thatis,youcan’tuse<property>or<constructor-arg>elementtorefertoanabstractbean.
In example listing 3-2, daoTemplate bean definition is abstract. You may have noticed that the
daoTemplatebeandefinitiondoesn’tspecifytheclassattribute.Ifaparentbeandefinitiondoesn’tspecify
theclassattribute,childbeandefinitions(likethefixedDepositDaoandpersonalBankingDao)specifythe
class attribute. It is important to note that if you don’t specify the class attribute, you must define the
parent bean definition as abstract so that Spring container doesn’t attempt to create a bean instance
correspondingtoit.
ToverifythatthefixedDepositDaoandpersonalBankingDaobeandefinitionsinheritdaoTemplate bean
definition’sdatabaseOperationsproperty,executethemainmethodofBankAppclass ofch03-bankapp-
inheritance project. BankApp’s main method invokes methods on the fixedDepositDao and
personalBankingDaobeans;thosebeansinturninvokemethodsontheDatabaseOperationsinstance.Ifa
DatabaseOperations instance is not injected into the fixedDepositDao and personalBankingDao beans,
java.lang.NullPointerExceptionwillbethrown.
ThefollowingdiagramsummarizeshowbeandefinitioninheritanceworksincaseofFixedDepositDao
andpersonalBankingDaobeandefinitions:
Figure3-2–BeandefinitioninheritanceinMyBankapplication
The above figure shows that the fixedDepositDaoand personalBankingDao bean definitions inherit the
databaseOperations property (shown in italics in the boxes labeled fixedDepositDao and
personalBankingDao)fromthedaoTemplatebeandefinition.TheabovefigurealsodepictsthattheSpring
container doesn’t attempt to create a bean instance corresponding to the daoTemplate bean definition
becauseitismarkedasabstract.
Let’snowlookatwhatconfigurationinformationgetsinheritedfromtheparentbeandefinition.
Whatgetsinherited?
Achildbeandefinitioninheritsthefollowingconfigurationinformationfromtheparentbeandefinition:
·properties–specifiedvia<property>elements
·constructorarguments–specifiedvia<constructor-arg>elements
·methodoverrides(discussedinsection4-5ofchapter4)

·initializationanddestroymethods(discussedinchapter5),and
·factorymethods–specifiedviafactory-methodattributeof<bean>element(refersection2-3of
chapter2toknowhowstaticandinstancefactorymethodsareusedforcreatingbeans)
IMPORTchapter3/ch03-bankapp-inheritance-example(ThisprojectshowstheMyBankapplication
thatusesbeandefinitioninheritance.Inthisproject,you’llseemultiplescenariosinwhichbeandefinition
inheritanceisused.Toruntheapplication,executethemainmethodoftheBankAppclassofthisproject)
Let’snowlookatsomeofthebeandefinitioninheritanceexamples.
Beandefinitioninheritanceexample–parentbeandefinitionisnotabstract
Thefollowingexamplelistingshowsabeaninheritanceexampleinwhichtheparentbeandefinitionis
notabstract,andthechildbeandefinitionsdefineanadditionaldependency:
Examplelisting3-3–applicationContext.xml-Beandefinitioninheritance–parentbeandefinitionisnot
abstract
Project–ch03-bankapp-inheritance-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanid="serviceTemplate"
class="sample.spring.chapter03.bankapp.base.ServiceTemplate">
<propertyname="jmsMessageSender"ref="jmsMessageSender"/>
<propertyname="emailMessageSender"ref="emailMessageSender"/>
<propertyname="webServiceInvoker"ref="webServiceInvoker"/>
</bean>
<beanid="fixedDepositService"class=".....FixedDepositServiceImpl"
parent="serviceTemplate">
<propertyname=“fixedDepositDao"ref="fixedDepositDao"/>
</bean>
<beanid="personalBankingService"class=".....PersonalBankingServiceImpl"
parent="serviceTemplate">
<propertyname="personalBankingDao"ref="personalBankingDao"/>
</bean>
<beanid="userRequestController"class=".....UserRequestControllerImpl">
<propertyname="serviceTemplate"ref="serviceTemplate"/>
</bean>
A littlebackgroundbefore we delve into the details ofthe above listedconfiguration: a service inthe
MyBank application may send JMS messages to a messaging-middleware or send emails to an email
server or it may invokean external web service. Intheabove example listing, the jmsMessageSender,
emailMessageSender and webServiceInvoker beans simplify these tasks by providing a layer of
abstraction.TheserviceTemplatebeanprovidesaccesstojmsMessageSender,emailMessageSenderand
webServiceInvoker beans. This is the reason why the serviceTemplate bean is dependent on the

jmsMessageSender,emailMessageSenderandwebServiceInvokerbeans.
Example listing 3-3 shows that the serviceTemplate bean definition is the parent bean definition of
fixedDepositServiceandpersonalBankingServicebeandefinitions.NoticethattheserviceTemplatebean
definitionisnotabstract;theclassattributespecifiesServiceTemplateastheclass.Inourpreviousbean
definition inheritance example (refer example listing 3-2), child bean definitions didn’t define any
properties.Intheaboveexamplelisting,noticethatthefixedDepositServiceandpersonalBankingService
childbeandefinitionsdefinefixedDepositDaoandpersonalBankingDaoproperties,respectively.
As parent bean definition’s 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
PersonalBankingServiceImplclassesaresubclassesofServiceTemplateclass.
ThefollowingexamplelistingshowsthePersonalBankingServiceImplclass:
Examplelisting3-4–PersonalBankingServiceImplclass
Project–ch03-bankapp-inheritance-examples
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/service
packagesample.spring.chapter03.bankapp.service;
publicclassPersonalBankingServiceImplextendsServiceTemplateimplements
PersonalBankingService{
privatePersonalBankingDaopersonalBankingDao;
publicvoidsetPersonalBankingDao(PersonalBankingDaopersonalBankingDao){
this.personalBankingDao=personalBankingDao;
}
@Override
publicBankStatementgetMiniStatement(){
returnpersonalBankingDao.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
PersonalBankingServiceImplclassisasubclassoftheServiceTemplateclass.
Thefollowingdiagramshowsthataparentbeandefinition(likeserviceTemplate)neednotbeabstract,
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:
Figure3-3–Childbeandefinitionsaddadditionalproperties,parentbeandefinitionisnotabstract,and
parent-childrelationshipexistsbetweentheclassesrepresentedbytheparentandchildbeandefinitions
Figure3-3shows:
·SpringcontainercreatesaninstanceofserviceTemplatebeanbecauseit’snotdefinedasabstract
·FixedDepositServiceImplandPersonalBankingServiceImplclasses(correspondingtothechild
bean definitions) are subclasses of ServiceTemplate class – the class corresponding to the
serviceTemplateparentbeandefinition.
· And, fixedDepositService and personalBankingService bean definitions define additional
properties,fixedDepositDaoandpersonalBankingDao,respectively.Youshouldnotethatthechild
beandefinitionscanalsodefineadditionalconstructorargumentsandmethodoverrides(discussed
insection4-5).
AsserviceTemplatebeandefinitionisnotabstract,otherbeanscandefineserviceTemplatebeanastheir
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,thefunctionalityofferedbytheparentbeancanbeutilizednotonlybychildbeansbutalsoby
otherbeansintheapplicationcontext.
Beandefinitioninheritanceexample–inheritingfactorymethodconfiguration
Childbeandefinitionscanusebeandefinitioninheritancetoinheritfactorymethodconfigurationfromthe
parentbeandefinition.Let’slookatanexamplethatshowsfactorymethodconfigurationsareinheritedby
childbeandefinitions.

ThefollowingControllerFactoryclassdefinesagetControllerinstancefactorymethod:
Examplelisting3-5–ControllerFactoryclass
Project–ch03-bankapp-inheritance-examples
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/controller
packagesample.spring.chapter03.bankapp.controller;
publicclassControllerFactory{
publicObjectgetController(StringcontrollerName){
Objectcontroller=null;
if("fixedDepositController".equalsIgnoreCase(controllerName)){
controller=newFixedDepositControllerImpl();
}
if("personalBankingController".equalsIgnoreCase(controllerName)){
controller=newPersonalBankingControllerImpl();
}
returncontroller;
}
}
The above example listing shows that the getController factory method creates an instance of
FixedDepositControllerImpl or PersonalBankingControllerImpl class, depending upon the value of the
controllerNameargumentpassedtoit.IfthevalueofcontrollerNameargumentisfixedDepositController,
thegetController methodcreates an instance ofFixedDepositControllerImpl class. And, if the value of
controllerNameargumentispersonalBankingController,thegetControllermethodcreatesaninstanceof
PersonalBankingControllerImplclass.
The following bean definitions inthe applicationContext.xml file of ch03-bankapp-inheritance-example
project show that the child bean definitions inherit the getController instance factory method
configurationfromtheparentbeandefinition:
Example listing 3-6 – applicationContext.xml - Bean definition inheritance – inheriting the factory
methodconfiguration
Project–ch03-bankapp-inheritance-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanid="controllerFactory"
class="sample.spring.chapter03.bankapp.controller.ControllerFactory"/>
<beanid="controllerTemplate"factory-bean="controllerFactory"
factory-method="getController"abstract="true">
</bean>
<beanid="fixedDepositController"parent="controllerTemplate">
<constructor-argindex="0"value="fixedDepositController"/>

<propertyname=“fixedDepositService"ref="fixedDepositService"/>
</bean>
<beanid="personalBankingController"parent="controllerTemplate">
<constructor-argindex="0"value="personalBankingController"/>
<propertyname="personalBankingService"ref="personalBankingService"/>
</bean>
In the above example listing, the ControllerFactory class represents a factory class that defines a
getController instance factory method. The controllerTemplate bean definition specifies that the
ControllerFactory’sgetController factorymethodis used forcreatingbeaninstances.ThegetController
method (refer example listing 3-5) creates an instance of FixedDepositControllerImpl or
PersonalBankingControllerImplbean,dependingontheargumentpassedtothegetControllermethod.
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
factorymethodconfiguration.ThefixedDepositControllerbeandefinitionwouldliketopassanargument
to the ControllerFactory’s getController factory method so that it creates an instance of
FixedDepositControllerImplbean.And,personalBankingControllerbeandefinitionwouldliketopassan
argument to the ControllerFactory’s 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 an instance factory method. In example listing 3-6, the
<constructor-arg>elementhasbeenusedbyfixedDepositControllerandpersonalBankingControllerchild
beandefinitionstopass‘fixedDepositService’and‘personalBankingService’values,respectively,tothe
getControllerfactorymethod.
It is recommended that you now run the main method of BankApp class of ch03-bankapp-inheritance-
examplesprojecttoseeusageofthebeandefinitioninheritanceexamplesdiscussedinthissection.
Let’snowlookathowconstructorargumentsarematched.

3-3Constructorargumentmatching
Inthepreviouschapter,wesawthattheconstructorargumentsarespecifiedinthebeandefinitionsusing
the<constructor-arg>element.Inthissection,we’lllookathowSpringcontainermatchesaconstructor
argumentspecifiedbya<constructor-arg>elementtothecorrespondingconstructorargumentspecifiedin
thebeanclass’sconstructor.
Beforewegointothedetailsofconstructorargumentmatching,let’slookbackathowwepassarguments
toabeanclass’sconstructor.
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).Toruntheapplication,executethemainmethodoftheBankAppclassofthisproject)
Passingsimplevaluesandbeanreferencesusing<constructor-arg>element
If a constructor argument is of simple Java type (like int, String, and so on), the <constructor-arg>
element’svalueattributeisusedtospecifythevalueoftheconstructorargument.Ifaconstructorargument
is a reference to a bean, you specify the name of the bean using the <constructor-arg> element’s ref
attribute.
ThefollowingexamplelistingshowstheUserRequestControllerImplclassofch03-bankapp-constructor-
args-by-typeprojectwhoseconstructoracceptsanargumentoftypeServiceTemplate:
Examplelisting3-7–UserRequestControllerImplclass
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/controller
packagesample.spring.chapter03.bankapp.controller;
publicclassUserRequestControllerImplimplementsUserRequestController{
privateServiceTemplateserviceTemplate;
publicUserRequestControllerImpl(ServiceTemplateserviceTemplate){
this.serviceTemplate=serviceTemplate;
}
@Override
publicvoidsubmitRequest(Requestrequest){
//--dosomethingusingServiceTemplate
serviceTemplate.getJmsMessageSender();//--Forex.,sendJMSmessage
.....
}
}
The following example listing shows that a reference to ServiceTemplate instance (represented by
serviceTemplatebeandefinition)ispassedtoUserRequestControllerImpl’sconstructorusingrefattribute
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
Sourcelocation-src/main/resources/META-INF/spring
<beanid="serviceTemplate"class="sample.spring.chapter03.bankapp.base.ServiceTemplate">
.....
</bean>
<beanid="userRequestController"
class="sample.spring.chapter03.bankapp.controller.UserRequestControllerImpl">
<constructor-argindex="0"ref="serviceTemplate"/>
</bean>
With this background information on how to pass simple values and bean references as constructor
arguments,let’snowlookathowSpringcontainermatchesconstructorargumenttypestolocatethebean’s
constructortobeinvoked.
Constructorargumentmatchingbasedontype
Ifthe<constructor-arg>element’sindexattributeisnotspecified,Springcontainerlocatestheconstructor
tobeinvokedbymatchingthetypesreferencedbythe<constructor-arg>elementswiththeargumenttypes
specifiedinthebeanclass’sconstructor(s).
Let’sfirstlookathowSpringcontainermatchesconstructorargumentswhentheconstructorargumentsare
Springbeansthatarenotrelatedbyinheritance.
ConstructorargumentsrepresentingdistinctSpringbeans
The following example listing shows the ServiceTemplate class that defines a constructor that accepts
referencestoJmsMessageSender,EmailMessageSenderandWebServiceInvokerbeans:
Examplelisting3-9–ServiceTemplateclass
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/base
packagesample.spring.chapter03.bankapp.base;
publicclassServiceTemplate{
.....
publicServiceTemplate(JmsMessageSenderjmsMessageSender,
EmailMessageSenderemailMessageSender,
WebServiceInvokerwebServiceInvoker){
.....
}
}
The following example listing shows the bean definitions for the ServiceTemplate class and the beans

referencedbyServiceTemplate:
Examplelisting3-10–applicationContext.xml-BeandefinitionfortheServiceTemplate class and its
dependencies
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/resources/META-INF/spring
<beanid="serviceTemplate"class="sample.spring.chapter03.bankapp.base.ServiceTemplate">
<constructor-argref="emailMessageSender"/>
<constructor-argref="jmsMessageSender"/>
<constructor-argref="webServiceInvoker"/>
</bean>
<beanid="jmsMessageSender"class="sample.spring.chapter03.bankapp.base.JmsMessageSender"/>
<bean id="emailMessageSender" class="sample.spring.chapter03.bankapp.base.EmailMessageSender"
/>
<beanid="webServiceInvoker"class="sample.spring.chapter03.bankapp.base.WebServiceInvoker"/>
Intheaboveexamplelisting,the<constructor-arg>elementsofserviceTemplatebeandon’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 class’s constructor is: JmsMessageSender,
EmailMessageSender,WebServiceInvoker.Asyoucansee,theorderinwhichconstructorargumentsare
definedbythe<constructor-arg>elementsisdifferentfromtheorderspecifiedbytheServiceTemplate
class’sconstructor.
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
becauseJmsMessageSender,EmailMessageSenderandWebServiceInvokerclassesaredistinctinnature
(thatis,theyarenotrelatedbyinheritance),whichmakesiteasierfortheSpringcontainertoinjecttheir
instancesintotheServiceTemplateclass’sconstructorinthecorrectorder.
Iftheconstructorargumenttypesarerelatedbyinheritance,Springcontainerneedsextrainstructionsto
help resolve constructor arguments. Let’s now look at how Spring container matches constructor
argumentswhenbeansreferencedbytheconstructorargumentsarerelatedbyinheritance.
ConstructorargumentsrepresentingrelatedSpringbeans
ConsiderthefollowingSampleBeanbeanclasswhoseconstructoracceptsargumenttypesthatarerelated
byinheritance:
Examplelisting3-11–SampleBeanclass
publicclassSampleBean{
publicSampleBean(ABeanaBean,BBeanbBean){.....}
.....
}
The above example listing shows that the SampleBean class’s constructor accepts ABean and BBean

typesasarguments.ABeanandBBeanrepresentSpringbeansthatarerelatedbyinheritance;BBeanisa
subclassofABean.
The following application context XML file shows the bean definitions for SampleBean, ABean and
BBeanclasses:
Examplelisting3-12–BeandefinitionsforSampleBean,ABeanandBBeanclasses
<beanid="aBean"class="example.ABean"/>
<beanid="bBean"class="example.BBean"/>
<beanid="sampleBean"class="example.SampleBean">
<constructor-argref="bBean"/>
<constructor-argref="aBean"/>
</bean>
AsaBeanandbBeanbeansarerelatedbyinheritance,Springcontainerappliesconstructorargumentsto
the SampleBean’s constructor in the order in which <constructor-arg> elements appear in the bean
definitionfortheSampleBeanclass.IntheabovesampleBeanbeandefinition,thefirst<constructor-arg>
elementreferstobBeanbeanandthesecond<constructor-arg>elementreferstoaBeanbean.Thismeans
that bBean is passed as the first constructor argument and aBean is passed as the second constructor
argumenttotheSampleBeanconstructor.AsinstanceofABean(thesuperclass)can’t bepassedwhere
BBean(thesubclass)instanceisexpected,thesecond<constructor-arg>elementinthesampleBeanbean
definitionresultsinexceptionbeingthrownbytheSpringcontainer.Tohandlesuchscenarios,youcan
use <constructor-arg> element’s index or type attribute to identify the constructor argument to which
<constructor-arg>elementapplies.Forinstance,thefollowingsampleBeanbeandefinitionmakesuseof
type attribute to indicate the type of the constructor argument to which the <constructor-arg> element
applies:
Examplelisting3-13 –<constructor-arg> element’stype attribute identifies the type of the constructor
argument
<beanid="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’stypeattributespecifiesthefully-qualifiednameofthetypetowhichthe
<constructor-arg>elementapplies.Intheaboveexamplelisting,thefirst<constructor-arg>appliestothe
constructorargumentoftypeBBean,andthesecond<constructor-arg>elementappliestotheconstructor
argument of type ABean. Specifying the type attribute takes away the ambiguity that arises when
constructorargumentsarerelatedbyinheritance.
NOTEIftwoormoreconstructorargumentsareofthesametype,theonlyoptionistouseindex
attributetoidentifytheconstructorargumenttowhicheach<constructor-arg>elementapplies.

Sofarwehavelookedatconstructorargumenttypematchingscenariosinwhichconstructorarguments
represented distinct or related Spring beans. We’ll now look at how constructor argument types are
matchedforstandardJavatypes(likeint,long,boolean,String,Date,andsoon)andcustomtypes.
ConstructorargumentsrepresentingstandardJavatypesandcustomtypes
Ifthetypeofaconstructorargumentisaprimitivetype(likeint,long,boolean,andsoon)oraStringtype
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
attributecanbeconverted,it’llnotbepossiblefortheSpringcontainertoderivethetype(forexample,
whetherthevaluerepresentsanintorlongorString)oftheconstructorargument.Insuchscenarios,you
needtoexplicitlyspecifythetypeoftheconstructorargumentusingthetypeattribute.
ThefollowingexamplelistingshowstheTransferFundsServiceImplclassthatdefinesaconstructorwhich
acceptsargumentsoftypesString,boolean,longandint:
Examplelisting3-14–TransferFundsServiceImplclass
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/service
packagesample.spring.chapter03.bankapp.service;
publicclassTransferFundsServiceImplimplementsTransferFundsService{
publicTransferFundsServiceImpl(StringwebServiceUrl,booleanactive,longtimeout,
intnumberOfRetrialAttempts){.....}
.....
}
As the above example listing shows, TransferFundsServiceImpl constructor accepts the following
arguments:webServiceUrl,active,timeoutandnumberOfRetrialAttempts.Thefollowingbeandefinition
for the TransferFundsServiceImpl class shows how constructor argument values can be passed to the
TransferFundsServiceImpl’sconstructor:
Examplelisting3-15–BeandefinitionfortheTransferFundsServiceImplclass
<beanid="transferFundsService"
class="sample.spring.chapter03.bankapp.service.TransferFundsServiceImpl">
<constructor-argvalue="http://someUrl.com/xyz"/>
<constructor-argvalue="true"/>
<constructor-argvalue="5"/>
<constructor-argvalue="200"/>
</bean>
Let’sassumethatthe3rd<constructor-arg>element(valueattribute’svalueis‘5’)issupposedtosupply
valueforthenumberOfRetrialAttemptsconstructorargument,andthe4th<constructor-arg>element(value
attribute’s value is ‘200’) is supposed to supply value for the timeout constructor argument. Spring

containerapplies<constructor-arg>elementstotheTransferFundsServiceImpl’sconstructorintheorder
inwhich<constructor-arg>elementsappearinthetransferFundsServicebeandefinition.Thismeansthat
the 3rd <constructor-arg> element applies to timeout argument, and the 4th <constructor-arg> element
appliestonumberOfRetrialAttemptsargument.Tohandlesuchambiguities,youcanspecifythetypeofa
constructorargumentvia<constructor-arg>element’stypeattribute,asshowninthefollowingexample
listing:
Examplelisting3-16–applicationContext.xml-<constructor-arg>element’stypeattribute
Project–ch03-bankapp-constructor-args-by-type
Sourcelocation-src/main/resources/META-INF/spring
<beanid="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>
IntheabovebeandefinitionfortheTransferFundsServiceImplclass,typeattributeisusedtospecifythe
constructor argument type. Spring container can now use type matching to correctly apply constructor
arguments.
NOTEIftwoormoreconstructorargumentsareofthesametype,theonlyoptionistouseindexattribute
foridentifyingtheconstructorargumenttowhicheach<constructor-arg>elementapplies.
Inthissection,wesawhowtypematchingisperformedbySpringtoresolveconstructorarguments.Let’s
nowlookathowyoucaninstructSpringtoperformconstructorargumentmatchingbasedonconstructor
argument’sname.
IMPORT chapter 3/ch03-bankapp-constructor-args-by-name (This project shows the MyBank
application in which bean class’s constructor arguments are matched byname.To run the application,
executethemainmethodoftheBankAppclassofthisproject)
Constructorargumentmatchingbasedonname
The <constructor-arg> element’s 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
againtheTransferFundsServiceImplclasswhoseconstructoracceptsmultiplearguments:
Examplelisting3-17–TransferFundsServiceImplclass
Project–ch03-bankapp-constructor-args-by-name
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/service
packagesample.spring.chapter03.bankapp.service;
publicclassTransferFundsServiceImplimplementsTransferFundsService{
.....

publicTransferFundsServiceImpl(StringwebServiceUrl,booleanactive,longtimeout,
intnumberOfRetrialAttempts){.....}
}
The above example listing shows that the names of the constructor arguments defined by
TransferFundsServiceImpl’s constructor are: webServiceUrl, active, timeout and
numberOfRetrialAttempts.
NOTETheTransferFundsServiceImplclass’sconstructoracceptsargumentsthataresimpleJavatypes
(like,int,long,boolean,String,andsoon),buttheconceptexplainedinthissectionalsoappliesto
scenariosinwhichconstructorargumentsarereferencestoSpringbeans.
ThefollowingbeandefinitionfortheTransferFundsServiceImplclassuses<constructor-arg>element’s
name attribute to specify the name of the constructor argument to which the <constructor-arg> element
applies:
Examplelisting3-18–applicationContext.xml-<constructor-arg>element’snameattribute
Project–ch03-bankapp-constructor-args-by-name
Sourcelocation-src/main/resources/META-INF/spring
<beanid="transferFundsService"
class="sample.spring.chapter03.bankapp.service.TransferFundsServiceImpl">
<constructor-argname="webServiceUrl"value="http://someUrl.com/xyz"/>
<constructor-argname="active"value="true"/>
<constructor-argname="numberOfRetrialAttempts"value="5"/>
<constructor-argname="timeout"value="200"/>
</bean>
TheaboveconfigurationwillworkonlyifTransferFundsServiceImplclassiscompiledwithdebugflag
enabled(referto-goptionofjavac).Whenthedebugflagisenabled,namesofconstructorargumentsare
preserved in the generated .class file. If you don’t compile your classes with debug flag enabled, the
constructorargumentnamesarelostduringcompilation,andSpringhasnowaytolocatetheconstructor
argument corresponding to the constructor argument name specified by the <constructor-arg> element’s
nameattribute.
Ifyoudon’twanttocompileyourclassesusingdebugflagenabled,youcanuse@ConstructorProperties
annotation(introducedinJavaSE6)toclearlyspelloutnamesoftheconstructorarguments,asshown
hereforTransferFundsServiceImplclass:
Examplelisting3-19–@ConstructorPropertiesannotation
Project–ch03-bankapp-constructor-args-by-name
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/service
packagesample.spring.chapter03.bankapp.service;

importjava.beans.ConstructorProperties;
publicclassTransferFundsServiceImplimplementsTransferFundsService{
@ConstructorProperties({"webServiceUrl","active","timeout","numberOfRetrialAttempts"})
publicTransferFundsServiceImpl(StringwebServiceUrl,booleanactive,longtimeout,
intnumberOfRetrialAttempts){.....}
}
In the above example listing, @ConstructorProperties annotation specifies the names of constructor
argumentsintheorderinwhichtheyappearinthebeanclass’sconstructor.Youmustensurethatyouuse
thesameconstructorargumentnamesinthe<constructor-arg>elements.
Let’snowlookathowthe@ConstructorPropertiesannotationaffectsbeandefinitioninheritance.
@ConstructorPropertiesannotationandbeandefinitioninheritance
If the constructor of the class corresponding to the parent bean definition is annotated with
@ConstructorPropertiesannotation,thebeanclasscorrespondingtothechildbeandefinitionmustalso
beannotatedwith@ConstructorPropertiesannotation.
The following example listing shows the serviceTemplate (parent bean definition) and
FixedDepositService(childbeandefinition)beandefinitions:
Examplelisting3-20–applicationContext.xml-Parentandchildbeandefinitions
Project–ch03-bankapp-constructor-args-by-name
Sourcelocation-src/main/resources/META-INF/spring
<beanid="serviceTemplate"
class="sample.spring.chapter03.bankapp.base.ServiceTemplate">
<constructor-argname="emailMessageSender"ref="emailMessageSender"/>
<constructor-argname="jmsMessageSender"ref="jmsMessageSender"/>
<constructor-argname="webServiceInvoker"ref="webServiceInvoker"/>
</bean>
<beanid="FixedDepositService"
class="sample.spring.chapter03.bankapp.service.FixedDepositServiceImpl"
parent="serviceTemplate">
<propertyname=“fixedDepositDao"ref="FixedDepositDao"/>
</bean>
TheaboveexamplelistingshowsthattheserviceTemplatebeandefinitionisnotabstract,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
ServiceTemplateclass(referexamplelisting3-21).Aswehavespecifiedconstructorargumentsbyname
in the serviceTemplate bean definition, the ServiceTemplate class’s constructor is annotated with the
@ConstructorPropertiesannotationtoensurethatconstructorargumentnamesareavailabletoSpringat
runtime,asshownhere:

Examplelisting3-21–ServiceTemplateclass
Project–ch03-bankapp-constructor-args-by-name
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/base
packagesample.spring.chapter03.bankapp.base;
importjava.beans.ConstructorProperties;
publicclassServiceTemplate{
.....
@ConstructorProperties({"jmsMessageSender","emailMessageSender","webServiceInvoker"})
publicServiceTemplate(JmsMessageSenderjmsMessageSender,
EmailMessageSenderemailMessageSender,
WebServiceInvokerwebServiceInvoker){.....}
}
As FixedDepositService is a child bean definition of serviceTemplate, the <constructor-arg>
configurationinserviceTemplatebeandefinitionisinheritedbytheFixedDepositServicebeandefinition.
ThismeansthattheFixedDepositServiceImplclassmustdefineaconstructorthatacceptsthesamesetof
arguments as defined by the ServiceTemplate class, and it must also be annotated with
@ConstructorProperties annotation. If you don’t annotate FixedDepositServiceImpl’s constructor with
@ConstructorPropertiesannotation,Springcontainerwillnotbeabletomatchtheinherited<constructor-
arg>elementswiththeconstructorargumentsspecifiedintheFixedDepositServiceImpl’sconstructor.
Youcan’tuse@ConstructorPropertiesannotationforpassingargumentsbynametoastaticorinstance
factorymethod,asexplainednext.
@ConstructorPropertiesannotationandfactorymethods
We saw in section 2-3 of chapter 2 that the <constructor-arg> elements are also used for passing
argumentstostaticandinstancefactorymethods.Youmightthinkthatyoucanpassargumentsbynameto
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 or instance
factorymethod,theonlyoptionyouhaveistocompileclasseswithdebugflagenabled.
NOTEIfyoucompileclasseswithdebugflagenabled,itresultsin.classfilesthatarelargerinsize,but
hasnoimpactontheruntimeperformanceoftheapplication.Itonlyresultsinincreasedloadingtimefor
theclasses.
Let’snowlookathowtoenableordisabledebugflaginEclipseIDE.
Enabling(ordisabling)thedebugflaginEclipseIDE
InEclipseIDE,followthesestepstoenablethedebugflagforprojects:
1.GotoWindowsàPreferencesandselecttheoptionJavaàCompiler
2.You’llnowseeasectiontitled‘ClassfileGeneration’.Inthissection,ifyoucheckthecheckbox
labeled‘Addvariableattributestogeneratedclassfiles(usedbythedebugger)’,thedebugflagis
enabled.Uncheckingthischeckboxwilldisablethedebugflag.
Sofarwehavemostlyseenbeandefinitionexamplesinwhichbeanpropertiesandconstructorarguments
werereferencestootherbeans.We’llnowlookatbeandefinitionexamplesinwhichbeanpropertiesand
constructorargumentsareofprimitivetype,collectiontype,java.util.Date,java.util.Properties,andsoon.

3-4 Configuring different types of bean properties and constructor
arguments
Inrealworldapplicationdevelopmentscenarios,propertiesandconstructorargumentsofaSpringbean
could range from a String type to reference to another bean to any other standard (like java.util.Date,
java.util.Map)orcustom(likeAddress)type.Sofarwehaveseenexamplesofhowtosupplyvaluefor
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
dependenciesviabeanproperties(usingrefattributeof<property>element)andconstructorarguments
(usingrefattributeof<constructor-arg>elements).
Inthissection,we’lllookatbuilt-inPropertyEditorimplementationsinSpringthatsimplifypassingbean
properties and constructor arguments of types java.util.Date, java.util.Currency, primitive type, and so
on.We’llalsolookathowtospecifyvaluesforcollectiontypes(likejava.util.Listandjava.util.Map)in
the application context XML file, and how to register a custom PropertyEditor implementation with
Spring.
Let’s 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.Toruntheapplication,executethemainmethodoftheSampleApp
classofthisproject)
Built-inpropertyeditorsinSpring
JavaBeansPropertyEditorsprovidethenecessarylogicforconvertingaJavatypetoastringvalue,and
viceversa.Springprovidesacoupleofbuilt-inPropertyEditorsthatareusedforconvertingstringvalue
of a bean property or a constructor argument (specified via value attribute of <property> and
<constructor-arg>elements)totheactualJavatypeofthepropertyorconstructorargument.
Beforewelookat examples involvingbuilt-inPropertyEditors,let’s firstunderstand the importance of
PropertyEditorsinsettingvaluesofbeanpropertiesorconstructorarguments.
ConsiderthefollowingBankDetailsclassthatwewanttoconfigureasasingleton-scopedbeanwithpre-
definedvaluesforitsattributes:
Examplelisting3-22–BankDetailsclass
publicclassBankDetails{
privateStringbankName;
publicvoidsetBankName(StringbankName){
this.bankName=bankName;
}
}

Intheaboveexamplelisting,bankNameisanattributeoftheBankDetailsclass,andisoftypeString.The
followingbeandefinitionfortheBankDetailsclassshowshowtosetthevalueofbankNameattributeto
‘MyPersonalBank’:
Examplelisting3-23–BeandefinitionfortheBankDetailsclass
<beanid="bankDetails"class="BankDetails">
<propertyname="bankName"value="MyPersonalBank"/>
</bean>
In the above bean definition, the <property> element’s value attribute specifies a string value for the
bankNameproperty.Asyoucansee,ifabeanpropertyisoftypeString,youcansimplysetthatproperty
valueusing<property> element’s value attribute. Similarly, if a constructor argument is of type String,
youcansettheconstructorargumentvalueusing<constructor-arg>element’svalueattribute.
Let’ssaythatthefollowingattributes(alongwiththeirsettermethods)areaddedtotheBankDetailsclass:
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.ThefollowingexamplelistingshowsthemodifiedBankDetailsclass:
Examplelisting3-24–BankDetailsclasscontainingdifferenttypesofproperties
Project–ch03-simple-types-examples
Sourcelocation-src/main/java/sample/spring/chapter03/beans
packagesample.spring.chapter03.beans;
.....
publicclassBankDetails{
privateStringbankName;
privatebyte[]bankPrimaryBusiness;
privatechar[]headOfficeAddress;
privatecharprivateBank;
privateCurrencyprimaryCurrency;
privateDatedateOfInception;
privatePropertiesbranchAddresses;
.....
publicvoidsetBankName(StringbankName){
this.bankName=bankName;
}
//--moresettermethods
}
YoucanconfiguretheBankDetailsclassasaSpringbeanbyspecifyingstringvaluesfortheproperties,
and letting the Spring container convert these string values into the corresponding Java types of the
propertiesbyusingregisteredJavaBeansPropertyEditorimplementations.
ThefollowingbeandefinitionfortheBankDetailsclassshowsthatsimplestringvaluesarespecifiedfor
differentpropertytypes:

Examplelisting3-25–applicationContext.xml-BeandefinitionfortheBankDetailsclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails">
<propertyname="bankName"value="MyPersonalBank"/>
<propertyname="bankPrimaryBusiness"value="Retailbanking"/>
<propertyname="headOfficeAddress"value="Addressofheadoffice"/>
<propertyname="privateBank"value="Y"/>
<propertyname="primaryCurrency"value="INR"/>
<propertyname="dateOfInception"value="30-01-2012"></property>
<propertyname="branchAddresses">
<value>
x=BranchX'saddress
y=BranchY'saddress
</value>
</property>
</bean>
Theaboveexamplelistingshows thatstring valuesarespecifiedforpropertiesoftypesjava.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
correspondingJavatypeofthepropertyorconstructorargument.Forinstance,Springcontainerconverts
the value ‘30-01-2012’ of dateOfInception property to java.util.Date type using CustomDateEditor (a
built-inPropertyEditorimplementationforjava.util.Datetype).
If you look at how branchAddresses property (of type java.util.Properties) is configured in example
listing 3-25, you’ll notice that instead of <property> element’s value attribute, <value> sub-element of
<property> element has been used to specify the value for the property. In case of single-valued
properties,theuseof<property>element’svalueattributeispreferredover<value>sub-element.But,if
youneedtospecifymultiplevaluesforapropertyorthevaluesneedtobespecifiedonseparatelines(as
inthecaseofbranchAddressesproperty),the<value>sub-elementispreferredovervalueattribute.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-inPropertyEditorimplementationsthatperformthetaskofconverting
valuesspecifiedintheapplicationcontextXMLfiletotheJavatypeofthebeanpropertyorconstructor
argument.Thefollowingtabledescribessomeofthebuilt-inPropertyEditorimplementationsinSpring:
Built-in PropertyEditor
implementation Description
CustomBooleanEditor convertsstringvaluetoBooleanorbooleantype
CustomNumberEditor convertsstringvaluetoanumber(likeint,long,andsoon)
ChracterEditor convertsstringvaluetochartype
ByteArrayPropertyEditor convertsstringvaluetobyte[]
CustomDateEditor convertsstringvaluetojava.util.Datetype
PropertiesEditor convertsstringvaluetojava.util.Propertiestype

Theabovetableshowsonlyasubsetofbuilt-inPropertyEditorimplementationsinSpring.Foracomplete
list,refertotheorg.springframework.beans.propertyeditorspackageofSpring.Itisimportanttonotethat
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
performconversionfromastringvaluetoajava.util.Datetype.Laterinthissection,we’lllookathow
youcanregisterpropertyeditorswithSpringcontainer.
Let’s now look at how to specify values for bean properties (or constructor arguments) of types
java.util.List,java.util.Setandjava.util.Map.
Specifyingvaluesfordifferentcollectiontypes
The <list>, <map> and <set> sub-elements (defined in Spring’s beans schema) of <property> and
<constructor-arg> elements are used to set properties and constructor arguments of type java.util.List,
java.util.Mapandjava.util.Set,respectively.
NOTESpring’sutilschemaalsoprovides<list>,<set>and<map>elementsthatsimplifysetting
propertiesandconstructorargumentsofdifferentcollectiontypes.Laterinthischapter,we’lllookat
Spring’sutilschemaelementsindetail.
ThefollowingDataTypesExampleclassshowsthatitsconstructoracceptsargumentsofdifferenttypes:
Examplelisting3-26–DataTypesExampleclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/java/sample/spring/chapter03/beans
packagesample.spring.chapter03.beans;
importjava.beans.ConstructorProperties;
.....
publicclassDataTypesExample{
privatestaticLoggerlogger=Logger.getLogger(DataTypesExample.class);
@SuppressWarnings("rawtypes")
@ConstructorProperties({"byteArrayType","charType","charArray",
"classType","currencyType","booleanType","dateType","longType",
"doubleType","propertiesType","listType","mapType","setType",
"anotherPropertiesType"})
publicDataTypesExample(byte[]byteArrayType,charcharType,
char[]charArray,ClassclassType,CurrencycurrencyType,
booleanbooleanType,DatedateType,longlongType,
doubledoubleType,PropertiespropertiesType,List<Integer>listType,
MapmapType,SetsetType,PropertiesanotherPropertiesType){
.....
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 class’s constructor accepts arguments of
typesjava.util.List,java.util.Map,java.util.Setandjava.util.Properties,andsoon,andlogsthevalueof
eachconstructorargument.
ThefollowingexamplelistingshowsthebeandefinitionfortheDataTypesExampleclass:
Examplelisting3-27–applicationContext.xml-BeandefinitionforDataTypesExampleclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="anotherPropertiesType">
<props>
<propkey="book">GettingstartedwiththeSpringFramework</prop>
</props>
</constructor-arg>
<constructor-argname="listType"value-type="java.lang.Integer">
<list>
<value>1</value>
<value>2</value>
</list>
</constructor-arg>
<constructor-argname="mapType">
<map>
<entry>
<key>
<value>mapkey1</value>
</key>
<value>mapkey1’svalue</value>
</entry>
</map>
</constructor-arg>
<constructor-argname="setType">
<set>
<value>Element1</value>
<value>Element2</value>
</set>
</constructor-arg>
</bean>
Theaboveexamplelistingshows:
· the value of anotherPropertiesType (of type java.util.Properties) is specified using the
<props>sub-elementof<constructor-arg>element.Each<prop>elementspecifiesakey-value
pair;thekeyattributespecifiesthekeyvalueandthecontentof<prop>elementisthevaluefor
thekey.Insteadofusing<props>element,youcanuse<value>sub-elementof<constructor-arg>
elementtospecifythevalueforanotherPropertiesTypeargument.
·thevalueoflistTypeconstructorargument(oftypejava.util.List)isspecifiedusingthe<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
argumentisoftypeList<Integer>(referexamplelisting3-26),thevalue-typeattribute’svalueis
specifiedasjava.lang.Integer.Thevalue-typeattributeisoptional,andisparticularlyusefulif
you are using a parameterized List type, like List<Integer>. If you specify the value-type
attribute,Springcontainerusestheregisteredpropertyeditorstoperformconversionofvalues
tothetypespecifiedbythevalue-typeattribute,followedbyconverting(ifrequired)thevalues
tothetypeacceptedbytheparameterizedListtype.Ifyoudon’tspecifythevalue-typeattribute,
Springcontainersimplyusestheregisteredpropertyeditorstoperformconversionofvaluesto
thetypeacceptedbytheparameterizedListtype.
·thevalueofmapTypeconstructorargument(oftypejava.util.Map) is specified usingthe
<map>sub-elementof<constructor-arg>.The <entry>sub-elementof <map> specifies a key-
valuepaircontainedintheMap;the<key>elementspecifiesthekeyandthe<value>element
specifiesthevalueforthekey.Thekey-typeandvalue-typeattributesof<map>elementspecify
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>.Springcontainerusesregisteredpropertyeditorstoperformconversion
of keys and values to the types specified by the key-type and value-type attributes, and to the
typesacceptedbytheparameterizedMaptype.
·thevalueofthesetTypeconstructorargument(oftypejava.util.Set)isspecifiedusingthe
<set> sub-element of <constructor-arg>. Each <value> sub-element of <set> specifies an
elementcontainedintheSet.Thevalue-typeattributeof<set>elementspecifiestheJavatypeof
elementsthatjava.util.Setaccepts.Thevalue-typeattributeisoptional,andisusefulifyouare
using parameterized Set type, like Set<Integer>. Spring container uses registered property
editorstoperformconversionofvaluestothetypespecifiedbythevalue-typeattribute,andto
thetypeacceptedbytheparameterizedSettype.
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
collectioncanalsobebeanreferences.Toaddresssuchscenarios,Springallowsyoutouseelementslike
<map>,<set>,<list>,<props>,<ref>,andsoon,assub-elementsof<list>,<map>and<set>elements.
Let’snowlookatexamplesthatdemonstratehowtoadddifferenttypesofelementstoMap,ListandSet
typeconstructorargumentsandbeanproperties.

AddingelementsoftypeList,Map,SetandPropertiestocollectiontypes
IfabeanpropertyorconstructorargumentisoftypeList<List>,simplyuseanested<list>element,as
shownhere:
Examplelisting3-28–Configurationexample:ListinsideaList
<constructor-argname="nestedList">
<list>
<list>
<value>AsimpleStringvalueinthenestedlist</value>
<value>AnothersimpleStringvalueinnestedlist</value>
</list>
</list>
</constructor-arg>
The <constructor-arg> element shown in the above example listing supplies value for a constructor
argumentnamednestedListwhichisoftypeList<List>.Thenested<list>elementrepresentsanelement
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.Aswiththe<list>element,a<set>elementcancontain<set>,<list>,<map>or<props>
element.Incaseofa<map>element,youcanuse<map>,<set>,<list>or<props>elementtospecifykey
andvalueofanentry.
ThefollowingexamplelistingshowshowyoucanspecifyvaluesforaMap<List,Set>typeconstructor
argument:
Examplelisting3-29–Configurationexample:MapcontainingListtypeaskeyandSettypeasvalue
<constructor-argname="nestedListAndSetMap">
<map>
<entry>
<key>
<list>
<value>aListelement</value>
</list>
</key>
<set>
<value>aSetelement</value>
</set>
</entry>
</map>
</constructor-arg>
The above example listing shows that the nestedListAndSetMap constructor argument is of Map type
whosekeyisoftypeListandvalueisoftypeSet.The<key>elementcanhaveeitherofthefollowing
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.
Addingbeanreferencestocollectiontypes
Youcanuse<ref>elementsinside<list>and<set>elementstoaddreferencestobeansintoproperties
andconstructorargumentsoftypeListandSet,respectively.
The following example listing shows how references to beans are added to a List type constructor
argument:
Examplelisting3-30–Configurationexample:Listcontainingreferencetobeans
<bean.....>
<constructor-argname="myList">
<list>
<refbean="aBean"/>
<refbean="bBean"/>
</list>
</constructor-arg>
</bean>
<beanid="aBean"class="somepackage.ABean"/>
<beanid="bBean"class="somepackage.BBean"/>
Theaboveexamplelistingshows that the myList constructorargumentis of typeListand it contains 2
elements-areferencetoaBeanbeanandareferencetobBeanbean.The<ref>element’sbeanattribute
specifiesthenameofthebeanreferencedbythe<ref>element.
Aswiththe<list>element,youcanuse<ref>elementsinside<set>elementtoaddbeanreferencestoa
Set type constructor argument or bean property. In case of <map> element, you can use <ref> element
insidea<key>elementtospecifyabeanreferenceasakey,andusethe<ref>elementtospecifyabean
referenceasavalueforthekey.ThefollowingexamplelistingshowsaMaptypeconstructorargument
thatcontainsasinglekey-valuepairinwhichbothkeyandvaluearereferencestobeans:
Examplelisting3-31–Configurationexample:Mapcontainingbeanreferencesaskeysandvalues
<bean.....>
<constructor-argname="myMapWithBeanRef">
<map>
<entry>
<key>
<refbean="aBean"/>
</key>
<refbean="bBean"/>
</entry>
</map>
</constructor-arg>
</bean>

<beanid="aBean"class="somepackage.ABean"/>
<beanid="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
referencetobBeanbean.
Addingbeannamestocollectiontypes
Ifyouwanttoaddabeanname(asspecifiedbytheidattributeof<bean>element)toaList,MaporSet
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
singlekey-valuepair,wherebeannameisthekeyandbeanreferenceisthevalue:
Examplelisting3-32–Configurationexample:Mapcontainingbeannameaskeyandbeanreferenceas
value
<constructor-argname="myExample">
<map>
<entry>
<key>
<idrefbean="sampleBean"/>
</key>
<refbean="sampleBean"/>
</entry>
</map>
</constructor-arg>
<beanid="sampleBean"class="somepackage.SampleBean"/>
TheaboveexamplelistingshowsthatthemyExampleconstructorargumentisoftypeMapwhosekeyis
thestringvalue‘sampleBean’andvalueisthesampleBeanbean.Wecouldhaveused<value>elementto
set‘sampleBean’stringvalueasthekey,but<idref>elementisusedbecauseSpringcontainerverifies
existenceofthesampleBeanbeanwhentheapplicationisdeployed.
NOTEYoucanusethe<idref>elementinsidea<property>or<constructor-arg>elementtosetabean
nameasthevalueofabeanpropertyorconstructorargument.
Addingnullvaluestocollectiontypes
YoucanaddanullvaluetocollectionsoftypeSetandListusing<null>element.Thefollowingexample
listingshowshowtoaddanullvaluetoaSettypeconstructorargumentusing<null>element:
Examplelisting3-33–Configurationexample:Setcontaininganullelement
<constructor-argname="setWithNullElement">
<set>
<value>Element1</value>
<value>Element2</value>

<null/>
</set>
</constructor-arg>
Intheaboveexamplelisting,setWithNullElementconstructorargumentcontains3elements:Element1,
Element2andnull.
ToaddanullkeytoaMaptypeconstructorargumentorproperty,youcanuse<null>elementinsidethe
<key>element.And,toaddanullvalue,youcanadda<null>elementinsidethe<entry>element.The
following example listing shows a Map type constructor argument that contains a null key and a null
value:
Examplelisting3-34–Configurationexample:Mapcontaininganullkeyandanullvalue
<constructor-argname="mapType">
<map>
<entry>
<key>
<null/>
</key>
<null/>
</entry>
</map>
</constructor-arg>
TheaboveexamplelistingshowsthatanelementwithnullkeyandnullvalueisaddedtothemapType
constructorargumentusing<null>element.
NOTEYoucanalsouse<null>elementinside<property>and<constructor-arg>elementstosetnull
valuesforpropertiesandconstructorarguments,respectively.
Let’snowlookathowtospecifyvaluesforarraytypepropertiesandconstructorarguments.
Specifyingvaluesforarrays
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-
elementof<constructor-arg>element.
Thefollowingexamplelistingshowshowyoucansetabeanpropertyoftypeint[]:
Examplelisting3-35–Configurationexample:Settingvalueofabeanpropertyoftypeint[]
<propertyname="numbersProperty">
<array>
<value>1</value>
<value>2</value>
</array>
</property>
Intheaboveexamplelisting,each<value>sub-elementofthe<array>elementrepresentsanelementin

thenumbersPropertyarray.ThepropertyeditorsregisteredwiththeSpringcontainerareusedtoconvert
thestringvaluespecifiedbyeachofthe<value>elementtointtype.Youcanuse<array>elementinside
<list>,<set>and<map>elements.Youcanalsouse<list>,<set>,<map>,<props>and<ref>elements
insidean<array>elementtocreatearraysofList,Set,Map,Propertiesandbeanreferences,respectively.
Ifyouwanttocreateanarrayofarrays,youcanuse<array>elementsinsidean<array>element.
Wediscussedthat<list>,<map>and<set>elementsareusedtosetpropertiesorconstructorarguments
of type List, Map andSet, respectively. Let’s now look at the default collection implementation that is
createdbySpringforeachoftheseelements.
Defaultcollectionimplementationfor<list>,<set>and<map>elements
The following table shows the default collection implementation that is created by Spring for <list>,
<set>and<map>elements:
Collectionelement DefaultcollectionimplementationcreatedbyS pring
<list> java.util.ArrayList
<set> java.util.LinkedHashSet
<map> java.util.LinkedHashMap
Theabovetablesuggests:
· if aproperty’s(or aconstructor argument’s) value is specified using <list> element, Spring
createsaninstanceofArrayListandassignsittotheproperty(ortheconstructorargument).
· if a property’s (or a constructor argument’s) value is specified using <set> element, Spring
createsaninstanceofLinkedHashSetandassignsittotheproperty(ortheconstructorargument).
·ifaproperty’s(oraconstructorargument’s)valueisspecifiedusing<map>element,Spring
createsaninstanceofLinkedHashMapandassignsittotheproperty(ortheconstructorargument).
It is likely that you may want to substitute a different implementation of List, Set or Map to a bean
propertyoraconstructorargument.Forinstance,insteadofjava.util.ArrayList,youmaywanttoassignan
instanceofjava.util.LinkedListtoabeanpropertyoftypeList.Insuchscenarios,itisrecommendedto
use <list>, <map> and <set> elements of Spring’s util schema (explained in section 3-8). The <list>,
<set>and<map>elementsofSpring’sutilschemaprovidetheoptiontospecifythefully-qualifiedname
oftheconcretecollectionclassthatyouwanttoassigntothepropertyorconstructorargumentofthebean.
Let’snowlookatsomeofthebuilt-inpropertyeditorsprovidedbySpring.

3-5Built-inpropertyeditors
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
CustomDateEditorbuilt-inpropertyeditors.Toviewthecompletelistofbuilt-inpropertyeditors,referto
org.springframework.beans.propertyeditorspackage.
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,
CustomCollectionEditorisregisteredforSet,SortedSetandListtypes.
Consider the following CollectionTypesExampleclass that defines attributes (and corresponding setter
methods)oftypeSetandList:
Examplelisting3-36–CollectionTypesExampleclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/java/sample/spring/chapter03/beans
packagesample.spring.chapter03.beans;
importjava.util.List;
importjava.util.Set;
publicclassCollectionTypesExample{
privateSetsetType;
privateListlistType;
.....
//--settermethodsforattributes
publicvoidsetSetType(SetsetType){
this.setType=setType;
}
.....
}
CollectionTypesExampleclassdefinessetTypeandlistTypeattributesoftypeSetandList,respectively.
ThefollowingexamplelistingshowsthebeandefinitionforCollectionTypesExampleclass:
Examplelisting3-37–applicationContext.xml-BeandefinitionforCollectionTypesExampleclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanclass="sample.spring.chapter03.beans.CollectionTypesExample">
<propertyname="listType">
<set>
<value>setelement1</value>
<value>setelement2</value>

</set>
</property>
<propertyname="setType">
<list>
<value>listelement1</value>
<value>listelement2</value>
</list>
</property>
.....
</bean>
Youmightthinkthattheaboveconfigurationisincorrectbecause<set>elementhasbeenusedtosetthe
valueoflistType property(of type List), and <list> element has been used to set the value of setType
property(oftypeSet).
Theaboveconfigurationiscompletelylegal,andtheSpringcontainerdoesnotcomplain.Thisisbecause
CustomCollectionEditor converts the ArrayList instance (created corresponding to the <list> type
element)toLinkedHashSettype(animplementationofSettype)beforesettingthesetTypeproperty.Also,
CustomCollectionEditorconverts the LinkedHashSet instance (created corresponding to the <set> type
element)toArrayListtype(animplementationofListtype)beforesettingthelistTypeproperty.
Figure3-4–CustomCollectionEditorconvertstheLinkedHashSettoArrayListtype
Figure3-4showsthattheCustomCollectionEditorconvertstheLinkedHashSettypetoArrayListtosetthe
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
LinkedHashSetcorrespondingtothe<set>element.AsthelistTypepropertyisoftypeList(referexample
listing3-36),theCustomCollectionEditorcomesintopictureforsettingthelistTypeproperty’svalue.If
the type of the bean property is List, CustomCollectionEditor creates an instance of ArrayList and
populatesitwiththeelementsfromtheLinkedHashSet.Intheend,thevalueofthelistTypevariableisset
totheArrayListimplementationcreatedbyCustomCollectionEditor.
Itisimportanttonotethatifapropertyorconstructorargumenttypeisaconcretecollectionclass(like
LinkedList),CustomCollectionEditorsimplycreatesaninstanceoftheconcretecollectionclassandadds
elements to it from the source collection. The following figure shows a scenario in which the bean

propertyisoftypejava.util.Vector(aconcretecollectionclass):
Figure3-5CustomCollectionEditorconvertstheArrayListtoVectortype
The above figure shows that the CustomCollectionEditor creates an instance of Vector (a concrete
collectionclass)andaddselementstoitfromthesourcecollection,ArrayList.
Let’snowlookatCustomMapEditorpropertyeditor.
CustomMapEditor
CustomMapEditorpropertyeditordealswithconvertingasourceMaptype(likeHashMap) toa target
Maptype(likeTreeMap).Bydefault,CustomMapEditorisregisteredonlyforSortedMaptype.
Figure3-6showsascenarioinwhichCustomMapEditorconvertsLinkedHashMap(thesourceMaptype)
toTreeMap(animplementationofSortedMaptype).
Figure3-6showsthesequenceofstepsperformedbySpringtosetthevalueofmapTypeproperty.First,
Spring creates an instance of LinkedHashMap corresponding to the <map> element. As the mapType
propertyisoftypeSortedMap,CustomMapEditorcomesintopicturewhilesettingthevalueofmapType
property. CustomMapEditor creates an instance of TreeMap (a concrete implementation of SortedSet
interface),addskey-valuepairsfromLinkedHashMaptothenewlycreatedTreeMapinstanceandassigns
theTreeMapinstancetothemapTypeproperty.

Figure3-6CustomMapEditorconvertstheLinkedHashMap(thesourceMaptype)toTreeMap(thetarget
Maptype)type
CustomDateEditor
CustomDateEditorisapropertyeditorforjava.util.Datetypebeanpropertiesandconstructorarguments.
CustomDateEditorsupportsacustomjava.text.DateFormatthatisusedforformattingadate/timestringto
a java.util.Date type object, and parsing a java.util.Date type object to a date/time string. In the next
section,we’llseehowCustomDateEditorisusedforsettingbeanpropertiesandconstructorargumentsof
typejava.util.Date.In ch03-simple-types-examples project,CustomDateEditor converts the string value
ofabeanproperty(referdateOfInceptionattributeofBankDetailsclass)orconstructorargument(refer
dateTypeconstructorargumentofDataTypesExampleclass)tojava.util.Datetype.
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
bankPrimaryBusinessattributeofBankDetailsclass),CurrencyEditor–forconvertingacurrencycodeto
a java.util.Currency object (refer primaryCurrency attribute of BankDetails class),
CharacterArrayPropertyEditor – for converting a string value to a char[] (refer headOfficeAddress
attributeofBankDetailsclass),andsoon.
Let’snowlookathowtoregisterpropertyeditorswiththeSpringcontainer.

3-6RegisteringpropertyeditorswiththeSpringcontainer
Spring’sBeanWrapperImplclassregistersacoupleofbuilt-inpropertyeditorswiththeSpringcontainer.
Forinstance,CustomCollectionEditor,CustomMapEditor,CurrencyEditor,ByteArrayPropertyEditorand
CharacterArrayEditor property editors are registered by default with the Spring container. But,
CustomDateEditor property editor is not registered by default with the Spring container. To register
propertyeditorswith the Springcontainer,youcanuseSpring’s CustomEditorConfigurerspecial bean.
CustomEditorConfigurer class implements Spring’s BeanFactoryPostProcessor interface (explained in
detailinsection5-4ofchapter5),anditisautomaticallydetectedandexecutedbytheSpringcontainer.
In ch03-simple-types-examples project, BankDetails class (refer example listing 3-24) defines a
dateOfInceptionpropertyoftypejava.util.Date.ThevaluespecifiedforthedateOfInceptionpropertyis
‘30-01-2012’ (refer example listing 3-25). To convert the string value ‘30-01-2012’ to java.util.Date
type,youmustregisteracustompropertyeditorforjava.util.DatetypeoryoucanregisterSpring’sbuilt-
inCustomDateEditorpropertyeditorwiththeSpringcontainer.
ToregisterpropertyeditorswiththeSpringcontainer,youneedtodothefollowing:
1. Create a class that implements Spring’s PropertyEditorRegistrar interface. This class is
responsibleforregisteringpropertyeditorswiththeSpringcontainer.
2.ConfigurethePropertyEditorRegistrarimplementationasaSpringbeanintheapplicationcontext
XMLfile.
3.ConfigureSpring’sCustomEditorConfigurerspecialbeanintheapplicationcontextXMLfile,and
provideitwithreferencetothePropertyEditorRegistrarimplementation(thatyoucreatedinstep1
andconfiguredinstep2).
Let’s now see how CustomDateEditor is registered with the Spring container in ch03-simple-types-
examplesproject.
CreatingaPropertyEditorRegistrarimplementation
The following example listing shows the MyPropertyEditorRegistrar class that implements
PropertyEditorRegistrarinterface:
Examplelisting3-38–MyPropertyEditorRegistrarclass
Project–ch03-simple-types-examples
Sourcelocation-src/main/java/sample/spring/chapter03/beans
packagesample.spring.chapter03.beans;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importorg.springframework.beans.PropertyEditorRegistrar;
importorg.springframework.beans.PropertyEditorRegistry;
importorg.springframework.beans.propertyeditors.CustomDateEditor;

publicclassMyPropertyEditorRegistrarimplementsPropertyEditorRegistrar{
@Override
publicvoidregisterCustomEditors(PropertyEditorRegistryregistry){
registry.registerCustomEditor(Date.class,newCustomDateEditor(
newSimpleDateFormat("dd-MM-yyyy"),false));
}
}
The above example listing shows that the MyPropertyEditorRegistrar class implements Spring’s
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. PropertyEditorRegistry’s
registerCustomEditor method is used for registering a PropertyEditor implementation with the Spring
container. In the above example listing, PropertyEditorRegistry’s registerCustomEditor is used for
registeringaCustomDateEditorpropertyeditorwiththeSpringcontainer.
ConfiguringtheCustomEditorConfigurerclass
The following example listing shows how the CustomEditorConfigurer class is configured in the
applicationcontextXMLfile:
Examplelisting3-39–applicationContext.xml-CustomEditorConfigurerconfiguration
Project–ch03-simple-types-examples
Sourcelocation-src/main/resources/META-INF/spring
<beanid="myPropertyEditorRegistrar"
class="sample.spring.chapter03.beans.MyPropertyEditorRegistrar"/>
<beanid="editorConfigurer"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<propertyname="propertyEditorRegistrars">
<list>
<refbean="myPropertyEditorRegistrar"/>
</list>
</property>
</bean>
In the above example listing, myPropertyEditorRegistrar bean definition configures
MyPropertyEditorRegistrarclassasaSpringbean.MyPropertyEditorRegistrarclassimplementsSpring’s
PropertyEditorRegistrar interface, and is responsible for registering additional property editors with
Spring container. CustomEditorConfigurer’s 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
automaticallydetectedandexecutedbytheSpringcontainer,resultinginregistrationofpropertyeditors
bytheMyPropertyEditorRegistrarinstance.
Let’s now look at how to use p-namespace (for bean properties) and c-namespace (for constructor
arguments)towriteconcisebeandefinitionsinapplicationcontextXMLfiles.

3-7Concisebeandefinitionswithpandcnamespaces
To make bean definitions less verbose in application context XML files, Spring provides p and c
namespaces tospecify values for bean properties andconstructor arguments, respectively. Thep and c
namespacesarealternativestousing<property>and<constructor-arg>elements,respectively.
Let’sfirstlookatp-namespace.
IMPORTchapter3/ch03-namespaces-example(ThisprojectshowsaSpringapplicationinwhichbean
properties and constructor arguments are set using p- and c-namespaces, respectively. To run the
application,executethemainmethodoftheSampleAppclassofthisproject)
p-namespace
Tousep-namespacetosetbeanproperties,specifybeanpropertiesasattributesofthe<bean>element,
andspecifyeachbeanpropertytobeinthep-namespace.
Thefollowingbeandefinitionshowshowtousep-namespacetosetbeanproperties:
Examplelisting3-40–applicationContext.xml-p-namespaceexample
Project–ch03-namespaces-example
Sourcelocation-src/main/resources/META-INF/spring
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation=".....">
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails"
p:bankName="MyPersonalBank"p:bankPrimaryBusiness="Retailbanking"
p:headOfficeAddress="Addressofheadoffice"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
bankDetailsbeandefinitionmakesuseofthepprefixforthep-namespacetospecifybeanproperties.If
you compare the above example listing with the example listing 3-25, you’ll notice that the above
examplelistingislessverbose.Eventhoughitispossibletouseamixof<property>elementsand p-
namespace to specify bean properties, it’s recommended that you choose one style for specifying bean
propertiesanduseitconsistentlyinbeandefinitions.
NOTE As p-namespace is implemented as part of Spring, there is no schema corresponding to p-
namespace. For this reason, you don’t 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,considerusingIntelliJIDEAorSpringSourceToolSuite(STS).
Ifabeanpropertyisnotareferencetoanotherbean,itisspecifiedusingthefollowingsyntax:
p:<property-name>="<property-value>"

here,<property-name>isthenameofthebeanproperty,and<property-value>isthevalueofthebean
property.
Ifabeanpropertyisareferencetoanotherbean,itisspecifiedusingthefollowingsyntax:
p:<property-name>-ref="<bean-reference>"
here,<property-name>isthenameofthebeanproperty,and<bean-reference>istheid(orname)of
thereferencedbean.Itisimportanttonotethatthenameofthebeanpropertyisfollowedby--ref.Asthe
branchAddressespropertyofBankDetailsbeanrepresentsareferencetothebranchAddressesbean,the
branchAddressespropertyisspecifiedasp:branchAddresses-refinexamplelisting3-40.
Let’snowlookathowc-namespaceisusedforsettingconstructorarguments.
c-namespace
To use c-namespace to supply values for constructor arguments, specify constructor arguments as
attributesofthe<bean>element,andspecifyeachconstructorargumenttobeinthec-namespace.
ThefollowingexamplelistingshowstheBankStatementclassthatwe’llconfigureasaSpringbeanusing
c-namespace.
Examplelisting3-41–BankStatementclass
Project–ch03-namespaces-example
Sourcelocation-src/main/java/sample/spring/chapter03/beans
packagesample.spring.chapter03.beans;
importjava.beans.ConstructorProperties;
publicclassBankStatement{
.....
@ConstructorProperties({"transactionDate","amount","transactionType",
"referenceNumber"})
publicBankStatement(DatetransactionDate,doubleamount,
StringtransactionType,StringreferenceNumber){
this.transactionDate=transactionDate;
this.amount=amount;
.....
}
.....
}
ThefollowingbeandefinitionfortheBankStatementclassshowsusageofc-namespaceforsettingvalues
ofconstructorarguments:
Examplelisting3-42–applicationContext.xml-c-namespaceexample
Project–ch03-namespaces-example

Sourcelocation-src/main/resources/META-INF/spring
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation=".....">
.....
<beanid="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
followedforspecifyingconstructorargumentsusingc-namespaceissimilartowhatwesawincaseofp-
namespace.
NOTE As c-namespace is implemented as part of Spring, there is no schema corresponding to c-
namespace. For this reason, you don’t see any schema reference corresponding to c-namespace in
examplelisting 3-42.If youwantyour IDEtoautocompleteconstructorargumentnames whenusingc-
namespace,considerusingIntelliJIDEAorSpringSourceToolSuite(STS).
Ifaconstructorargumentisnotareferencetoanotherbean,itisspecifiedusingthefollowingsyntax:
c:<constructor-argument-name>="<constructor-argument-value>"
here, <constructor-argument-name> is the name of the constructor argument, and <constructor-
argument-value>isthevalueoftheconstructorargument.
Ifaconstructorargumentisareferencetoanotherbean,itisspecifiedusingthefollowingsyntax:
c:<constructor-argument-name>-ref="<bean-reference>"
here,<constructor-argument-name>isthenameoftheconstructorargument,and<bean-reference>is
theid(orname)ofthereferencedbean.Itisimportanttonotethatthenameoftheconstructorargumentis
followedby--ref.Forinstance,ifaconstructorargumentnamedmyargumentrepresentsareferencetoa
beanwithid‘x’,youspecifymyargumentconstructorargumentas:
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,theconfigurationshowninexamplelisting3-42willnotwork.Insuchcases,yousupplyvalues
forconstructorargumentsusingtheirindex,asshownhere:
Examplelisting3-43–Supplyingvaluesforconstructorargumentsusingtheirindex

<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation=".....">
.....
<beanid="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
indexoftheconstructorargumentisprefixedwithanunderscorebecauseattributenamesinXMLcannot
beginwithanumericvalue.Ifaconstructorargumentisareferencetoanotherbean,-refmustbeaddedto
the index of the constructor argument. For instance, if the constructor argument at index 0 represents
referencetoanotherbean,itisspecifiedasc:_0-ref.Eventhoughit’spossibletouseacombinationof
<constructor-arg>elementsandc-namespacetospecifyconstructorarguments,it’srecommendedthatyou
chooseonestyleofspecifyingconstructorargumentsanduseitconsistentlyinbeandefinitions.
Wesawearlierhow<list>,<map>and<set>elementsareusedtosetpropertiesorconstructorarguments
oftypeList,Map andSet, respectively. Let’s now look at Spring’s util schema that simplifies creating
collectiontypes,Propertiestype,constants,andsoon,andexposingthemasaSpringbeans.

3-8Spring’sutilschema
Spring’s util schema simplifies configuring beans by providing a concise way to perform common
configurationtasks.Thefollowingtabledescribesthevariouselementsofutilschema:
Element Description
<list> Createsajava.util.Listtype,andexposesitasabean
<map> Createsajava.util.Maptype,andexposesitasabean
<set> Createsajava.util.Settype,andexposesitasabean
<constant> Exposesapublicstaticfieldonatypeasabean
<property-path> Exposesabeanpropertyasabean
<properties> Createsajava.util.Propertiesfromapropertiesfile,andexposesitasabean
NOTE All the elements of Spring’s util schema accept a scope attribute that identifies whether the
exposedbeanisasingleton-orprototype-scoped.
SpringprovidesaFactoryBeaninterfacethatcanbeimplementedtocreateafactoryobjectresponsible
forcreatingbeaninstances.Insteadofusingutilschema’selementsmentionedintheabovetable,youcan
useanout-of-the-boxFactoryBeanimplementationprovidedbySpringtoperformthesamefunctionality.
Inthissection,we’lllookattheutilschema’selementsandthebuilt-inFactoryBeanimplementationsthat
youcanuseinsteadofutilschema’selements.
IMPORTchapter3/ch03-util-schema-examples(This project shows a Spring application that makes
useofSpring’sutilschemaelementstocreatesharedinstancesofList,Set,Map,andsoon.Torunthe
application,executethemainmethodoftheSampleAppclassofthisproject)
Let’sfirstlookatthe<list>element.
<list>
The<list> element ofSpring’s util schema is used for creating objects of type java.util.List, as shown
here:
Examplelisting3-44–applicationContext.xml-utilschema’s<list>element
Project–ch03-util-schema-examples
Sourcelocation-src/main/resources/META-INF/spring
<beansxmlns="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">
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="listType"ref="listType"/>
.....
</bean>

<util:listid="listType"list-class="java.util.ArrayList">
<value>AsimpleStringvalueinlist</value>
<value>AnothersimpleStringvalueinlist</value>
</util:list>
</beans>
First,youneedtoincludeSpring’sutilschematoaccessitselements.Intheaboveexamplelisting,the
<list>elementofutilschemacreatesaninstanceofjava.util.ArrayListandexposesitasabean.Theid
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 don’t
specify the list-class attribute, an instance of java.util.ArrayList is created by default. The <value>
elementofSpring’sbeansschemaisusedtospecifyindividualelementsofthelist.
As util schema’s <list> element exposes a List instance as a bean, you can refer to the exposed List
instancefromotherbeans.Forinstance,intheaboveexamplelisting,thelistTypeconstructorargument
(oftypejava.util.List) of DataTypesExamplebeanspecifies listType as the value of the ref attribute to
refertotheListinstancecreatedbytheutilschema’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(referexamplelisting3-27),you’llnoticethattheutilschema’s<list>element
gives youcontrol over the List implementation to create. For instance, if you want to create a Vector
insteadofanArrayListinstance,specifyjava.util.Vectorasthevalueofthelist-classattribute.
Let’snowlookatSpring’sListFactoryBeanwhichyoucanuseinsteadofutilschema’s<list>element.
ListFactoryBean
Analternativetousingutilschema’s<list>elementisSpring’sListFactoryBean–afactorythatisused
forcreatinginstancesofjava.util.ListandmakingthemavailableasSpringbeans.
ThefollowingexamplelistingshowshowtheListFactoryBeancanbeusedinsteadoftheutilschema’s
<list>element:
Examplelisting3-45–ListFactoryBeanexample
<beans.....>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="listType"ref="listType"/>
.....
</bean>
<beanid="listType"class="org.springframework.beans.factory.config.ListFactoryBean">
<propertyname="sourceList">
<list>
<value>AsimpleStringvalueinlist</value>
<value>AnothersimpleStringvalueinlist</value>

</list>
</property>
</bean>
</beans>
Intheaboveexamplelisting,thesourceListpropertyofListFactoryBeanspecifiestheelementsinthelist.
Bydefault,ListFactoryBeancreatesaninstanceofjava.util.ArrayList.IfyouwanttheListFactoryBeanto
createaninstanceofanyotherListimplementation(likeVector),settheListFactoryBean’stargetListClass
property.ThetargetListClasspropertyspecifiesthefully-qualifiednameoftheconcreteimplementation
classofjava.util.ListinterfacethatshouldbecreatedbytheListFactoryBean.
Ifyoucompareexamplelistings3-44and3-45,you’llnoticethatusingutilschema’s<list>elementisa
lotsimplerthanusingtheListFactoryBeantocreateaListinstanceandexposeitasabean.
<map>
The <map> element of Spring’s util schema is used for creating an object of type java.util.Map and
exposingitasabean,asshownhere:
Examplelisting3-46–applicationContext.xml-utilschema’s<map>element
Project–ch03-util-schema-examples
Sourcelocation-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">
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="mapType"ref="mapType"/>
.....
</bean>
<util:mapid="mapType"map-class="java.util.TreeMap">
<entrykey="mapkey1"value="mapkey1’svalue"/>
</util:map>
.....
</beans>
Intheaboveexamplelisting,utilschema’s<map>elementcreatesaninstanceofjava.util.TreeMapand
exposes it as a bean. The id attribute specifies the id with which the bean is made available to other
beans,andmap-classattributespecifiesthefully-qualifiednameoftheconcreteimplementationclassof
java.util.Map interface that should be created by the <map> element. The <entry> element of Spring’s
beansschemaspecifiesakey-valuepairinthecreatedMapinstance.
Asthe<map>elementexposesaMapinstanceasabean,theexposedMapinstancecanbereferenced
fromotherbeans.Forinstance,intheaboveexamplelisting,DataTypesExample’smapTypeconstructor

argument (of type java.util.Map) specifies value of ref attribute as mapType to refer to the TreeMap
instancecreatedbythe<map>element.
NOTEWesawearlierinthischapterthat<key>and<value>sub-elementsof<entry>areusedtospecify
akey-valuepaircontainedintheMapinstance.Theexamplelisting3-46showsthatyoucanalsospecify
akey-valuepaircontainedintheMapinstancebyusing<entry>element’skeyandvalueattributes.
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, you’ll 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.LinkedHashMapbydefault.
Let’snowlookatSpring’sMapFactoryBeanthatyoucanuseinsteadofutilschema’s<map>element.
MapFactoryBean
Insteadofusingutilschema’s<map>element,youcanuseSpring’sMapFactoryBean–afactorythatis
usedforcreatinginstancesofjava.util.MapandmakingthemavailableasSpringbeans.
ThefollowingexamplelistingshowshowMapFactoryBeanisused:
Examplelisting3-47–MapFactoryBeanexample
<beans.....>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="mapType"ref="mapType"/>
.....
</bean>
<beanid="mapType"class="org.springframework.beans.factory.config.MapFactoryBean">
<propertyname="sourceMap">
<map>
<entrykey="mapkey1"value="mapkey1’svalue"/>
</map>
</property>
</bean>
.....
</beans>
In the above example listing, MapFactoryBean’s sourceMap property specifies the key-value pairs
containedintheMapinstancecreatedbytheMapFactoryBean.Bydefault,MapFactoryBeancreatesan
instanceofjava.util.LinkedHashMap.YoucancontroltheMapinstancecreatedbyMapFactoryBeanby
setting the targetMapClass property. The targetMapClass specifies the fully-qualified name of the
concreteimplementationclassofjava.util.Mapinterface.Forinstance,ifyouspecifyjava.util.HashMap

asthevalueoftargetMapClass,MapFactoryBeancreatesaninstanceofjava.util.HashMap.
If you compare example listings 3-46 and 3-47, you’ll notice that using util schema’s <map> element
resultsinamoreconciseconfigurationthanMapFactoryBeanforcreatingMapinstances.
<set>
The<set>elementofSpring’sutilschemaisusedforcreatinganobjectoftypejava.util.Setandexposing
itasabean,asshownhere:
Examplelisting3-48–applicationContext.xml-utilschema’s<set>element
Project–ch03-util-schema-examples
Sourcelocation-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">
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="setType"ref="setType"/>
</bean>
<util:setid="setType"set-class="java.util.HashSet">
<value>Element1</value>
<value>Element2</value>
</util:set>
.....
</beans>
Intheaboveexamplelisting,utilschema’s<set>elementcreatesaninstanceofHashSetandexposesitas
aSpringbeanwithidassetType.Theidattributespecifiestheidwithwhichthebeanismadeavailable
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 Spring’s beans schema
specifiesanelementinthecreatedSetinstance.
TheSetinstancecreatedbythe<set>elementcanbereferencedfromotherbeans.Forinstance,inthe
aboveexamplelisting,DataTypesExample’ssetTypeconstructorargument(oftypejava.util.Set)refersto
theHashSetinstancecreatedbythe<set>element.
Insteadofusingutilschema’s<set>element,youcanuseSpring’sSetFactoryBeantocreateaSetinstance
andexposeitasaSpringbean.
SetFactoryBean
Spring’sSetFactoryBeanisafactoryobjectforcreatinginstancesofjava.util.Settype.
ThefollowingexamplelistingshowshowyoucanuseSetFactoryBeantoperformthesamefunctionasthe
utilschema’s<set>element:

Examplelisting3-49–SetFactoryBeanexample
<beans.....>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="setType"ref="setType"/>
.....
</bean>
<beanid="setType"class="org.springframework.beans.factory.config.SetFactoryBean">
<propertyname="sourceSet">
<set>
<value>Element1</value>
<value>Element2</value>
</set>
</property>
</bean>
.....
</beans>
Intheaboveexamplelisting,SetFactoryBean’ssourceSetpropertyspecifiestheelementscontainedinthe
SetinstancecreatedbytheSetFactoryBean.SetFactoryBean’stargetSetClasspropertyspecifiesthefully-
qualified name of the class that implements java.util.Set interface. If the targetSetClass property is
specified,SetFactoryBeancreatesaninstance 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,SetFactoryBeancreatesaninstanceofjava.util.HashSet.IfthetargetSetClasspropertyis
unspecified,SetFactoryBeancreatesaninstanceofjava.util.LinkedHashSet.
The above example listing shows that using util schema’s <set> element results in a more concise
configurationthanusingSetFactoryBeanforcreatingSetinstances.
<properties>
Theutilschema’s<properties>elementisusefulifyouwanttocreateaninstanceofjava.util.Properties
objectfromapropertiesfile,andexposethejava.util.Propertiesobjectasabean.
Thefollowingexamplelistingshowshowthe<properties>elementisused:
Examplelisting3-50–applicationContext.xml-utilschema’s<properties>element
Project–ch03-util-schema-examples
Sourcelocation-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">

<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails">
.....
<propertyname="branchAddresses"ref="branchAddresses"/>
</bean>
.....
<util:propertiesid="branchAddresses"
location="classpath:META-INF/addresses.properties"/>
</beans>
Intheaboveexamplelisting,<properties>elementcreatesaninstanceofjava.util.Propertiescontaining
propertiesloadedfromtheaddresses.propertiesfile(specifiedbythelocationattribute),andexposesthe
java.util.PropertiesinstanceasabeanwithbranchAddressesastheid(specifiedbytheidattribute).The
above example listing also shows that the branchAddresses property (of type java.util.Properties) of
BankDetailsbeanreferstothebranchAddressesbeancreatedbytheutilschema’s<properties>element.
Analternativetousingthe<properties>elementisSpring’sPropertiesFactoryBean.
PropertiesFactoryBean
Spring’sPropertiesFactoryBeanisafactoryforcreatinginstancesofjava.util.Properties.
The following example listing shows how you can use PropertiesFactoryBean to perform the same
functionastheutilschema’s<properties>element:
Examplelisting3-51–PropertiesFactoryBeanexample
<beans.....>
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails">
.....
<propertyname="branchAddresses"ref="branchAddresses"/>
</bean>
<beanid="branchAddresses"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<propertyname="location"value="classpath:META-INF/addresses.properties"/>
</bean>
.....
</beans>
Intheaboveexamplelisting,beandefinitionforSpring’sPropertiesFactoryBeancreates an instance of
java.util.Properties from the properties loaded from addresses.properties file (specified by location
property),andexposesthejava.util.PropertiesinstanceasabeanwithbranchAddressesastheid.
<constant>
Theutilschema’s<constant>elementisusedforexposinganobject’spublicstaticfieldasaSpringbean.
Thefollowingexamplelistingshowsanexampleusageof<constant>element:

Examplelisting3-52–applicationContext.xml-utilschema’s<constant>element
Project–ch03-util-schema-examples
Sourcelocation-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">
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="booleanType"ref="booleanTrue"/>
.....
</bean>
<util:constantid="booleanTrue"static-field="java.lang.Boolean.TRUE"/>
.....
</beans>
Theutilschema’s<constant>elementexposesthevaluespecifiedbyitsstatic-fieldattributeasaSpring
bean. In the above example listing, <constant> element exposes a bean whose value is
java.lang.Boolean.TRUEandidisbooleanTrue.Youcanspecifyanypublicstaticfieldasthevalueofthe
static-fieldattributeand refertoitfromotherbeansintheSpringcontainer.Forinstance,intheabove
example listing, booleanType bean is referenced by DataTypesExample’s booleanType constructor
argumentoftypeboolean.
A rather less concise way to expose public static fields as Spring beans is to use Spring’s
FieldRetrievingFactoryBean.
FieldRetrievingFactoryBean
Spring’sFieldRetrievingFactoryBeanisafactoryforretrievingvalueofapublicstaticfieldspecifiedby
the FieldRetrievingFactoryBean’s staticField property. The value retrieved by the
FieldRetrievingFactoryBeanisexposedasabean.YoucanalsousetheFieldRetrievingFactoryBeanto
retrieveanon-staticfieldvalue.
ThefollowingexamplelistingshowsanexampleusageofFieldRetrievingFactoryBean:
Examplelisting3-53–FieldRetrievingFactoryBeanexample
<beans.....>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<constructor-argname="booleanType"ref="booleanTrue"/>
.....
</bean>
<beanid="booleanTrue"

class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<propertyname="staticField"value="java.lang.Boolean.TRUE"/>
</bean>
.....
</beans>
Intheaboveexamplelisting,FieldRetrievingFactoryBeanretrievesthevalueofjava.lang.Boolean.TRUE
field and exposes it as a bean. The bean exposed by the FieldRetrievingFactoryBean is referenced by
DataTypesExample’sbooleanTypeconstructorargumentoftypeboolean.
<property-path>
Theutilschema’s<property-path>elementisusedtoexposeabeanpropertyvalueasabean.
Thefollowingexamplelistingshowsanexampleusageof<property-path>element:
Examplelisting3-54–applicationContext.xml-utilschema’s<property-path>element
Project–ch03-util-schema-examples
Sourcelocation-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">
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails">
.....
<propertyname="dateOfInception"ref="dateType"/>
.....
</bean>
<util:property-pathid="dateType"path="dataTypes.dateType"/>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<propertyname="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
propertyandexposesitasabeanwithidasdateType.Thepathattributeof<property-path>elementhas
thefollowingsyntax:
<bean-name>.<bean-property>
Here,<bean-name>istheidornameofthebean,and<bean-property>isthenameoftheproperty.

As<property-path>elementexposesa bean,theexposedbean canbereferencedbyother beansinthe
Spring container. For instance in the above example listing, dateType bean is referenced by
dateOfInceptionpropertyofBankDetailsbean.
Instead of using <property-path> element, you can use Spring’s PropertyPathFactoryBean to expose a
beanpropertyvalueasabean.
PropertyPathFactoryBean
PropertyPathFactoryBean is a factory used for creating bean instances that represent a bean property
value.
ThefollowingexamplelistingshowshowtousePropertyPathFactoryBean:
Examplelisting3-55–PropertyPathFactoryBeanexample
<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">
<beanid="bankDetails"class="sample.spring.chapter03.beans.BankDetails">
.....
<propertyname="dateOfInception"ref="dateType"/>
.....
</bean>
<beanid="dataType"
class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<propertyname="targetBeanName"value="dataTypes"/>
<propertyname="propertyPath"value="dateType"/>
</bean>
<beanid="dataTypes"class="sample.spring.chapter03.beans.DataTypesExample">
.....
<propertyname="dateType"value="30-01-2012"/>
.....
</bean>
</beans>
In the above example listing, PropertyPathFactoryBean is used to create an instance of a bean that
representsthevalueofdateTypepropertyofdataTypesbean.PropertyPathFactoryBean’stargetBeanName
attributespecifiestheidornameofthebeanthatcontainstheproperty,andPropertyPathFactoryBean’s
propertyPath attribute specifies thename ofthe property whose valueis tobeexposed 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
referencedbydateOfInceptionproperty(oftypejava.util.Date)ofBankDetailsbean.
Now, that we have taken an in-depth look at util schema elements, let’s look at Spring’s FactoryBean
interface.

3-9FactoryBeaninterface
Spring’sFactoryBeaninterfaceisimplementedbyclassesthatactasafactoryforcreatingbeaninstances.
Intheprevioussection,wesawthattheclassesthatimplementtheFactoryBeaninterfaceareconfigured
intheapplicationcontextXMLfilelikeanyotherbean.FactoryBeanisparticularlyusefulifyouwantto
performcomplicatedconditionalcheckstodecideonwhichbeantypetocreate,andtoexecutecomplex
beaninitializationlogic.
Let’snowlookatanapplicationscenarioinwhichwe’lluseFactoryBeanforselectingabeantype,and
thencreatingit.
MyBankapplication–Storingeventsinthedatabase
In MyBank application, important events, like credit and debit transactions, open and liquidate fixed
deposits,andsoon,aresavedinthedatabase.MyBankmaydirectlysavetheseeventsinthedatabaseor
indirectlybyfirstsendingtheeventstoamessagingmiddlewareorawebservice.Thefollowingtable
describestheclassesthataredefinedbytheMyBankapplicationfordirectlyorindirectlysavingevents:
Class Description
DatabaseEventSender
Classthatcontainsthefunctionalityforsavingeventsinthedatabase
MessagingEventSender Classthatcontainsthefunctionalityforsendingeventstoamessagingmiddleware
WebServiceEventSender Classthatcontainsthefunctionalityforsendingeventstoaremotewebservice
Thedecisiontodirectlysavetheeventsinthedatabaseortosendthemtoamessagingmiddlewareora
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)fromthedatabase.propertiesfileandcreatestheDatabaseEventSenderinstance.Similarly,ifa
messging.propertiesfileexists,MyBankcreatesaninstanceofMessagingEventSenderinstance,andifa
webservice.propertiesfileexists,aninstanceofWebServiceEventSenderiscreated.
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
messagingmiddleware.
The following class diagram shows that the FixedDepositServiceImpl class of MyBank uses either
DatabaseEventSender or MessagingEventSender or WebServiceEventSender instance to directly or
indirectlysaveeventsrelatedtofixeddepositsinthedatabase:

Figure3-7FixedDepositServiceImplclassusesoneoftheimplementationsofEventSenderinterface.
Intheaboveclassdiagram,sendEventmethodofEventSenderinterfacedefinesthecontractfordirectly
or indirectly saving events in the database. DatabaseEventSender, MessagingEventSender and
WebServiceEventSender classes implement the EventSender interface and provide an appropriate
implementationforthesendEventmethod.
Let’snowlookathowFactoryBeansimplifieschoosingtherightimplementationofEventSenderinterface
andinitializingit.
IMPORTchapter3/ch03-bankapp-factorybean(ThisprojectshowstheMyBankapplicationthatusesa
FactoryBean implementation to create objects of type EventSender. To run the application, execute the
mainmethodoftheBankAppclassofthisproject)
MyBank–FactoryBeanexample
In MyBank, selecting the right EventSender implementation and initializing it is an involved task;
therefore,itrepresentsanidealscenarioforusingaFactoryBeanimplementation.FactoryBeaninterface
definesthefollowingmethodsthatyouneedtoimplement:
·getObjectType:returnsthetypeoftheobjectmanagedbytheFactoryBeanimplementation.In
caseofMyBank,theFactoryBeanimplementationcreatesandreturnsobjectsoftypeEventSender.
·getObject:returnstheobjectmanagedbytheFactoryBeanimplementation.IncaseofMyBank,
the getObject method returns an instance of DatabaseEventSender or MessagingEventSender or
WebServiceEventSender.
· isSingleton:returnstrueiftheFactoryBean implementation is afactoryfor singleton-scoped
objects.IftheisSingletonmethodreturnstrue,theobjectreturnedbythegetObjectmethodiscached
bytheSpringcontainerandthesameinstanceisreturnedonsubsequentrequests.IftheFactoryBean
implementationisafactoryforprototype-scopedobjects,returnfalsefromtheisSingletonmethod.
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
isSingletonmethodreturnstrueincaseofMyBank.
ThefollowingexamplelistingshowstheEventSenderFactoryBean–theFactoryBeanimplementationthat

createsandreturnsobjectsoftypeEventSender:
Examplelisting3-56–EventSenderFactoryBeanclass
Project–ch03-bankapp-factorybean
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/event
packagesample.spring.chapter03.bankapp.event;
importorg.springframework.beans.factory.FactoryBean;
importorg.springframework.beans.factory.FactoryBeanNotInitializedException;
importorg.springframework.core.io.ClassPathResource;
.....
publicclassEventSenderFactoryBeanimplementsFactoryBean<EventSender>{
privateStringdatabasePropertiesFile;
privateStringwebServicePropertiesFile;
privateStringmessagingPropertiesFile;
.....
publicEventSendergetObject()throwsException{
EventSendereventSender=null;
Propertiesproperties=newProperties();
ClassPathResourcedatabaseProperties=null;
if(databasePropertiesFile!=null){
databaseProperties=newClassPathResource(databasePropertiesFile);
}
.....
if(databaseProperties!=null&&databaseProperties.exists()){
InputStreaminStream=databaseProperties.getInputStream();
properties.load(inStream);
eventSender=newDatabaseEventSender(properties);
}
elseif(webServiceProperties!=null&&webServiceProperties.exists()){.....}
elseif(messagingProperties!=null&&messagingProperties.exists()){.....}
returneventSender;
}
publicClass<?>getObjectType(){
returnEventSender.class;
}
publicbooleanisSingleton(){
returntrue;
}
}

The above example listing shows that the EventSenderFactoryBean implements FactoryBean interface.
The EventSender parameter in FactoryBean<EventSender> indicates that the FactoryBean’s getObject
returns objects of type EventSender. The databasePropertiesFile, webServicePropertiesFile and
messagingPropertiesFile are properties of the EventSenderFactoryBean class, and they represent the
locationofdatabase.properties,webservice.propertiesandmessaging.propertiesfilesintheclasspath.
ThegetObjectmethodusesSpring’sClassPathResourceclasstoverifywhetherthespecifiedproperties
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 class’s constructor. For instance, in the above example
listing,ifdatabase.propertiesfile(representedbydatabasePropertiesFileproperty)exists,propertiesare
loaded from the database.properties file and passed as an argument to the DatabaseEventSender’s
constructor.ThegetObjectTypemethodreturnsEventSendertypebecausetheEventSenderFactoryBean’s
getObjectmethodreturnsobjectsoftypeEventSender.TheisSingletonmethodreturnstrue,whichmeans
thattheobjectreturnedbygetObjectmethodiscachedbySpringandthesameinstanceisreturnedevery
timeEventSenderFactoryBean’sgetObjectmethodisinvoked.
Now, that you have seen how EventSenderFactoryBean class is implemented in the MyBank, you can
guesshowSpring’sbuilt-inFactoryBeanimplementations,likeListFactoryBean(forcreatinginstancesof
Listtype),MapFactoryBean(forcreatinginstancesofMaptype),SetFactoryBean(forcreatinginstances
ofSettype),andsoon,areimplemented.
The following example listing shows how EventSenderFactoryBean is configured in the application
contextXMLfile:
Examplelisting3-57–applicationContext.xml-EventSenderFactoryBeanconfiguration
Project–ch03-bankapp-factorybean
Sourcelocation-src/main/resources/META-INF/spring
<beans.....>
<beanid="service"
class="sample.spring.chapter03.bankapp.service.FixedDepositServiceImpl">
.....
<propertyname="eventSender"ref="eventSenderFactory"/>
</bean>
.....
<beanid="eventSenderFactory"
class="sample.spring.chapter03.bankapp.event.EventSenderFactoryBean">
<propertyname="databasePropertiesFile"value="META-INF/config/database.properties"/>
</bean>
</beans>
The above example listing shows thattheEventSenderFactoryBean is configured likeanyother Spring
bean.EventhoughaFactoryBeanimplementationisconfiguredlikeanyotherSpringbean,itistreated
differentlybytheSpringcontainer.Oneofthemostimportantdifferencesisthatifabeanisdependenton
a FactoryBean implementation, the Spring container invokes the getObject method of the FactoryBean
implementationandinjectsthereturnedobjectintothedependentbean.

NOTEYoushouldnotethatFactoryBean’sgetObjectmethodisinvokedonlyoncebytheSpring
containeriftheisSingletonmethodreturnstrue.
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
invokestheEventSenderFactoryBean’sgetObjectmethodandinjectsthereturnedEventSenderobjectinto
theFixedDepositServiceImplinstance.
The following example listing shows the FixedDepositServiceImpl class that requires EventSender
instancecreatedbyEventSenderFactoryBean:
Examplelisting3-58–FixedDepositServiceImplclass
Project–ch03-bankapp-factorybean
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp/service
packagesample.spring.chapter03.bankapp.service;
importsample.spring.chapter03.bankapp.event.EventSender;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
.....
privateEventSendereventSender;
publicvoidsetEventSender(EventSendereventSender){
this.eventSender=eventSender;
}
.....
publicvoidcreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
.....
eventSender.sendEvent(event);
}
}
The above example listing shows that the FixedDepositServiceImpl class depends on an EventSender
instanceandnotontheEventSenderFactoryBeaninstance.TheSpringcontainerobtainstheEventSender
instancebyinvokingEventSenderFactoryBean’sgetObjectmethod,andinjectstheobtainedEventSender
instanceintotheFixedDepositServiceImplinstance.
Let’snow lookathowto access theFactoryBean itself and not the bean it creates and returns via the
getObjectmethod.
AccessingtheFactoryBeaninstance
If you want to obtain the FactoryBean itself from the Spring container, prefix the name (or id) of the
factorybeanwithampersand‘&’.
Let’ssaythattheFixedDepositServiceImplclassrequiresaccesstotheEventSenderFactoryBeanitself,
asshownhere:

Example listing 3-59 – FixedDepositServiceImpl class that depends on the EventSenderFactoryBean
itself
packagesample.spring.chapter03.bankapp.service;
importsample.spring.chapter03.bankapp.event.EventSenderFactoryBean;
importsample.spring.chapter03.bankapp.event.EventSender;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
.....
privateEventSenderFactoryBeaneventSenderFactoryBean;
publicvoidsetEventSenderFactoryBean(EventSenderFactoryBeaneventSenderFactoryBean){
this.eventSenderFactoryBean=eventSenderFactoryBean;
}
.....
publicvoidcreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
.....
EventSendereventSender=eventSenderFactoryBean.getObject();
evenSender.sendEvent(event);
}
}
Intheaboveexamplelisting,theFixedDepositServiceImplclassdependsontheEventSenderFactoryBean
itself,andusesitsgetObjectmethodtoobtainaninstanceofEventSenderobject.
Wesawinexamplelisting3-57thatwhenyoudefinetheEventSenderFactoryBeanbeanasadependency
of FixedDepositServiceImpl bean, the Spring container invokes the getObject method of
EventSenderFactoryBeanandinjectsthereturnedEventSenderobjectintotheFixedDepositServiceImpl
bean. To instruct the Spring container to inject the EventSenderFactoryBean itself, add ampersand ‘&’
prefixtotheid(orname)ofthebeanspecifiedbytherefattribute,asshowninthefollowingexample
listing:
Examplelisting3-60–InjectingtheEventSenderFactoryBeaninstanceintotheFixedDepositServiceImpl
bean
<beans.....>
<beanid="service"class="sample.spring.chapter03.bankapp.service.FixedDepositServiceImpl">
.....
<propertyname="eventSenderFactoryBean"ref="&eventSenderFactory"/>
</bean>
.....
<beanid="eventSenderFactory"
class="sample.spring.chapter03.bankapp.event.EventSenderFactoryBean">
<propertyname="databasePropertiesFile"value="META-INF/config/database.properties"/>

</bean>
</beans>
In the above example listing, the following <property> element specifies that the
FixedDepositServiceImplbeanisdependentonEventSenderFactoryBean:
<propertyname="eventSenderFactoryBean"ref="&eventSenderFactory"/>
Noticethattherefattribute’svalueis"&eventSenderFactory".The&prefixinstructstheSpring
containertoinjecttheEventSenderFactoryBeaninstanceitselfintotheFixedDepositServiceImplbean.
The use of ampersand ‘&’ is also required when you want to retrieve the FactoryBean instance itself
usingApplicationContext’sgetBeanmethod.ThefollowingexamplelistingshowstheBankAppclassof
MyBankapplicationthatretrievestheEventSenderobjectcreatedbytheEventSenderFactoryBean, and
theEventSenderFactoryBeaninstanceitself:
Examplelisting3-61–BankAppclass
Project–ch03-bankapp-factorybean
Sourcelocation-src/main/java/sample/spring/chapter03/bankapp
packagesample.spring.chapter03.bankapp;
.....
publicclassBankApp{
privatestaticLoggerlogger=Logger.getLogger(BankApp.class);
publicstaticvoidmain(Stringargs[]){
ApplicationContextcontext=newClassPathXmlApplicationContext(
.....
logger.info("InvokinggetBean(\"eventFactory\")returns:"+
context.getBean("eventSenderFactory"));
logger.info("InvokinggetBean(\"&eventFactory\")returns:"+
context.getBean("&eventSenderFactory"));
}
}
If you execute the main method of the BankApp class shown above, you’ll find that calling
getBean("eventSenderFactory") returns an instance of DatabaseEventSender class, and
getBean("&eventSenderFactory")returnsEventSenderFactoryBeaninstance.
3-10Summary
In this chapter, we saw how you can use bean definition inheritance to create less verbose and easily
manageablebeandefinitions.Themajorityofthischapterfocusedonhowtosetdifferenttypesofbean
properties andconstructorargumentsusingbuilt-inFactoryBeanimplementations,Spring’sutil schema,
and p- and c-namespaces. We also looked at some of the built-in PropertyEditor implementations in
SpringandhowtoregisteradditionalpropertyeditorswiththeSpringcontainer.Inthenextchapter,we’ll
takeanin-depthlookatdependencyinjectionfeatureofSpring.

Chapter4-Dependencyinjection

4-1Introduction
In the previous chapter, we looked at how to configure beans using Spring’s util schema, p- and c-
namespaces,FactoryBeanimplementations,andsoon.Inthischapterwefocusondifferentdependency
injectionscenarios which we typically come across inreal world application development efforts and
howSpringaddressesthesescenarios.
We’llbeginthischapterwithalookatinnerbeans-analternativetousingtherefattributeof<property>
and<constructor-arg> elements. We’ll 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. We’ll wrap this chapter with an in-depth look at
Spring’sautowiringfeature.
IMPORTchapter4/ch04-bankapp-dependencies(Thisprojectshowsusageofinnerbeansand<bean>
element’sdepends-onattribute.Thisprojectalsoshowsimplicationsofdefiningdependenceofsingleton-
scopedbeansonprototype-scopedbeans,andviceversa.Toruntheapplication,executethemainmethod
oftheBankAppclassofthisproject)

4-2Innerbeans
Ifadependencyofabeanisnotsharedbymultiplebeans,youcanconsiderdefiningthedependencyasan
inner bean. An inner bean is defined inside a <property> or <constructor-arg> element by using the
<bean>elementofSpring’sbeansschema.Youshouldnotethataninnerbeanisonlyaccessibletothe
beandefinitionenclosingit,andnottootherbeansregisteredwiththeSpringcontainer.
Thefollowingexamplelistingshowshowwegenerallyrepresentbeandependencies:
Examplelisting4-1–Dependencyspecifiedusing<property>element’srefattribute
<beanid="service"
class="sample.spring.chapter04.bankapp.service.FixedDepositServiceImpl">
<propertyname=“fixedDepositDao"ref="dao"/>
</bean>
<beanid="dao"class="sample.spring.chapter04.bankapp.dao.FixedDepositDaoImpl"/>
Theaboveexamplelistingshowsthattheservicebeanisdependentondaobean.Ifservicebeanisthe
onlybeanthatisdependentonthedaobean,thenyoucandefinethedaobeanasaninnerbeanofservice
bean.
Examplelisting4-2–applicationContext.xml-Innerbeanexample
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/resources/META-INF/spring
<beanid="service"
class="sample.spring.chapter04.bankapp.service.FixedDepositServiceImpl">
<propertyname=“fixedDepositDao">
<beanclass="sample.spring.chapter04.bankapp.dao.FixedDepositDaoImpl"/>
</property>
</bean>
In the above example listing, the bean definition for the FixedDepositDaoImpl class is inside the
<property>elementofservicebean.Ifyoucomparetheaboveexamplelistingwith4-1,you’llnoticethat
the<property> element no longer specifies the ref attribute, and the <bean> element corresponding to
FixedDepositDaoImplclassdoesn’thavetheidattributeanymore.
The<bean>elementcorrespondingtoaninnerbeandefinitiondoesn’tspecifyanidattributebecausean
inner bean is not registered with the Spring container. If you specify an id attribute for an inner bean
definition,itisignoredbytheSpringcontainer.Aninnerbeanisalwaysprototype-scoped;therefore,if
the <bean> element corresponding to an inner bean definition specifies the scope attribute, then it is
ignoredbytheSpringcontainer.Itisimportanttonotethataninnerbeanisanonymousinnature,andit’s
not accessible to other beans (except the bean that contains the inner bean definition) in the Spring
container.
NOTEAsincaseofnormalbeandefinition,youcanuse<property>,<constructor-arg>,andsoon,
elementsinsidethe<bean>elementoftheinnerbeandefinition.

Inthepreviouschapter,wesawthatSpring’sutilschemaelementsareusedtocreatebeansthatrepresent
a List, Set, Map, and so on. We saw that the beans created by Spring’s util schema elements are
referenced by other beans. The concept of inner beans makes it possible to use Spring’s util schema
elements inside <property> and <constructor-arg> elements also, as shown in the following example
listing:
Examplelisting4-3–utilschema’s<list>elementdefinesaninnerbean
<beansxmlns="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">
<beanid="someBean"class="com.sample.SomeBean">
.....
<constructor-argname="listType">
<util:listlist-class="java.util.ArrayList">
<value>AsimpleStringvalueinlist</value>
<value>AnothersimpleStringvalueinlist</value>
</util:list>
</constructor-arg>
.....
</bean>
</beans>
Intheaboveexamplelisting,thelistTypeconstructorargumentisoftypejava.util.List.Thevaluepassed
tothelistTypeconstructorargumentisspecifiedbytheutilschema’s<list>element.Notethatwedidn’t
specifytheidattributeofthe<list>elementbecauseSpringcontainerignoresidsofinnerbeans.
Let’snowlookatdepends-onattributeof<bean>element.

4-3Explicitlycontrollingthebeaninitializationorderwithdepends-on
attribute
Insection1-4ofchapter1,wediscussedthatbeansarecreatedintheorderinwhichtheyaredefinedin
theapplicationcontextXMLfile.Theorderinwhichbeansarecreatedisalsodecidedbasedontheinter-
dependenciesofbeans.Forinstance,ifbeanAacceptsaninstanceofbeanBasaconstructorargument,
theSpringcontainerwillcreatebeanBbeforebeanAirrespectiveoftheorderinwhichtheyaredefined
intheapplicationcontextXMLfile.ThisbehavioroftheSpringcontainerensuresthatthedependencies
ofabean(beanBisadependencyinourexample)arecompletelyconfiguredbeforetheyareinjectedinto
thedependentbean(beanAisadependentbeaninourexample).
In some application scenarios, bean dependencies are not explicitly specified via <property> and
<constructor-arg> elements. If the bean dependencies are not 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-onattribute.
Let’snowlookatanexamplescenarioinwhichdepends-onattributeisusedtocontroltheinitialization
orderofbeans.
MyBank–implieddependenciesbetweenbeans
IntheMyBankapplicationofthepreviouschapter,aFactoryBeanimplementationcreatedanEventSender
objectthatwasusedbytheFixedDepositServiceImplinstancetodirectlyorindirectlystoreeventsinthe
database (refer section 3-9 of chapter 3 for details). Let’s say that instead of using a FactoryBean
implementation for creating an EventSender implementation, the approach shown in the following
diagramisadopted:
Figure4-1–EventSenderSelectorServiceImplclasswritesthenameoftheEventSenderimplementation
intheappConfig.propertiesfile,whichislaterreadbytheFixedDepositServiceImplinstance
Theabovediagramshowsthat:
·anEventSenderSelectorServiceImplclassisusedtodecideontheEventSenderimplementation
(DatabaseEventSender or WebServiceEventSender or MessagingEventSender) to be used by the
FixedDepositServiceImplclass
· EventSenderSelectorServiceImpl class stores the fully-qualified name of the EventSender
implementationintheappConfig.propertiesfile

· FixedDepositServiceImpl class reads the fully-qualified name of the EventSender
implementationfromtheappConfig.propertiesfile,createstheEventSenderobjectandusesitfor
storingfixeddepositeventsinthedatabase
The above approach suggests that the FixedDepositServiceImpl instance won’t 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
implicitlydependentontheEventSenderSelectorServiceImplclass.
Let’s now look at the implication of implicit dependence of FixedDepositServiceImpl instance on the
EventSenderSelectorServiceImplinstance.
Implicitdependencyproblem
Consider the following application context XML file that contains bean definitions for
FixedDepositServiceImplandEventSenderSelectorServiceImplclasses:
Examplelisting4-4–applicationContext.xml-Implicitdependencyexample
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/resources/META-INF/spring
<beans.....>
<beanid="service"
class="sample.spring.chapter04.bankapp.service.FixedDepositServiceImpl">
.....
<constructor-argindex="0"value="META-INF/config/appConfig.properties"/>
</bean>
<beanid="eventSenderSelectorService"
class="sample.spring.chapter04.bankapp.service.EventSenderSelectorServiceImpl">
<constructor-argindex="0"value="META-INF/config/appConfig.properties"/>
</bean>
</beans>
The above application context XML file shows that both FixedDepositServiceImpl and
EventSenderSelectorServiceImplclass’sconstructoracceptlocationoftheappConfig.propertiesfile.The
EventSenderSelectorServiceImplinstanceusestheappConfig.propertiesfileforcommunicatingthefully-
qualifiednameoftheEventSenderimplementationclasstotheFixedDepositServiceImplinstance.Asan
explicit dependence doesn’t exist between service and eventSenderSelectorService beans, Spring
containercreates theirinstancesintheorder inwhich theyare defined intheapplicationcontextXML
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,theFixedDepositServiceImplinstancewillnotbeabletoreadthenameofthefully-qualified
EventSenderimplementationclassfromtheappConfig.propertiesfile.
Let’s now take an in-depth look at the EventSenderSelectorServiceImpl and FixedDepositServiceImpl
classes,andtheappConfig.propertiesfile.

EventSenderSelectorServiceImpl–thewriter
ThefollowingexamplelistingshowstheEventSenderSelectorServiceImplclass:
Examplelisting4-5–EventSenderSelectorServiceImplclass
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importorg.springframework.core.io.ClassPathResource;
importsample.spring.chapter04.bankapp.Constants;
publicclassEventSenderSelectorServiceImpl{
publicEventSenderSelectorServiceImpl(StringconfigFile)throwsException{
ClassPathResourceresource=newClassPathResource(configFile);
OutputStreamos=newFileOutputStream(resource.getFile());
Propertiesproperties=newProperties();
properties
.setProperty(Constants.EVENT_SENDER_CLASS_PROPERTY,
"sample.spring.chapter04.bankapp.event.DatabaseEventSender");
properties.store(os,null);
.....
}
}
TheaboveexamplelistingshowsthatthelocationofappConfig.propertiesfileispassedasaconstructor
argument to the EventSenderSelectorServiceImpl class’s constructor. The
EventSenderSelectorServiceImpl class’sconstructorwritesa property namedeventSenderClass (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
class’s constructor sets the fully-qualified name of the DatabaseEventSender class as the value of
eventSenderClassproperty.
appConfig.properties
The following is the entry that gets added to the appConfig.propertiesfile by
EventSenderSelectorServiceImplclass:
eventSenderClass=sample.spring.chapter04.bankapp.event.DatabaseEventSender
FixedDepositServiceImpl–thereader
The eventSenderClass property written by the EventSenderSelectorServiceImpl instance is read by the

FixedDepositServiceImplinstance,asshowninthefollowingexamplelisting:
Examplelisting4-6–FixedDepositServiceImplclass
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importorg.springframework.core.io.ClassPathResource;
importsample.spring.chapter04.bankapp.Constants;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
privateFixedDepositDaofixedDepositDao;
privateEventSendereventSender;
publicFixedDepositServiceImpl(StringconfigFile)throwsException{
ClassPathResourceconfigProperties=newClassPathResource(configFile);
if(configProperties.exists()){
InputStreaminStream=configProperties.getInputStream();
Propertiesproperties=newProperties();
properties.load(inStream);
StringeventSenderClassString=
properties.getProperty(Constants.EVENT_SENDER_CLASS_PROPERTY);
if(eventSenderClassString!=null){
Class<?>eventSenderClass=Class.forName(eventSenderClassString);
eventSender=(EventSender)eventSenderClass.newInstance();
logger.info("CreatedEventSenderclass");
}else{
logger.info("appConfig.propertiesfiledoesn'tcontaintheinformation"+
"aboutEventSenderclass");
}
}
}
publicvoidcreateFixedDeposit(FixedDepositDetailsfixedDepositDetails)throwsException{
.....
eventSender.sendEvent(event);
}
}
The above example listing shows following sequence of actions are performed by the constructor of
FixedDepositServiceImplclass:
· loads properties from the appConfig.properties file. The configFile constructor argument
representsthelocationoftheappConfig.propertiesfile.
· obtains property named eventSenderClass (represented by
EVENT_SENDER_CLASS_PROPERTY constant defined in the Constants class) from the
properties loaded fromtheappConfig.propertiesfile. The value of eventSenderClass property is
the fully-qualified name of the EventSender implementation class that FixedDepositServiceImpl
needstouse.ThevalueofeventSenderClasspropertyisstoredintheeventSenderClassStringlocal
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
FixedDepositServiceImpl’screateFixedDepositmethod(refertothecreateFixedDepositmethodin
theaboveexamplelisting)todirectlyorindirectlystoreeventsinthedatabase.
YoushouldnotethatifapropertynamedeventSenderClassisnotfoundintheappConfig.propertiesfile,
theeventSenderClassStringvariableisnot set. In this case, the FixedDepositServiceImpl’s constructor
printsthefollowingmessageontheconsole:‘appConfig.propertiesfiledoesn'tcontaintheinformation
aboutEventSenderclass’.
In example listing 4-4, we looked at bean definitions for EventSenderSelectorServiceImpl and
FixedDepositServiceImplclasses, and concluded that the FixedDepositServiceImpl instance is created
beforeEventSenderSelectorServiceImplinstancebecauseSpringcontainerinitializesbeansintheorder
inwhichtheyappearintheapplicationcontextXMLfile.Wesawinexamplelisting4-5thatthecreation
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 will not find any
eventSenderClasspropertyintheappConfig.propertiesfile.ThisshowsthattheFixedDepositServiceImpl
class is implicitly dependent on the EventSenderSelectorServiceImpl class; therefore, the
EventSenderSelectorServiceImplinstancemustbecreatedbeforetheFixedDepositServiceImplinstance.
Howtoaddressimplicitdependencyproblem?
Wecansolvetheimplicitdependencyproblemintwoways:
· we change the order in which bean definitions for EventSenderSelectorServiceImpl and
FixedDepositServiceImpl classes are defined in the application context XML file. If the bean
definitionfortheEventSenderSelectorServiceImplclassappearsbeforethebeandefinitionforthe
FixedDepositServiceImpl class, the EventSenderSelectorServiceImpl instance will be created
beforetheFixedDepositServiceImplinstance.
· use <bean> element’s depends-on attribute to explicitly specify that the service bean
(corresponding to the FixedDepositServiceImpl class) is dependent on the
eventSenderSelectorServicebean(correspondingtotheEventSenderSelectorServiceImplclass).
Thefollowingexamplelistingshowstheusageof<bean>element’sdepends-onattribute:

Examplelisting4-7–<bean>element’sdepends-onattribute
<beans.....>
<beanid="service"
class="sample.spring.chapter04.bankapp.service.FixedDepositServiceImpl"
depends-on="eventSenderSelectorService">
.....
</bean>
<beanid="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
dependentontheeventSenderSelectorServicebean.Thedepends-onattributespecifiestheidsornames
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
(correspondingtotheFixedDepositServiceImplclass)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'tcontaintheinformationaboutEventSenderclass’.
Multipleimplicitdependencies
Ifabeanhasmultipleimplicitdependencies,youcanspecifyidsornamesofallthosedependenciesas
thevalueofdepends-onattribute,asshownhere:
Examplelisting4-8–depends-onattributeexample-multipleimplicitdependencies
<beans.....>
<beanid="abean".....depends-on="bBean,cBean">
.....
</bean>
.....
</beans>
Theaboveexamplelistingshowsthatyoucanspecifymultiplebeanidsornamesasthevalueofdepends-
onattribute.
depends-onattributeandbeandefinitioninheritance
It is important to note that the depends-on attribute is not inherited by child bean definitions. The

following example listing shows an abstract serviceTemplate parent bean definition that uses the
depends-onattributetospecifybaseServicebeanasadependency:
Examplelisting4-9–depends-onattribute–beandefinitioninheritance
<beanid="serviceTemplate"class=".....ServiceTemplate"depends-on="baseService"
abstract="true"/>
<beanid="someService"class=".....SomeServiceImpl"parent="serviceTemplate"/>
<beanid="someOtherService"class=".....SomeOtherServiceImpl"parent="serviceTemplate"/>
<beanid="baseService"class=".....BaseServiceImpl"/>
Intheaboveexamplelisting,someServiceandsomeOtherServicechildbeandefinitionsdon’tinheritthe
depends-on attribute from the serviceTemplate parent bean definition. As the Spring container creates
beansintheorderinwhichtheyaredefinedintheapplicationcontextXMLfile,thebaseServicebeanis
createdafterthecreationofsomeServiceandsomeOtherServicebeans.
Let’s now look at how the Spring container manages dependencies of singleton- and prototype-scoped
beans.

4-4Singleton-andprototype-scopedbean’sdependencies
Asingleton-scopedbean(anditssingleton-scopeddependencies)iscreatedwhentheApplicationContext
instance is created. And, a prototype-scoped bean (and its prototype-scoped dependencies) is created
eachtimeApplicationContext’sgetBeanmethodisinvokedtoobtaintheprototype-scopedbean.
If a singleton-scoped bean is dependent on a prototype-scoped bean, or vice versa, things get a bit
complicated.Forinstance,ifasingleton-scopedbeanisdependentonaprototype-scopedbean,youmight
ask the question whether the Spring container will create the prototype-scoped bean (the dependency)
beforethesingleton-scopedbean(thedependentbean)?ortheSpringcontainerwillcreateandinjectthe
prototype-scopedbeaninstanceonlywhenyoucalltheApplicationContext’sgetBeanmethodtoretrieve
the singleton-scoped bean instance? The answers to these questions lies in the way singleton- and
prototype-scopeddependenciesofabeanaremanagedbytheSpringcontainer,asexplainednext.
Singleton-scopedbean’sdependencies
The following example listing shows the singleton-scoped customerRequestService bean of MyBank
application,anditsdependencies:
Examplelisting4-10–applicationContext.xml-DependenciesofcustomerRequestServicebean
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRequestService"
class="sample.spring.chapter04.bankapp.service.CustomerRequestServiceImpl">
<constructor-argname="customerRequestDetails"ref="customerRequestDetails"/>
<constructor-argname="customerRequestDao"ref="customerRequestDao"/>
</bean>
<beanid="customerRequestDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRequestDetails"
scope="prototype"/>
<beanid="customerRequestDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRequestDaoImpl"/>
TheaboveexamplelistingshowsthatthecustomerRequestService (singleton-scoped)beandepends on
customerRequestDetails (prototype-scoped) and customerRequestDao (singleton-scoped) beans.
CustomerRequestServiceobject(representedbythecustomerRequestServicebean)representsaservice
that is invoked when a bank customer creates a new request, like a cheque book request.
CustomerRequestServiceputsthedetailsofthecustomerrequestintoaCustomerRequestDetails object
(represented by the customerRequestDetails bean) and saves it in the data store using
CustomerRequestDaoobject(representedbythecustomerRequestDaobean).
ThefollowingexamplelistingshowsthemainmethodofBankAppclassthatloadsthebeandefinitions
showninexamplelisting4-10:
Examplelisting4-11–BankAppclass

Project–ch04-bankapp-dependencies
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp
packagesample.spring.chapter04.bankapp;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassBankApp{
privatestaticLoggerlogger=Logger.getLogger(BankApp.class);
publicstaticvoidmain(Stringargs[])throwsException{
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
.....
logger.info("BeginningwithaccessingCustomerRequestService");
CustomerRequestServicecustomerRequestService_1
=context.getBean(CustomerRequestService.class);
.....
CustomerRequestServicecustomerRequestService_2
=context.getBean(CustomerRequestService.class);
.....
logger.info("DonewithaccessingCustomerRequestService");
}
}
The above example listing shows that after the ApplicationContext instance is created,
ApplicationContext’sgetBeanmethodisinvokedtwicetoobtainreferencetothecustomerRequestService
bean.
IfyouexecutethemainmethodoftheBankAppclass,you’llseethefollowingoutput:
CreatedCustomerRequestDetailsinstance
CreatedCustomerRequestDaoImplinstance
CreatedCustomerRequestServiceImplinstance
.....
BeginningwithaccessingCustomerRequestService
DonewithaccessingCustomerRequestService
The‘Created.....’messagesshownintheaboveoutputareprintedbytheconstructorsoftherespective
bean classes. The above output shows that the customerRequestDetails (prototype-scoped) and
customerRequestDao(singleton-scoped)dependenciesofthecustomerRequestService(singleton-scoped)
bean are created and injected into the customerRequestService instance when the Spring container is
created.Asno‘Created.....’message was printed on the console between‘Beginning.....’ and ‘Done
.....’ messages, no bean instances were created by the Spring container when ApplicationContext’s
getBeanmethodwasinvokedtoretrievethecustomerRequestServicebean.
Figure4-2showsthesequencediagramthatdepictsthesequenceofeventsthatoccurwhenBankApp’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)
beansarefirstcreated,followedbycreationofcustomerRequestService(singleton-scoped).Constructor-
based DI is used to inject the customerRequestDetails and customerRequestDao beans into the
customerRequestServicebean.Asasingleton-scopedbeaniscreatedonlyoncebytheSpringcontainer,
theSpringcontainerhasonlyoneopportunitytoinjectcustomerRequestServicebean’sdependencies.For
thisreason,theSpringcontainerinjectsprototype-scopedcustomerRequestDetailsbeaninstanceintothe
customerRequestService bean only once. The implication of this behavior is that the
customerRequestServicebeanendsupholdingreferencetothesamecustomerRequestDetailsbeanduring
itslifetime.
Figure 4-2 - The sequence of events that occur when the Spring container is created and the
customerRequestServicebeanisretrievedfromtheSpringcontainer
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 onlyonce during the lifetime of the customerRequestService bean. This
meansthatirrespectiveofwhethersetter-orconstructor-basedDIisused,asingletonbeaniscreatedand
configuredonlyonceduringit’slifetime.
Now,oncetheSpringcontaineriscreated,anyrequestforthesingleton-scopedcustomerRequestService
beanreturnsthesamecachedinstanceofthecustomerRequestServicebean.Forthisreason,no‘Created
.....’messagewaswrittenouttotheconsolebetween‘Beginning.....’and‘Done.....’messageswhenwe
executedBankApp’smainmethod(referexamplelisting4-11).
As the singleton-scoped customerRequestService bean always holds reference to the same prototype-
scopedcustomerRequestDetailsbean, itmay adversely affectthe behavior ofMyBank application.For
instance, if multiple customers simultaneously submit request to the CustomerRequestServiceImpl
instance,alltherequestswillresultinmodifyingthesameinstanceoftheCustomerRequestDetailsobject
heldbytheCustomerRequestService.Ideally,CustomerRequestServiceImplshouldcreateanewinstance
ofCustomerRequestDetailsobjectoneveryrequest.Insection4-5,we’llseewhatmodificationsweneed
tomaketothebeanclassofasingleton-scopedbeansothatitcanretrieveanewinstanceofaprototype-
scopedbeanoneverymethodcall.

Let’snowlookathowtheSpringcontainermanagesprototype-andsingleton-scopeddependenciesofa
prototype-scopedbean.
Prototype-scopedbean’sdependencies
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
CustomerRegistrationServiceImplclassofMyBankapplicationcontainsthenecessarybusinesslogicto
registercustomers.AsthecustomersfollowasequenceofstepstoregisterwiththeMyBankapplication,
theCustomerRegistrationServiceImplobjectmaintainsconversationalstatebetweenmethodcalls.
The following example listing shows the prototype-scoped customerRegistrationService bean
(representingtheCustomerRegistrationServiceImplclass)ofMyBankapplication,anditsdependencies:
Examplelisting4-12–applicationContext.xml-customerRegistrationServicebeananditsdependencies
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRegistrationService"
class="sample.spring.chapter04.bankapp.service.CustomerRegistrationServiceImpl"
scope="prototype">
<constructor-argname="customerRegistrationDetails"ref="customerRegistrationDetails"/>
<constructor-argname="customerRegistrationDao"ref="customerRegistrationDao"/>
</bean>
<beanid="customerRegistrationDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRegistrationDetails"
scope="prototype"/>
<beanid="customerRegistrationDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRegistrationDaoImpl"/>
TheaboveexamplelistingshowsthatthecustomerRegistrationService(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(representedbythecustomerRegistrationDetailsbean).AsbothCustomerRegistrationServiceImpl
and CustomerRegistrationDetails objects are stateful in nature, both customerRegistrationService and
customerRegistrationDetailsbeansaredefinedasprototype-scopedbeans.
ThefollowingexamplelistingshowsthemainmethodofBankAppclassthatloadscustomerregistration
relatedbeans(referexamplelisting4-12)andperformsregistrationsfor2customers:
Examplelisting4-13–BankAppclass
Project–ch04-bankapp-dependencies
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp

packagesample.spring.chapter04.bankapp;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassBankApp{
privatestaticLoggerlogger=Logger.getLogger(BankApp.class);
publicstaticvoidmain(Stringargs[])throwsException{
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
.....
logger.info("BeginningwithaccessingCustomerRegistrationService");
CustomerRegistrationServicecustomerRegistrationService_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("registeredcustomerwithidaccount_1");
CustomerRegistrationServicecustomerRegistrationService_2=context
.getBean(CustomerRegistrationService.class);
.....
logger.info("registeredcustomerwithidaccount_2");
logger.info("DonewithaccessingCustomerRegistrationService");
}
}
The above example listing shows that the BankApp’smain method calls ApplicationContext’s 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’llseethefollowingoutputontheconsole:
CreatedCustomerRegistrationDaoImplinstance
.....
BeginningwithaccessingCustomerRegistrationService
CreatedCustomerRegistrationDetailsinstance
CreatedCustomerRegistrationServiceImplinstance
registeredcustomerwithidaccount_1
CreatedCustomerRegistrationDetailsinstance
CreatedCustomerRegistrationServiceImplinstance

registeredcustomerwithidaccount_2
DonewithaccessingCustomerRegistrationService
The‘Created.....’messagesshownintheaboveoutputareprintedbytheconstructorsoftherespective
bean classes. The above output shows that the singleton-scoped customerRegistrationDao bean
(representingtheCustomerRegistrationDaoImplclass)iscreatedonlyoncewhentheApplicationContext
instance is created. The ‘Created.....’ messages between ‘Beginning.....’ and ‘Done.....’ messages
indicatethateachtimeApplicationContext’sgetBeanmethod isinvokedto obtaintheprototype-scoped
customerRegistrationService bean, a new instance of the customerRegistrationService bean and its
prototype-scopeddependency(thecustomerRegistrationDetailsbean)iscreatedbytheSpringcontainer.
Figure4-3showsthesequencediagramthatdepictsthesequenceofeventsthatoccurwhenBankApp’s
main method (refer example listing 4-13) is executed. The figure shows that the singleton-scoped
customerRegistrationDaobeaniscreatedonlyoncewhenApplicationContextinstanceiscreated.When
theprototype-scopedcustomerRegistrationServicebeanisrequestedfromtheSpringcontainer,theSpring
container first creates an instance of customerRegistrationDetails bean (which is the prototype-scoped
dependency of the customerRegistrationService bean), followed by the creation of the
customerRegistrationServicebean.Thisshowsthatifaprototype-scopedbeanXisdependentonanother
prototype-scopedbeanY,SpringcontainerwillcreateanewinstanceofXandYeachtimeyourequest
beanXfromtheSpringcontainer.
Figure 4-3 – The sequence of events that occur when the Spring container is created and the
customerRegistrationServicebeanisretrievedfromtheSpringcontainer
Earlierinthissection,wesawthatifasingleton-scopedbeanisdependentonaprototype-scopedbean,
then throughout its lifetime the singleton-scoped bean is associated with the same instance of the
prototype-scopedbean.Let’snowlookatdifferentwaysinwhichasingleton-scopedbeancanretrievea
newinstanceofaprototype-scopedbeanfromtheSpringcontainer.

4-5Obtainingnewinstancesofprototypebeansinsidesingletonbeans
In the previous section, we saw that the prototype-scoped dependency of a singleton-scoped bean is
injectedatthetimeofcreationofthesingleton-scopedbean(referfigure4-2).Springcontainercreates
instanceofasingleton-scopedbeanonlyonce;therefore,thesingleton-scopedbeanholdsreferencetothe
sameprototype-scopedbeaninstanceduringitslifetime.Asingleton-scopedbean’smethodscanretrieve
a new instance of their prototype-scoped dependency from the Spring container using any one of the
followingapproaches:
·makethesingleton-scopedbean’sclassimplementSpring’sApplicationContextAwareinterface
·usethe<lookup-method>elementofSpring’sbeansschema
·usethe<replaced-method>elementofSpring’sbeansschema
NOTEItispossibletousethenewkeywordtocreateaninstanceoftheprototype-scopedbean’sclassin
asingleton-scopedbean’smethodanduseit.Astheresponsibilityofcreatingabeaninstanceiswiththe
Springcontainer,weshouldnotattempttodirectlycreateabeaninstanceusingthenewkeyword.
IMPORTchapter4/ch04-bankapp-context-aware(Thisprojectshowsascenarioinwhichasingleton-
scopedbeanimplementsSpring’sApplicationContextAwareinterfacetoobtaininstancesofaprototype-
scopedbeanfromtheSpringcontainer.Toruntheapplication,executethemainmethodoftheBankApp
classofthisproject)
Let’sfirstbeginbylookingattheApplicationContextAwareinterface.
ApplicationContextAwareinterface
Spring’s 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
ApplicationContextobject.
ApplicationContextAwareinterfaceisalifecycleinterface,whichmeansthattheSpringcontainercalls
thebeansimplementingtheApplicationContextAwareinterfaceatappropriatetimesduringtheirlifetime.
Forinstance,ApplicationContextAware’ssetApplicationContextmethodiscalledbytheSpringcontainer
afterthebeaninstanceiscreatedbutbeforethebeaninstanceiscompletelyinitialized.Abeaninstanceis
consideredcompletelyinitializedonlyafteritsinitializationmethod(refersection5-2ofchapter5)is
calledbytheSpringcontainer.Itisimportanttonotethatafterabeaninstanceiscompletelyinitialized,it
is injected into the dependent bean instances by the Spring container. In chapter 5, we’ll look at some
morelifecycleinterfacesinSpring.
AbeanthatimplementstheApplicationContextAwareinterfacecanaccessotherbeansregisteredwiththe
ApplicationContextinstancebycallingApplicationContext’sgetBeanmethod.Thismeansthatifthebean
class of a singleton-scoped bean implements ApplicationContextAware interface, it can fetch a new
instanceofaprototype-scopedbeanfromtheSpringcontainerbycallingApplicationContext’sgetBean
method.Asthesingleton-scopedbeanexplicitlyobtainsitsprototype-scopeddependencyfromtheSpring
containerbycallingApplicationContext’sgetBeanmethod,youdon’tneedtodefinetheprototype-scoped
beanasadependencyofthesingleton-scopedbeanintheapplicationcontextXMLfile.

ThefollowingexamplelistingshowstheCustomerRequestServiceImplclassthatneedsanewinstanceof
CustomerRequestDetails object each time CustomerRequestServiceImpl’s submitRequest method is
called:
Examplelisting4-14–CustomerRequestServiceImplclass
Project–ch04-bankapp-context-aware
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importsample.spring.chapter04.bankapp.dao.CustomerRequestDao;
importsample.spring.chapter04.bankapp.domain.CustomerRequestDetails;
publicclassCustomerRequestServiceImplimplementsCustomerRequestService{
privateCustomerRequestDetailscustomerRequestDetails;
privateCustomerRequestDaocustomerRequestDao;
@ConstructorProperties({"customerRequestDetails","customerRequestDao"})
publicCustomerRequestServiceImpl(CustomerRequestDetailscustomerRequestDetails,
CustomerRequestDaocustomerRequestDao){
this.customerRequestDetails=customerRequestDetails;
this.customerRequestDao=customerRequestDao;
}
publicvoidsubmitRequest(StringrequestType,StringrequestDescription){
//--populateCustomerRequestDetailsobjectandsaveit
customerRequestDetails.setType(requestType);
customerRequestDetails.setDescription(requestDescription);
customerRequestDao.submitRequest(customerRequestDetails);
}
}
TheaboveexamplelistingshowsthattheCustomerRequestDetailsandCustomerRequestDaoobjectsare
passedasargumentstotheCustomerRequestServiceImplclass’sconstructor.ThesubmitRequestmethod
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
obtainanewinstanceoftheCustomerRequestDetailsobjectfromtheSpringcontaineroneachinvocation.
The following example listing shows the CustomerRequestServiceContextAwareImpl class (a modified
versionofCustomerRequestServiceImplclassthatwesawinexamplelisting4-14)thatimplementsthe
ApplicationContextAwareinterface:
Example listing 4-15 – CustomerRequestServiceContextAwareImpl class that implements Spring’s
ApplicationContextAwareinterface
Project–ch04-bankapp-context-aware

Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ApplicationContextAware;
publicclassCustomerRequestServiceContextAwareImplimplements
CustomerRequestService,ApplicationContextAware{
privateCustomerRequestDaocustomerRequestDao;
privateApplicationContextapplicationContext;
@ConstructorProperties({"customerRequestDao"})
publicCustomerRequestServiceContextAwareImpl(CustomerRequestDaocustomerRequestDao)
{
this.customerRequestDao=customerRequestDao;
}
publicvoidsetApplicationContext(ApplicationContextapplicationContext)
throwsBeansException{
this.applicationContext=applicationContext;
}
publicvoidsubmitRequest(StringrequestType,StringrequestDescription){
CustomerRequestDetailscustomerRequestDetails=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
CustomerRequestDetailsobjectfromtheSpringcontainer.
As the CustomerRequestServiceContextAwareImpl class explicitly obtains CustomerRequestDetails
object from the Spring container, you don’t need to use Spring’s DI mechanism to inject
CustomerRequestDetails instance intotheCustomerRequestServiceContextAwareImpl instance. For this
reason, CustomerRequestServiceContextAwareImpl class’s constructor (refer example listing 4-15)
doesn’tspecifyCustomerRequestDetailsobjectasanargument.Ifyounowgotoch04-bankapp-context-
awareprojectandexecuteBankApp’smainmethod,you’llfindthatoneachinvocationofsubmitRequest
methodanewinstanceofCustomerRequestDetailsobjectisfetchedfromtheSpringcontainer.

InthecontextofMyBank,wesawthattheApplicationContextAwareinterfaceisusefulifabeanrequires
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
FrameworkandstillaccessotherbeansfromtheSpringcontainerbyusingmethodinjectiontechniques
offeredby<lookup-method>and<replaced-method>elementsofSpring’sbeansschema.
Let’sfirstlookatthe<lookup-method>element.
IMPORT chapter 4/ch04-bankapp-lookup-method (This project shows the MyBank application that
uses<lookup-method>elementofSpring’sbeansschema.Toruntheapplication,executethemainmethod
oftheBankAppclassofthisproject)
<lookup-method>element
Ifabeanclassdefinesabeanlookupmethodwhosereturntyperepresentsabean,the<lookup-method>
element instructs the Spring container to provide implementation for this method. The method
implementationprovidedbytheSpringcontainerisresponsibleforretrievingthebeaninstancefromthe
Springcontainerandreturningit.
The <lookup-method> element’s bean attribute specifies the name of the bean to be looked-up and
returnedbythemethodimplementation,andthenameattribute specifies the nameof themethodwhose
implementation is to be provided by the Spring container. It is important to note that the bean lookup
methoddefinedbythebeanclasscanbeanabstractoraconcretemethod.
NOTETheuseof<lookup-method>elementtoinstructtheSpringcontainertoprovideimplementation
forabeanlookupmethodisreferredtoasa‘MethodInjectiontechinique’becausethe<lookup-method>
elementinjectsabeanlookupmethodimplementationintothebeanclass.
The following example listing shows CustomerRequestServiceImpl’s getCustomerRequestDetails
abstractmethodthatreturnsaninstanceofCustomerRequestDetailsinstance:
Examplelisting4-16–CustomerRequestServiceImplclass–definingabeanlookupmethod
Project–ch04-bankapp-lookup-method
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
publicabstractclassCustomerRequestServiceImplimplementsCustomerRequestService{
privateCustomerRequestDaocustomerRequestDao;
@ConstructorProperties({"customerRequestDao"})
publicCustomerRequestServiceImpl(CustomerRequestDaocustomerRequestDao){
this.customerRequestDao=customerRequestDao;
}
publicabstractCustomerRequestDetailsgetCustomerRequestDetails();
@Override

publicvoidsubmitRequest(StringrequestType,StringrequestDescription){
//--populateCustomerRequestDetailsobjectandsaveit
CustomerRequestDetailscustomerRequestDetails=getCustomerRequestDetails();
.....
}
}
The above example listing shows that the CustomerRequestServiceImpl class is defined as abstract
becauseitcontainsanabstractbeanlookupmethod,getCustomerRequestDetails.Insteadofabstract,we
could have very well defined the getCustomerRequestDetails method as a concrete method. The
submitRequest method invokes the getCustomerRequestDetails method to access a
CustomerRequestDetailsinstance.
The following example listing shows bean definitions for CustomerRequestServiceImpl and
CustomerRequestDetailsclasses:
Examplelisting4-17–applicationContext.xml-<lookup-method>elementusage
Project–ch04-bankapp-lookup-method
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRequestService"
class="sample.spring.chapter04.bankapp.service.CustomerRequestServiceImpl">
<constructor-argname="customerRequestDao"ref="customerRequestDao"/>
<lookup-methodbean="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> element’s name attribute is
getCustomerRequestDetails, which instructs the Spring container to provide implementation for the
getCustomerRequestDetailslookupmethod(referexamplelisting4-16)ofCustomerRequestServiceImpl
class.Thevalueof<lookup-method> element’s beanattributeiscustomerRequestDetails, 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
getCustomerRequestDetailsmethodreturnsaCustomerRequestDetailsobject.
In example listing 4-16, the CustomerRequestService’s submitRequest method invokes the
getCustomerRequestDetails bean lookup method to obtain a CustomerRequestDetails instance. As
CustomerRequestDetailsclassisrepresentedasaprototype-scopedbeanintheapplicationcontextXML
file (refer example listing4-17), each invocation of thesubmitRequest methodresultsin retrieval ofa
newinstanceofCustomerRequestDetailsobjectfromtheSpringcontainer.
To check that the <lookup-method> element provides correct implementation for the

CustomerRequestService’s getCustomerRequestDetails bean lookup method, the main method of
BankAppclassobtainsaninstanceofCustomerRequestServicefromtheSpringcontainerandinvokesits
submitRequestmethodmultipletimes.IfeachinvocationofthesubmitRequestmethodresultsinretrieval
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
getCustomerRequestDetailsmethod.
ThefollowingexamplelistingshowstheBankApp’smainmethodthatinvokesCustomerRequestService’s
submitRequestmethodmultipletimes:
Examplelisting4-18–BankAppclass
Project–ch04-bankapp-lookup-method
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp
packagesample.spring.chapter04.bankapp;
.....
publicclassBankApp{
privatestaticLoggerlogger=Logger.getLogger(BankApp.class);
publicstaticvoidmain(Stringargs[])throwsException{
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
.....
logger.info("BeginningwithaccessingCustomerRequestService");
CustomerRequestServicecustomerRequestService_1=context
.getBean(CustomerRequestService.class);
customerRequestService_1.submitRequest("checkBookRequest",
"Requesttosenda50-leafcheckbook");
customerRequestService_1.submitRequest("checkBookRequest",
"Requesttosenda100-leafcheckbook");
.....
logger.info("DonewithaccessingCustomerRequestService");
}
}
IfyouexecutetheBankApp’smainmethod,you’llseethefollowingoutputontheconsole:
BeginningwithaccessingCustomerRequestService
CreatedCustomerRequestDetailsinstance
CreatedCustomerRequestDetailsinstance
.....
DonewithaccessingCustomerRequestService
The‘Created.....’messagesshownintheaboveoutputareprintedbytheconstructorsoftherespective
beanclasses.TheaboveoutputshowsthateachinvocationofCustomerRequestService’ssubmitRequest
methodresultedinretrievalofanewCustomerRequestDetailsinstancefromtheSpringcontainer.
AstheimplementationofthebeanlookupmethodisprovidedbytheSpringcontainer,somerestrictions

applytothesignatureofthebeanlookupmethods.Forinstance,thebeanlookupmethodmustbedefined
aspublicorprotected,anditmustnotacceptanyarguments.Asthebeanclasscontainingthebeanlookup
methodissubclassedatruntimebytheSpringcontainertoprovidetheimplementationforthebeanlookup
method,thebeanclassandthebeanlookupmethodmustnotbedefinedasfinal.
NOTE As the bean class containing the bean lookup method needs to be subclassed at runtime by the
Springcontainertoprovideimplementationforthebeanlookupmethod,theSpringcontainerusesCGLIB
(http://cglib.sourceforge.net/)librarytoperformsubclassingofthebeanclass.StartingwithSpring3.2,
the CGLIB classes are packaged within the spring-core JAR file itself; therefore, you don’t need to
explicitlyspecifythatyourprojectisdependentonCGLIBJARfile.
The<lookup-method> element provides a method injection technique in which a bean class defines a
beanlookupmethodwhoseimplementationisprovidedbytheSpringcontainer.Insteadofusing<lookup-
method> element, you can consider using <replaced-method> element of Spring’s beans schema to
performmethodinjection.
IMPORTchapter4/ch04-bankapp-replaced-method(ThisprojectshowstheMyBankapplicationthat
uses <replaced-method> element of Spring’s beans schema. To run the application, execute the main
methodoftheBankAppclassofthisproject)
<replaced-method>element
The<replaced-method>elementallowsyoutoreplaceanyarbitrarymethodinabeanclass
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:
Examplelisting4-19–CustomerRequestServiceImplclass
Project–ch04-bankapp-replaced-method
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
.....
publicclassCustomerRequestServiceImplimplementsCustomerRequestService{
privateCustomerRequestDaocustomerRequestDao;
.....
publicObjectgetMyBean(StringbeanName){
returnnull;
}
@Override
publicvoidsubmitRequest(StringrequestType,StringrequestDescription){
//--populateCustomerRequestDetailsobjectandsaveit
CustomerRequestDetailscustomerRequestDetails=
(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.ThegetMyBeanmethodacceptsnameofabeanasanargument,andinsteadofreturningthebean
instance corresponding to the bean name argument, the getMyBean method returns null. The
submitRequestmethodpassescustomerRequestDetailsstringasargumenttothegetMyBeanmethodand
assumes that the getMyBean method returns an instance of customerRequestDetails bean. Using
<replaced-method>element,youcanoverridethegetMyBeanmethodwithamethodthatreturnsthebean
instancecorrespondingtothebeannameargument.
The <replaced-method> element needs information about the overridden method (which is
CustomerRequestServiceImpl getMyBean method in our example scenario) and the overriding method.
TheoverridingmethodisprovidedbytheclassthatimplementsSpring’sMethodReplacerinterface.The
following example listing shows MyMethodReplacer class that implements the MethodReplacer
interface:
Examplelisting4-20–MyMethodReplacerclass
Project–ch04-bankapp-replaced-method
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importorg.springframework.beans.factory.support.MethodReplacer;
importorg.springframework.context.ApplicationContextAware;
publicclassMyMethodReplacerimplementsMethodReplacer,ApplicationContextAware{
privateApplicationContextapplicationContext;
@Override
publicObjectreimplement(Objectobj,Methodmethod,Object[]args)throwsThrowable{
returnapplicationContext.getBean((String)args[0]);
}
@Override
publicvoidsetApplicationContext(ApplicationContextapplicationContext)
throwsBeansException{
this.applicationContext=applicationContext;
}
}
Spring’sMethodReplacerinterfacedefinesareimplementmethodwhoseimplementationisprovidedby
the MyMethodReplacer class. The reimplement method represents the overriding method.
MyMethodReplacer class also implements Spring’s ApplicationContextAware interface so that the
reimplement method can access the ApplicationContext instance. The reimplement method uses the
ApplicationContext’sgetBeanmethodtoretrievebeansfromtheSpringcontainer.

Thereimplementmethodacceptsthefollowingarguments:
·Objectobj–identifiestheobjectwhosemethodweareoverriding.Inourexamplescenario,the
objobjectistheCustomerRequestServiceImplobject.
· Methodmethod – identifies the bean class’s method that is overridden by the reimplement
method.Inourexamplescenario,thisisCustomerRequestServiceImpl’sgetMyBeanmethod.
·Object[]args–identifiesargumentspassedtothemethodthatweareoverriding.Inourexample
scenario,args represents the arguments passed to the CustomerRequestServiceImpl’s getMyBean
method.Inexamplelisting4-20,args[0]inthereimplementmethodrefersthebeannameargument
passedtotheCustomerRequestServiceImpl’sgetMyBeanmethod.
IfyounowlookatMyMethodReplacer’sreimplementmethodinexamplelisting4-20,youcaninferthatit
usesargs argument to first obtain bean name passed to the CustomerRequestServiceImpl’s getMyBean
method,andthencallsApplicationContext’sgetBeanmethodtoobtainthecorrespondingbeaninstance.
As MyMethodReplacer’s reimplement method overrides CustomerRequestServiceImpl’s getMyBean
method,calltogetMyBeanmethod at runtime returns thebeaninstance whose name was passed tothe
getMyBeanmethod.
The <replaced-method> element informs the Spring container that MyMethodReplacer’s reimplement
methodoverridesCustomerRequestServiceImpl’sgetMyBeanmethod,asshowninthefollowingexample
listing:
Examplelisting4-21–applicationContext.xml-<replaced-method>elementusage
Project–ch04-bankapp-replaced-method
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRequestService"
class="sample.spring.chapter04.bankapp.service.CustomerRequestServiceImpl">
<constructor-argname="customerRequestDao"ref="customerRequestDao"/>
<replaced-methodname="getMyBean"replacer="methodReplacer"/>
</bean>
<beanid="methodReplacer"
class="sample.spring.chapter04.bankapp.service.MyMethodReplacer"/>
The above example listing shows bean definitions for MyMethodReplacer and
CustomerRequestServiceImplclasses.The<replace-method>element’snameattributespecifiesnameof
the method that you want to override, and the replacer attribute specifies reference to the bean that
implementstheMethodReplacerinterface.Themethodspecifiedbythenameattributeisoverriddenby
thereimplementmethodofthebeanreferencedbythereplacerattribute.
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
CustomerRequestService’s getMyBean method with the MyMethodReplacer’s reimplement method.
BankAppclassofch04-bankapp-replaced-methodprojectissameastheonewesawinexamplelisting
4-18 for ch04-bankapp-lookup-methodproject. If you execute the main method of the BankApp class,
you’llfindthat<replaced-method>elementoverridesCustomerRequestServiceImpl’sgetMyBeanmethod

withMyMethodReplacer’sreimplement method; therefore, a fresh instance of CustomerRequestDetails
instanceisretrievedfromtheSpringcontainereachtimeCustomerRequestServiceImpl’ssubmitRequest
method(referexamplelisting4-19)isinvoked.
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
getMyBeanmethodasanabstractmethodandusedthe<replaced-method>elementinthesamewayas
describedinthissection.
NOTEAsthebeanclassneedstobesubclassedatruntimebytheSpringcontainertoreplaceabean
methodwithadifferentmethod,theSpringcontainerusesCGLIB(http://cglib.sourceforge.net/)libraryto
performsubclassingofthebeanclass.StartingwithSpring3.2,theCGLIBclassesarepackagedwithin
thespring-coreJARfileitself;therefore,youdon’tneedtoexplicitlyspecifythatyourprojectis
dependentonCGLIBJARfile.
Let’snowlookathow<replaced-method>elementuniquelyidentifiesthebeanmethodtobeoverridden.
Uniquelyidentifyingthebeanmethod
You may come across scenarios in which the bean method that you want to replace using <replaced-
method>elementcan’tbeuniquelyidentifiedbyname.Forinstance,thefollowingexamplelistingshows
abeanclassthatcontainsoverloadedperformmethods:
Examplelisting4-22–Overloadedmethodsinabeanclass
publicclassMyBean{
publicvoidperform(Stringtask1,Stringtask2){.....}
publicvoidperform(Stringtask){.....}
publicvoidperform(my.Tasktask){.....}
}
In theabove examplelisting, theMyBean class contains multiplemethods named perform. To uniquely
identifythebeanmethodtobeoverridden,the<replaced-method>elementuses<arg-type>sub-elements
to specify method argument types. For instance, the following example listing shows how <replaced-
method>elementspecifiesthattheperform(String,String)methodofMyBeanclassshouldbereplaced:
Examplelisting4-23–<replaced-method>elementwith<arg-type>sub-element
<beanid="mybean"class="MyBean">
<replaced-methodname="perform"replacer=".....">
<arg-type>java.lang.String</arg-type>
<arg-type>java.lang.String</arg-type>
</replaced-method>
</bean>
Insteadofusingthefully-qualifiednameasthevalueof<arg-type>element,youcanuseasubstringofthe
fully-qualifiednameasthevalue.Forinstance,insteadofusingjava.lang.String,youcanspecifyStror
Stringasthevalueof<arg-type>elementintheaboveexamplelisting.
Let’snowlookatSpring’sautowiringfeaturethatsavesyoutheeffortofspecifyingbeandependenciesin
theapplicationcontextXMLfile.

4-6Autowiringdependencies
In Spring, you have the option to either explicitly specify bean dependencies using <property> and
<constructor-arg>elementsorletSpringautomaticallyresolvebeandependencies.Theprocessinwhich
dependenciesareautomaticallyresolvedbySpringisreferredtoas‘autowiring’.
IMPORTchapter4/ch04-bankapp-autowiring(This project shows the MyBank application that uses
Spring’sautowiringfeaturefordependencyinjection.Toruntheapplication,executethemainmethodof
theBankAppclassofthisproject)
The<bean>element’sautowireattributespecifieshowabean’sdependenciesareautomaticallyresolved
by Spring. The autowire attribute can take any one of the following values: default, byName, byType,
constructorandno.Let’snowlookateachoftheseattributevaluesindetail.
NOTEYoushouldnotethatthe<bean>element’sautowireattributeisnotinheritedbychildbean
definitions.
byType
Ifyouspecifyautowireattribute’svalueasbyType,Springautowiresbeanpropertiesbasedontheirtype.
For instance, if a bean A defines a property of type X, Spring finds a bean of type X in the
ApplicationContextandinjectsitintobeanA.Let’slookatanexampleusageofbyTypeautowiringinthe
MyBankapplication.
ThefollowingexamplelistingshowstheMyBankapplication’sCustomerRegistrationServiceImplclass:
Examplelisting4-24–CustomerRegistrationServiceImplclass
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
publicclassCustomerRegistrationServiceImplimplementsCustomerRegistrationService{
privateCustomerRegistrationDetailscustomerRegistrationDetails;
privateCustomerRegistrationDaocustomerRegistrationDao;
....
publicvoidsetCustomerRegistrationDetails(
CustomerRegistrationDetailscustomerRegistrationDetails){
this.customerRegistrationDetails=customerRegistrationDetails;
}
publicvoidsetCustomerRegistrationDao(
CustomerRegistrationDaocustomerRegistrationDao){
this.customerRegistrationDao=customerRegistrationDao;
}
.....
}

The above example listing shows that the CustomerRegistrationServiceImpl class defines properties
namedcustomerRegistrationDetails(oftypeCustomerRegistrationDetails)andcustomerRegistrationDao
(of type CustomerRegistrationDao). This means that the CustomerRegistrationDetails and
CustomerRegistrationDaoobjectsaredependenciesofCustomerRegistrationServiceImplobject.
The following example listing shows bean definitions for CustomerRegistrationServiceImpl,
CustomerRegistrationDetails and CustomerRegistrationDaoImpl (an implementation of
CustomerRegistrationDaointerface)classes:
Examplelisting4-25–applicationContext.xml-autowiringbyTypeconfiguration
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRegistrationService"
class="sample.spring.chapter04.bankapp.service.CustomerRegistrationServiceImpl"
scope="prototype"autowire="byType"/>
<beanid="customerRegistrationDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRegistrationDetails"
scope="prototype"/>
<beanid="customerRegistrationDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRegistrationDaoImpl"/>
Intheaboveexamplelisting,thecustomerRegistrationServicebeandefinitiondoesn’tcontain<property>
elementsforsettingcustomerRegistrationDetailsandcustomerRegistrationDaoproperties(referexample
listing4-24).Instead,the<bean>elementspecifiesautowireattribute’svalueasbyTypetoinstructSpring
to automatically resolve dependencies of the customerRegistrationService bean based on their type.
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
customerRegistrationDetailsandcustomerRegistrationDaobeansintocustomerRegistrationServicebean.
It may happen that Spring doesn’t 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
ApplicationContextthatmatchthepropertytype,anexceptionisthrown.Insuchcases,insteadofusing
autowiringfeature,use<property>elementstoexplicitlyidentifybeandependenciesorsetabeanasthe
primarycandidateforautowiringbysettingthevalueofprimaryattributeof<bean>elementtotrue.
constructor
If you specify autowire attribute’s value as constructor, Spring autowires bean class’s constructor
argumentsbasedontheirtype.Forinstance,ifbeanA’sconstructoracceptsargumentsoftypeXandY,
SpringfindsbeansoftypesXandYintheApplicationContextandinjectsthemasargumentstobeanA’s
constructor.Let’slookatanexampleusageofconstructorautowiringintheMyBankapplication.

ThefollowingexamplelistingshowstheMyBankapplication’sCustomerRequestServiceImplclass:
Examplelisting4-26–CustomerRequestServiceImplclass
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
publicclassCustomerRequestServiceImplimplementsCustomerRequestService{
privateCustomerRequestDetailscustomerRequestDetails;
privateCustomerRequestDaocustomerRequestDao;
@ConstructorProperties({"customerRequestDetails","customerRequestDao"})
publicCustomerRequestServiceImpl(
CustomerRequestDetailscustomerRequestDetails,
CustomerRequestDaocustomerRequestDao){
this.customerRequestDetails=customerRequestDetails;
this.customerRequestDao=customerRequestDao;
}
.....
}
The CustomerRequestServiceImpl class defines a constructor that accepts arguments of type
CustomerRequestDetailsandCustomerRequestDao.
The following example listing shows bean definitions for CustomerRequestServiceImpl,
CustomerRequestDetails and CustomerRequestDaoImpl (an implementation of CustomerRequestDao
interface)classes:
Examplelisting4-27–applicationContext.xml-constructorautowiring
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRequestService"
class="sample.spring.chapter04.bankapp.service.CustomerRequestServiceImpl"
autowire="constructor">
</bean>
<beanid="customerRequestDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRequestDetails"scope="prototype"/>
<beanid="customerRequestDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRequestDaoImpl"/>
In theaboveexamplelisting,thecustomerRequestServicebeandefinitionspecifiesautowire 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 class’s constructor. As customerRequestDetails and customerRequestDao

beans are of type CustomerRequestDetails and CustomerRequestDao, Spring automatically injects
instancesofthesebeansintocustomerRequestServicebean.
IfSpringdoesn’tfindanybeanintheApplicationContextwhosetypematchestheconstructorargument
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 the primary
candidateforautowiringbysettingvalueofprimaryattributeof<bean>elementtotrue.
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
ApplicationContextandinjectsitintobeanA.Let’slookatanexampleusageofbyNameautowiringinthe
MyBankapplication.
ThefollowingexamplelistingshowstheMyBankapplication’sFixedDepositServiceImplclass:
Examplelisting4-28–FixedDepositServiceImplclass
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importsample.spring.chapter04.bankapp.dao.FixedDepositDao;
importsample.spring.chapter04.bankapp.domain.FixedDepositDetails;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
privateFixedDepositDaomyFixedDepositDao;
publicvoidsetMyFixedDepositDao(FixedDepositDaomyFixedDepositDao){
this.myFixedDepositDao=myFixedDepositDao;
}
.....
}
The above example listing shows that FixedDepositServiceImpl class defines a property named
myFixedDepositDaooftypeFixedDepositDao.
The following example listing shows bean definitions for FixedDepositServiceImpl and
FixedDepositDaoImpl(animplementationofFixedDepositDaointerface)classes:
Examplelisting4-29–applicationContext.xml-byNameautowiring
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/resources/META-INF/spring
<beanid="FixedDepositService"
class="sample.spring.chapter04.bankapp.service.FixedDepositServiceImpl"
autowire="byName"/>

<beanid="myFixedDepositDao"
class="sample.spring.chapter04.bankapp.dao.FixedDepositDaoImpl"/>
Intheaboveexamplelisting,FixedDepositServicebeandefinitionspecifiesautowireattribute’svalueas
byName, which means properties of FixedDepositService bean are automatically resolved by Spring
basedontheirnames.Inlisting4-28,wesawthattheFixedDepositServiceImplclassdefinesaproperty
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
FixedDepositServicebean.
default/no
Ifyouspecifyautowireattribute’svalueasdefaultorno,autowiringfeatureisdisabledforthebean.As
Spring’s default behavior is to use no autowiring for beans, specifying autowire attribute’s value as
defaultmeansnoautowiringwillbeperformedforthebean.Youcanexplicitlyspecifythatabeanmust
notuseSpring’sautowiringfeaturebyspecifyingautowireattribute’svalueasno.
NOTEYoucanchangethedefaultautowiringbehaviorofbeansbysettingthedefault-autowireattribute
of<beans>element.For instance, if you set default-autowire attribute’s value tobyType, it effectively
meanssettingvalueofautowireattributeofallthe<bean>elementsintheapplicationcontextXMLfileto
byType.Youshouldnotethatifa<bean>element’sautowireattributespecifiesadifferentvaluethanthe
<beans>element’sdefault-autowireattribute,the<bean>element’sautowireattributevalueappliestothe
bean.
The following example listing shows the bean definition for the MyBank application’s
CustomerRegistrationServiceImplclassthatspecifiesautowireattribute’svalueasno:
Examplelisting4-30–applicationContext.xml-noautowiring
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/resources/META-INF/spring
<beanid="customerRegistrationService_"
class="sample.spring.chapter04.bankapp.service.CustomerRegistrationServiceImpl"
scope="prototype"autowire="no"/>
Example listing 4-24 showed that the CustomerRegistrationServiceImpl class defines
customerRegistrationDetails(oftypeCustomerRegistrationDetails)andcustomerRegistrationDao(oftype
CustomerRegistrationDao) properties. As the autowire attribute’s value is specified as no for
customerRegistrationService_bean,autowiringisdisabledforcustomerRegistrationService_bean.This
means that the customerRegistrationDetails and customerRegistrationDao properties of
customerRegistrationService_beanarenotsetbySpring.
So far in this section we have seen different ways in which bean dependencies can be autowired by
Spring.Let’snowlookathowwecanmakeabeanunavailableforautowiringpurposesusing<bean>
element’sautowire-candidateattribute.

Makingbeansunavailableforautowiring
ThedefaultbehavioroftheSpringcontaineristomakebeansavailableforautowiring.Youcanmakea
beanunavailabletootherbeansforautowiringpurposesbysettingautowire-candidateattribute’svalueto
false.
In MyBank application, the AccountStatementServiceImpl class defines a property of type
AccountStatementDao.ThefollowingexamplelistingshowstheAccountStatementServiceImplclass:
Examplelisting4-31–AccountStatementServiceImplclass
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/java/sample/spring/chapter04/bankapp/service
packagesample.spring.chapter04.bankapp.service;
importsample.spring.chapter04.bankapp.dao.AccountStatementDao;
importsample.spring.chapter04.bankapp.domain.AccountStatement;
publicclassAccountStatementServiceImplimplementsAccountStatementService{
privateAccountStatementDaoaccountStatementDao;
publicvoidsetAccountStatementDao(AccountStatementDaoaccountStatementDao){
this.accountStatementDao=accountStatementDao;
}
.....
}
The following example listing shows bean definitions for AccountStatementServiceImpl and
AccountStatementDaoImpl(animplementationofAccountStatementDaointerface)classes:
Examplelisting4-32–applicationContext.xml-autowire-candidateattribute
Project–ch04-bankapp-autowiring
Sourcelocation-src/main/resources/META-INF/spring
<beanid="accountStatementService"
class="sample.spring.chapter04.bankapp.service.AccountStatementServiceImpl"
autowire="byType"/>
<beanid="accountStatementDao"
class="sample.spring.chapter04.bankapp.dao.AccountStatementDaoImpl"
autowire-candidate="false"/>
Intheaboveexamplelisting,theaccountStatementServicebeandefinitionspecifiesautowireattribute’s
valueas byType, which means AccountStatementDaopropertytype ofaccountStatementService bean is
autowiredbytype.AsaccountStatementDaobeanisoftypeAccountStatementDao,you mightthink that
Spring will inject accountStatementDao bean instance into accountStatementService bean. But, Spring
won’t consider accountStatementDao bean for autowiring purposes because the accountStatementDao
beandefinitionspecifiesautowire-candidateattribute’svalueasfalse.

NOTEYoushouldnotethatabeanthatisunavailabletootherbeansforautowiringpurposescanitself
makeuseofSpring’sautowiringfeaturetoautomaticallyresolveit’sdependencies.
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> element’s 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 usageof default-autowire-
candidatesattribute:
Examplelisting4-33–default-autowire-candidatesattributeexample
<beansdefault-autowire-candidates="*Dao">
.....
<beanid="customerRequestDetails"
class="sample.spring.chapter04.bankapp.domain.CustomerRequestDetails"
scope="prototype"autowire-candidate="true"/>
<beanid="customerRequestDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRequestDaoImpl"/>
<beanid="customerRegistrationDao"
class="sample.spring.chapter04.bankapp.dao.CustomerRegistrationDaoImpl"/>
.....
</beans>
Intheaboveexamplelisting,default-autowire-candidatesvalueissetto*Dao,whichmeansthatbeans
whose names end with Dao (like customerRequestDao and customerRegistrationDao beans) will be
available for autowiring purposes. If a bean name doesn’t match the pattern specified by the default-
autowire-candidates attribute (like customerRequestDetails bean), you can still make it available for
autowiringpurposesbysettingtheautowire-candidateattributeofthecorresponding<bean>elementto
true.
Let’snowlookatlimitationsofusingautowiringinapplications.
Autowiringlimitations
Wesawthatautowiringfeaturesavestheefforttoexplicitlyspecifybeandependenciesusing<property>
and<constructor-arg>elements.Thedownsidesofusingautowiringfeatureare:
·Youcan’tuseautowiringtosetpropertiesorconstructorargumentsthatareofsimpleJavatypes
(likeint,long,boolean,String,Date, and so on). You canautowire arrays, typed collections and
mapsiftheautowireattribute’svalueissettobyTypeorconstructor.
· As bean dependencies are automatically resolved by Spring, it results in hiding the overall
structureoftheapplication.Ifyouuse<property>and<constructor-arg>elementstospecifybean
dependencies,itresultsinexplicitlydocumentingtheoverallstructureoftheapplication.Youcan
easily understand and maintain an application in which bean dependencies are explicitly
documented.Forthisreason,itisnotrecommendedtouseautowiringinlargeapplications.
4-7Summary
Inthischapter,welookedathowSpringcaterstodifferentdependencyinjectionscenarios.Welookedat
how you can use ApplicationContextAware interface, <replaced-method> and <lookup-method> sub-
elementsof<bean> element toprogrammaticallyretrieve 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
beansandbeandefinitions.

Chapter5-Customizingbeansandbeandefinitions
5-1Introduction
SofarinthisbookwehaveseenexamplesinwhichtheSpringcontainercreatedabeaninstancebasedon
thebeandefinitionspecifiedintheapplicationcontextXMLfile.Inthischapter,we’llgoastepfurther
andlookat:
·howtoincorporatecustominitializationanddestructionlogicforabean
·howtointeractwithanewlycreatedbeaninstancebyimplementingSpring’sBeanPostProcessor
interface
·howtomodifybeandefinitionsbyimplementingSpring’sBeanFactoryPostProcessorinterface

5-2Customizingbean’sinitializationanddestructionlogic
We saw in earlier chapters that the Spring container is responsible for creating a bean instance and
injectingitsdependencies.Aftercreatingabeaninstancebyinvokingtheconstructorofthebeanclass,the
Springcontainersetsbeanpropertiesbyinvokingbean’ssettermethods.Ifyouwanttoexecutecustom
initialization logic (like opening a file, creating a database connection, and so on) after the bean
propertiesaresetbutbeforethebeaniscompletelyinitializedbytheSpringcontainer,youcandosoby
specifyingthenameoftheinitializationmethodasthevalueofinit-methodattributeof<bean>element.
Similarly,ifyou wantto executecustomcleanuplogic before the Spring container containingthe bean
instance is destroyed, you can specify the name of the cleanup method as the value of destroy-
methodattributeof<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
destructionmethods.Totestwhethertheinitializationmethodisexecuted,executethemainmethodofthe
BankApp class of this project. To test whether the destruction method is executed, execute the main
methodoftheBankAppWithHookclassofthisproject.)
The following example listing shows the MyBank’s FixedDepositDaoImpl class that defines an
initializationmethodnamedinitializeDbConnectionforobtainingconnectiontoMyBank’sdatabase,anda
destructionmethodnamedreleaseDbConnectionforreleasingtheconnection:
Examplelisting5-1–FixedDepositDaoImplclass-Custominitializationanddestructionlogic
Project–ch05-bankapp-customization
Sourcelocation-src/main/java/sample/spring/chapter05/bankapp/dao
packagesample.spring.chapter05.bankapp.dao;
publicclassFixedDepositDaoImplimplementsFixedDepositDao{
privatestaticLoggerlogger=Logger.getLogger(FixedDepositDaoImpl.class);
privateDatabaseConnectionconnection;
publicFixedDepositDaoImpl(){
logger.info("FixedDepositDaoImpl'sconstructorinvoked");
}
publicvoidinitializeDbConnection(){
logger.info("FixedDepositDaoImpl’sinitializeDbConnectionmethodinvoked");
connection=DatabaseConnection.getInstance();
}
publicbooleancreateFixedDeposit(FixedDepositDetailsfixedDepositDetails){
logger.info("FixedDepositDaoImpl’screateFixedDepositmethodinvoked");
//--savethefixeddepositsandthenreturntrue
returntrue;
}

publicvoidreleaseDbConnection(){
logger.info("FixedDepositDaoImpl’sreleaseDbConnectionmethodinvoked");
connection.releaseConnection();
}
}
In the above example listing, the DatabaseConnection object is used for interacting with the MyBank’s
database. FixedDepositDaoImpl class defines an initializeDbConnection method that initializes the
DatabaseConnection object, which is later used by the createFixedDeposit method for saving fixed
depositdetailsintheMyBank’sdatabase.
The following example listing shows the MyBank’s FixedDepositServiceImpl class that uses
FixedDepositDaoImplinstancetocreatenewfixeddeposits:
Examplelisting5-2–FixedDepositServiceImplclass
Project–ch05-bankapp-customization
Sourcelocation-src/main/java/sample/spring/chapter05/bankapp/service
packagesample.spring.chapter05.bankapp.service;
publicclassFixedDepositServiceImplimplementsFixedDepositService{
privatestaticLoggerlogger=Logger.getLogger(FixedDepositServiceImpl.class);
privateFixedDepositDaomyFixedDepositDao;
publicvoidsetMyFixedDepositDao(FixedDepositDaomyFixedDepositDao){
logger.info("FixedDepositServiceImpl'ssetMyFixedDepositDaomethodinvoked");
this.myFixedDepositDao=myFixedDepositDao;
}
@Override
publicvoidcreateFixedDeposit(FixedDepositDetailsfixedDepositDetails)throwsException{
//--createfixeddeposit
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 FixedDepositServiceImpl’s createFixedDeposit method is invoked, it results in invocation of
FixedDepositDaoImpl’screateFixedDepositmethod.
The following example listing shows bean definitions for FixedDepositDaoImpl and
FixedDepositServiceImplclasses:
Examplelisting5-3–applicationContext.xml–usageofinit-methodanddestroy-methodattributes
Project–ch05-bankapp-customization
Sourcelocation-src/main/resources/META-INF/spring

<beans.....>
<beanid="FixedDepositService"
class="sample.spring.chapter05.bankapp.service.FixedDepositServiceImpl">
<propertyname="myFixedDepositDao"ref="myFixedDepositDao"/>
</bean>
<beanid="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-methodattributes,respectively.
NOTEItisimportanttonotethattheinitializationanddestructionmethodsspecifiedbytheinit-method
anddestroy-methodattributesof<bean>elementmustnotacceptanyarguments,butcanbedefinedto
throwexceptions.
The following example listing shows BankApp class whose main method retrieves
FixedDepositServiceImplinstancefromtheApplicationContextandinvokesFixedDepositServiceImpl’s
createFixedDepositmethod:
Examplelisting5-4–BankAppclass
Project–ch05-bankapp-customization
Sourcelocation-src/main/java/sample/spring/chapter05/bankapp
packagesample.spring.chapter05.bankapp;
publicclassBankApp{
publicstaticvoidmain(Stringargs[])throwsException{
ApplicationContextcontext=newClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");
FixedDepositServiceFixedDepositService=context.getBean(FixedDepositService.class);
FixedDepositService.createFixedDeposit(newFixedDepositDetails(1,1000,
12,"someemail@somedomain.com"));
}
}
IfyounowexecutetheBankApp’smainmethod,you’llseethefollowingoutputontheconsole:
FixedDepositDaoImpl'sconstructorinvoked
FixedDepositDaoImpl’sinitializeDbConnectionmethodinvoked
FixedDepositServiceImpl'ssetMyFixedDepositDaomethodinvoked
FixedDepositDaoImpl’screateFixedDepositmethodinvoked
TheaboveoutputshowsthattheSpringcontainerfirstcreatesFixedDepositDaoImpl’sinstance,andthen

invokes initializeDbConnection method. After the invocation of initializeDbConnection method, the
FixedDepositDaoImplinstanceisinjectedintotheFixedDepositServiceImplinstance.Thisshowsthatthe
Springcontainerinjectsadependency(theFixedDepositDaoImplinstance)intothedependentbean(the
FixedDepositServiceImpl instance) after the initialization method of the dependency is invoked by the
Springcontainer.
YoumayhavenoticedthattheoutputfromexecutingBankApp’smainmethoddidn’tcontainthefollowing
message:FixedDepositDaoImpl’sreleaseDbConnectionmethodinvoked(referFixedDepositDaoImpl’s
releaseDbConnection method in example listing 5-1). This means that the FixedDepositDaoImpl’s
releaseDbConnection method was not called by the Spring container when BankApp’s main method
exited.Inarealworldapplicationdevelopmentscenario,thismeansthatthedatabaseconnectionheldby
FixedDepositDaoImpl instance is never released. Let’s now see how you can make Spring gracefully
destroysingleton-scopedbeaninstancesbycallingthecleanupmethodspecifiedbythe<bean>element’s
destroy-methodattribute.
MakingSpringinvokecleanupmethodspecifiedbythedestory-methodattribute
The web version of ApplicationContext implementation is represented by Spring’s
WebApplicationContextobject.WebApplicationContextimplementationhasthenecessarylogictoinvoke
thecleanupmethod(specifiedbythedestroy-methodattribute)ofsingleton-scopedbeaninstancesbefore
thewebapplicationisshutdown.
NOTETheapproachdescribedinthissectiononmakingSpringgracefullydestroysingleton-scopedbean
instancesbycallingthecleanupmethodisspecifictostandaloneapplications.
Thefollowingexa