The Spring Framework - Reference Documentation

helpflightInternet and Web Development

Nov 10, 2013 (3 years and 11 months ago)

562 views

The Spring Framework - Reference Documentation
Version 2.5.1
Copyright © 2004-2007 Rod Johnson,Juergen Hoeller,Alef Arendsen,Colin Sampaleanu,
Rob Harrop,Thomas Risberg,Darren Davison,Dmitriy Kopylenko,Mark Pollack,Thierry
Templier,Erwin Vervaet,Portia Tung,Ben Hale,Adrian Colyer,John Lewis,Costin Leau,
Mark Fisher,SamBrannen,Ramnivas Laddad
Copies of this document may be made for your own use and for distribution to others,provided that you do not
charge any fee for such copies and further provided that each copy contains this Copyright Notice,whether
distributed in print or electronically.
Preface................................................................................................................................................xv
1.Introduction...................................................................................................................................16
1.1.Overview..............................................................................................................................16
1.2.Usagescenarios....................................................................................................................18
2.What's newinSpring2.0and2.5?.................................................................................................21
2.1.Introduction..........................................................................................................................21
2.2.TheInversionof Control (IoC) container................................................................................21
2.2.1.Newbeanscopes........................................................................................................21
2.2.2.EasierXMLconfiguration...........................................................................................21
2.2.3.ExtensibleXMLauthoring..........................................................................................22
2.2.4.Annotation-drivenconfiguration..................................................................................22
2.2.5.Autodetectingcomponentsintheclasspath..................................................................22
2.3.Aspect OrientedProgramming(AOP)....................................................................................22
2.3.1.EasierAOPXMLconfiguration..................................................................................23
2.3.2.Support for@AspectJaspects.....................................................................................23
2.3.3.Support for beannamepointcut element......................................................................23
2.3.4.Support for AspectJload-timeweaving........................................................................23
2.4.TheMiddleTier....................................................................................................................23
2.4.1.Easier configurationof declarative transactions inXML...............................................23
2.4.2.Full WebSpheretransactionmanagement support.........................................................23
2.4.3.JPA...........................................................................................................................24
2.4.4.AsynchronousJMS.....................................................................................................24
2.4.5.JDBC........................................................................................................................24
2.5.TheWebTier........................................................................................................................25
2.5.1.SensibledefaultinginSpringMVC.............................................................................25
2.5.2.Portletframework.......................................................................................................25
2.5.3.Annotation-basedcontrollers.......................................................................................25
2.5.4.Aformtaglibraryfor SpringMVC.............................................................................25
2.5.5.Tiles2support...........................................................................................................25
2.5.6.JSF1.2support..........................................................................................................26
2.5.7.JAX-WSsupport........................................................................................................26
2.6.Everythingelse.....................................................................................................................26
2.6.1.Dynamiclanguagesupport..........................................................................................26
2.6.2.Enhancedtestingsupport............................................................................................26
2.6.3.JMXsupport..............................................................................................................26
2.6.4.Deployinga Springapplicationcontext as JCAadapter.................................................27
2.6.5.Taskscheduling.........................................................................................................27
2.6.6.Java5(Tiger)support.................................................................................................27
2.7.MigratingtoSpring2.5..........................................................................................................27
2.7.1.Changes.....................................................................................................................28
2.8.Updatedsampleapplications..................................................................................................30
2.9.Improveddocumentation.......................................................................................................30
I.CoreTechnologies............................................................................................................................31
3.TheIoCcontainer..................................................................................................................32
3.1.Introduction..................................................................................................................32
3.2.Basics- containersandbeans.........................................................................................32
3.2.1.Thecontainer.....................................................................................................33
3.2.2.Instantiatingacontainer......................................................................................34
3.2.3.Thebeans..........................................................................................................35
3.2.4.Usingthecontainer.............................................................................................39
3.3.Dependencies................................................................................................................40
3.3.1.Injectingdependencies........................................................................................40
Spring Framework (2.5.1) ii
3.3.2.Dependenciesandconfigurationindetail.............................................................45
3.3.3.Usingdepends-on..............................................................................................53
3.3.4.Lazily-instantiatedbeans.....................................................................................54
3.3.5.Autowiringcollaborators....................................................................................55
3.3.6.Checkingfordependencies..................................................................................57
3.3.7.MethodInjection................................................................................................57
3.4.Beanscopes..................................................................................................................60
3.4.1.Thesingletonscope............................................................................................61
3.4.2.Theprototypescope...........................................................................................62
3.4.3.Singletonbeanswithprototype-beandependencies...............................................63
3.4.4.Theotherscopes.................................................................................................64
3.4.5.Customscopes...................................................................................................68
3.5.Customizingthenatureof abean....................................................................................70
3.5.1.Lifecyclecallbacks.............................................................................................70
3.5.2.Knowingwhoyouare.........................................................................................74
3.6.Beandefinitioninheritance............................................................................................76
3.7.Containerextensionpoints.............................................................................................77
3.7.1.CustomizingbeansusingBeanPostProcessors....................................................77
3.7.2.CustomizingconfigurationmetadatawithBeanFactoryPostProcessors...............80
3.7.3.CustomizinginstantiationlogicusingFactoryBeans............................................83
3.8.TheApplicationContext..............................................................................................83
3.8.1.BeanFactoryorApplicationContext?................................................................84
3.8.2.InternationalizationusingMessageSources..........................................................84
3.8.3.Events...............................................................................................................87
3.8.4.Convenient accesstolow-level resources.............................................................88
3.8.5.Convenient ApplicationContextinstantiationfor webapplications......................89
3.9.Gluecodeandtheevil singleton.....................................................................................90
3.10.Deploying a Spring ApplicationContext as a J2EERARfile..........................................90
3.11.Annotation-basedconfiguration....................................................................................91
3.11.1.@Autowired......................................................................................................92
3.11.2.Fine-tuningannotation-basedautowiringwithqualifiers.....................................94
3.11.3.CustomAutowireConfigurer.............................................................................97
3.11.4.@Resource........................................................................................................97
3.11.5.@PostConstructand@PreDestroy....................................................................98
3.12.Classpathscanningfor managedcomponents................................................................99
3.12.1.@Componentandfurther stereotypeannotations...................................................99
3.12.2.Auto-detectingcomponents...............................................................................100
3.12.3.Usingfilterstocustomizescanning....................................................................100
3.12.4.Namingauto-detectedcomponents....................................................................101
3.12.5.Providingascopefor auto-detectedcomponents.................................................102
3.12.6.Providingqualifier metadatawithannotations....................................................102
3.13.RegisteringaLoadTimeWeaver.....................................................................................103
4.Resources...............................................................................................................................104
4.1.Introduction..................................................................................................................104
4.2.TheResourceinterface..................................................................................................104
4.3.Built-inResourceimplementations................................................................................105
4.3.1.UrlResource......................................................................................................105
4.3.2.ClassPathResource...........................................................................................105
4.3.3.FileSystemResource..........................................................................................106
4.3.4.ServletContextResource...................................................................................106
4.3.5.InputStreamResource........................................................................................106
4.3.6.ByteArrayResource...........................................................................................106
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) iii
4.4.TheResourceLoader.....................................................................................................106
4.5.TheResourceLoaderAwareinterface..............................................................................107
4.6.Resourcesasdependencies............................................................................................108
4.7.ApplicationcontextsandResourcepaths........................................................................108
4.7.1.Constructingapplicationcontexts........................................................................108
4.7.2.Wildcards inapplicationcontext constructor resource paths..................................109
4.7.3.FileSystemResourcecaveats..............................................................................111
5.Validation,Data-binding,the BeanWrapper,andPropertyEditors..........................................113
5.1.Introduction..................................................................................................................113
5.2.ValidationusingSpring's Validatorinterface.................................................................113
5.3.Resolvingcodestoerror messages.................................................................................115
5.4.BeanmanipulationandtheBeanWrapper........................................................................115
5.4.1.Settingandgettingbasic andnestedproperties.....................................................115
5.4.2.Built-inPropertyEditorimplementations..............................................................117
6.Aspect OrientedProgrammingwithSpring...........................................................................123
6.1.Introduction..................................................................................................................123
6.1.1.AOPconcepts....................................................................................................123
6.1.2.SpringAOPcapabilitiesandgoals.......................................................................125
6.1.3.AOPProxies......................................................................................................126
6.2.@AspectJsupport.........................................................................................................126
6.2.1.Enabling@AspectJSupport................................................................................126
6.2.2.Declaringanaspect.............................................................................................127
6.2.3.Declaringapointcut...........................................................................................127
6.2.4.Declaringadvice................................................................................................133
6.2.5.Introductions......................................................................................................139
6.2.6.Aspectinstantiationmodels.................................................................................139
6.2.7.Example............................................................................................................140
6.3.Schema-basedAOPsupport...........................................................................................141
6.3.1.Declaringanaspect.............................................................................................142
6.3.2.Declaringapointcut...........................................................................................142
6.3.3.Declaringadvice................................................................................................143
6.3.4.Introductions......................................................................................................148
6.3.5.Aspectinstantiationmodels.................................................................................149
6.3.6.Advisors............................................................................................................149
6.3.7.Example............................................................................................................149
6.4.ChoosingwhichAOPdeclarationstyle touse.................................................................151
6.4.1.SpringAOPor full AspectJ?...............................................................................151
6.4.2.@AspectJ or XMLfor SpringAOP?....................................................................151
6.5.Mixingaspecttypes.......................................................................................................152
6.6.Proxyingmechanisms....................................................................................................152
6.6.1.UnderstandingAOPproxies................................................................................153
6.7.Programmaticcreationof @AspectJProxies...................................................................155
6.8.UsingAspectJwithSpringapplications..........................................................................156
6.8.1.Using AspectJ to dependency inject domain objects with Spring............................156
6.8.2.Other Springaspectsfor AspectJ.........................................................................159
6.8.3.ConfiguringAspectJ aspects usingSpringIoC.....................................................159
6.8.4.Load-time weavingwithAspectJ inthe SpringFramework...................................160
6.9.FurtherResources.........................................................................................................167
7.SpringAOPAPIs...................................................................................................................168
7.1.Introduction..................................................................................................................168
7.2.Pointcut APIinSpring...................................................................................................168
7.2.1.Concepts............................................................................................................168
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) iv
7.2.2.Operationsonpointcuts......................................................................................169
7.2.3.AspectJexpressionpointcuts...............................................................................169
7.2.4.Conveniencepointcutimplementations................................................................169
7.2.5.Pointcutsuperclasses..........................................................................................171
7.2.6.Custompointcuts................................................................................................171
7.3.AdviceAPIinSpring....................................................................................................171
7.3.1.Advicelifecycles................................................................................................171
7.3.2.AdvicetypesinSpring........................................................................................172
7.4.AdvisorAPIinSpring...................................................................................................177
7.5.Usingthe ProxyFactoryBeantocreate AOPproxies........................................................177
7.5.1.Basics................................................................................................................177
7.5.2.JavaBeanproperties............................................................................................178
7.5.3.JDK-andCGLIB-basedproxies..........................................................................179
7.5.4.Proxyinginterfaces.............................................................................................180
7.5.5.Proxyingclasses.................................................................................................181
7.5.6.Using'global'advisors........................................................................................182
7.6.Conciseproxydefinitions..............................................................................................182
7.7.CreatingAOPproxies programmaticallywiththe ProxyFactory.......................................183
7.8.Manipulatingadvisedobjects.........................................................................................184
7.9.Usingthe"autoproxy"facility........................................................................................185
7.9.1.Autoproxybeandefinitions.................................................................................185
7.9.2.Usingmetadata-drivenauto-proxying..................................................................187
7.10.UsingTargetSources...................................................................................................189
7.10.1.Hot swappabletarget sources.............................................................................189
7.10.2.Poolingtargetsources.......................................................................................190
7.10.3.Prototypetargetsources....................................................................................191
7.10.4.ThreadLocaltargetsources...............................................................................191
7.11.DefiningnewAdvicetypes..........................................................................................192
7.12.Furtherresources.........................................................................................................192
8.Testing...................................................................................................................................193
8.1.Introduction..................................................................................................................193
8.2.Unittesting...................................................................................................................193
8.2.1.Mockobjects......................................................................................................193
8.2.2.Unit testingsupport classes.................................................................................194
8.3.Integrationtesting.........................................................................................................194
8.3.1.Overview...........................................................................................................194
8.3.2.Whichsupport frameworktouse.........................................................................195
8.3.3.Commongoals...................................................................................................195
8.3.4.JDBCtestingsupport..........................................................................................197
8.3.5.Commonannotations..........................................................................................197
8.3.6.JUnit 3.8legacysupport......................................................................................199
8.3.7.SpringTestContextFramework...........................................................................203
8.3.8.PetClinicexample..............................................................................................213
8.4.FurtherResources.........................................................................................................214
II.MiddleTierDataAccess..................................................................................................................216
9.Transactionmanagement.......................................................................................................217
9.1.Introduction..................................................................................................................217
9.2.Motivations..................................................................................................................217
9.3.Keyabstractions............................................................................................................219
9.4.Resourcesynchronizationwithtransactions....................................................................221
9.4.1.High-levelapproach...........................................................................................222
9.4.2.Low-levelapproach............................................................................................222
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) v
9.4.3.TransactionAwareDataSourceProxy...................................................................222
9.5.Declarativetransactionmanagement...............................................................................223
9.5.1.Understandingthe SpringFramework's declarative transactionimplementation......224
9.5.2.Afirstexample...................................................................................................224
9.5.3.Rollingback.......................................................................................................227
9.5.4.Configuringdifferent transactional semantics for different beans...........................229
9.5.5.<tx:advice/>settings........................................................................................230
9.5.6.Using@Transactional.......................................................................................231
9.5.7.Transactionpropagation......................................................................................236
9.5.8.Advisingtransactionaloperations........................................................................237
9.5.9.Using@TransactionalwithAspectJ...................................................................240
9.6.Programmatictransactionmanagement...........................................................................240
9.6.1.UsingtheTransactionTemplate.........................................................................241
9.6.2.UsingthePlatformTransactionManager.............................................................242
9.7.Choosingbetweenprogrammatic anddeclarative transactionmanagement........................243
9.8.Applicationserver-specificintegration............................................................................243
9.8.1.BEAWebLogic..................................................................................................243
9.8.2.IBMWebSphere................................................................................................243
9.9.Solutionstocommonproblems......................................................................................243
9.9.1.Use of the wrong transaction manager for a specific DataSource...........................244
9.10.FurtherResources........................................................................................................244
10.DAOsupport........................................................................................................................245
10.1.Introduction................................................................................................................245
10.2.Consistentexceptionhierarchy.....................................................................................245
10.3.Consistent abstract classes for DAOsupport.................................................................246
11.DataaccessusingJDBC.......................................................................................................247
11.1.Introduction................................................................................................................247
11.1.1.Choosingastyle...............................................................................................247
11.1.2.Thepackagehierarchy......................................................................................248
11.2.Using the JDBCCore classes to control basic JDBCprocessing and error handling.........248
11.2.1.JdbcTemplate..................................................................................................248
11.2.2.NamedParameterJdbcTemplate..........................................................................251
11.2.3.SimpleJdbcTemplate........................................................................................253
11.2.4.DataSource......................................................................................................254
11.2.5.SQLExceptionTranslator.................................................................................255
11.2.6.Executingstatements........................................................................................256
11.2.7.RunningQueries...............................................................................................256
11.2.8.Updatingthedatabase.......................................................................................257
11.2.9.Retrievingauto-generatedkeys..........................................................................257
11.3.Controllingdatabaseconnections.................................................................................258
11.3.1.DataSourceUtils.............................................................................................258
11.3.2.SmartDataSource.............................................................................................258
11.3.3.AbstractDataSource........................................................................................258
11.3.4.SingleConnectionDataSource..........................................................................258
11.3.5.DriverManagerDataSource...............................................................................258
11.3.6.TransactionAwareDataSourceProxy.................................................................259
11.3.7.DataSourceTransactionManager......................................................................259
11.3.8.NativeJdbcExtractor.........................................................................................259
11.4.JDBCbatchoperations................................................................................................260
11.4.1.BatchoperationswiththeJdbcTemplate.............................................................260
11.4.2.BatchoperationswiththeSimpleJdbcTemplate..................................................261
11.5.SimplifyingJDBCoperations withthe SimpleJdbc classes.............................................262
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) vi
11.5.1.InsertingdatausingSimpleJdbcInsert................................................................262
11.5.2.Retrievingauto-generatedkeysusingSimpleJdbcInsert.......................................262
11.5.3.Specifyingthe columns touse for a SimpleJdbcInsert.........................................263
11.5.4.UsingSqlParameterSourcetoprovideparameter values......................................263
11.5.5.CallingastoredprocedureusingSimpleJdbcCall................................................264
11.5.6.Declaringparameters touse for a SimpleJdbcCall...............................................266
11.5.7.HowtodefineSqlParameters.............................................................................267
11.5.8.CallingastoredfunctionusingSimpleJdbcCall..................................................267
11.5.9.ReturningResultSet/REFCursor fromaSimpleJdbcCall.....................................268
11.6.ModelingJDBCoperations as Javaobjects...................................................................269
11.6.1.SqlQuery..........................................................................................................269
11.6.2.MappingSqlQuery.............................................................................................269
11.6.3.SqlUpdate........................................................................................................270
11.6.4.StoredProcedure.............................................................................................270
11.6.5.SqlFunction....................................................................................................273
11.7.Commonissues withparameter anddata value handling................................................273
11.7.1.ProvidingSQLtypeinformationfor parameters..................................................273
11.7.2.HandlingBLOBandCLOBobjects...................................................................274
11.7.3.Passinginlists of values for INclause...............................................................275
11.7.4.Handlingcomplextypes for storedprocedure calls.............................................276
12.Object Relational Mapping(ORM) dataaccess....................................................................277
12.1.Introduction................................................................................................................277
12.2.Hibernate....................................................................................................................278
12.2.1.Resourcemanagement......................................................................................278
12.2.2.SessionFactorysetupinaSpringcontainer.......................................................279
12.2.3.TheHibernateTemplate...................................................................................279
12.2.4.ImplementingSpring-basedDAOswithout callbacks..........................................281
12.2.5.ImplementingDAOs basedonplainHibernate 3API..........................................281
12.2.6.Programmatictransactiondemarcation...............................................................282
12.2.7.Declarativetransactiondemarcation...................................................................283
12.2.8.Transactionmanagementstrategies....................................................................284
12.2.9.Container resourcesversuslocal resources.........................................................286
12.2.10.Spurious applicationserver warnings whenusingHibernate..............................287
12.3.JDO............................................................................................................................288
12.3.1.PersistenceManagerFactorysetup...................................................................288
12.3.2.JdoTemplateandJdoDaoSupport......................................................................289
12.3.3.ImplementingDAOs basedonthe plainJDOAPI...............................................289
12.3.4.Transactionmanagement...................................................................................291
12.3.5.JdoDialect......................................................................................................292
12.4.OracleTopLink...........................................................................................................293
12.4.1.SessionFactoryabstraction..............................................................................293
12.4.2.TopLinkTemplateandTopLinkDaoSupport........................................................294
12.4.3.ImplementingDAOs basedonplainTopLinkAPI..............................................295
12.4.4.Transactionmanagement...................................................................................296
12.5.iBATISSQLMaps......................................................................................................297
12.5.1.SettinguptheSqlMapClient.............................................................................297
12.5.2.UsingSqlMapClientTemplateandSqlMapClientDaoSupport.............................298
12.5.3.ImplementingDAOs basedonplainiBATISAPI...............................................299
12.6.JPA............................................................................................................................300
12.6.1.JPAsetupinaSpringenvironment....................................................................300
12.6.2.JpaTemplateandJpaDaoSupport......................................................................304
12.6.3.ImplementingDAOs basedonplainJPA............................................................305
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) vii
12.6.4.ExceptionTranslation.......................................................................................307
12.7.TransactionManagement.............................................................................................308
12.8.JpaDialect.................................................................................................................309
III.TheWeb........................................................................................................................................310
13.WebMVCframework..........................................................................................................311
13.1.Introduction................................................................................................................311
13.1.1.Pluggabilityof other MVCimplementations.......................................................312
13.1.2.Featuresof SpringWebMVC...........................................................................312
13.2.TheDispatcherServlet..............................................................................................313
13.3.Controllers..................................................................................................................317
13.3.1.AbstractControllerandWebContentGenerator...............................................318
13.3.2.Othersimplecontrollers....................................................................................319
13.3.3.TheMultiActionController............................................................................319
13.3.4.Commandcontrollers........................................................................................322
13.4.Handlermappings.......................................................................................................323
13.4.1.BeanNameUrlHandlerMapping............................................................................323
13.4.2.SimpleUrlHandlerMapping...............................................................................324
13.4.3.Interceptingrequests - the HandlerInterceptorinterface...................................325
13.5.Viewsandresolvingthem............................................................................................326
13.5.1.Resolvingviews - the ViewResolverinterface....................................................327
13.5.2.ChainingViewResolvers...................................................................................328
13.5.3.Redirectingtoviews.........................................................................................329
13.6.Usinglocales..............................................................................................................330
13.6.1.AcceptHeaderLocaleResolver..........................................................................330
13.6.2.CookieLocaleResolver....................................................................................330
13.6.3.SessionLocaleResolver...................................................................................331
13.6.4.LocaleChangeInterceptor...............................................................................331
13.7.Usingthemes..............................................................................................................331
13.7.1.Introduction.....................................................................................................331
13.7.2.Definingthemes...............................................................................................332
13.7.3.Themeresolvers...............................................................................................332
13.8.Spring'smultipart (fileupload)support..........................................................................333
13.8.1.Introduction.....................................................................................................333
13.8.2.UsingtheMultipartResolver...........................................................................333
13.8.3.Handlinga file uploadina form........................................................................334
13.9.UsingSpring'sformtaglibrary.....................................................................................336
13.9.1.Configuration...................................................................................................337
13.9.2.Theformtag.....................................................................................................337
13.9.3.Theinputtag...................................................................................................338
13.9.4.Thecheckboxtag.............................................................................................338
13.9.5.Thecheckboxestag..........................................................................................340
13.9.6.Theradiobuttontag........................................................................................340
13.9.7.Theradiobuttonstag......................................................................................340
13.9.8.Thepasswordtag.............................................................................................341
13.9.9.Theselecttag.................................................................................................341
13.9.10.Theoptiontag...............................................................................................341
13.9.11.Theoptionstag.............................................................................................342
13.9.12.Thetextareatag............................................................................................342
13.9.13.Thehiddentag...............................................................................................343
13.9.14.Theerrorstag...............................................................................................343
13.10.Handlingexceptions..................................................................................................345
13.11.Conventionoverconfiguration...................................................................................345
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) viii
13.11.1.TheController- ControllerClassNameHandlerMapping...................................345
13.11.2.TheModel - ModelMap(ModelAndView)............................................................346
13.11.3.TheView- RequestToViewNameTranslator.....................................................348
13.12.Annotation-basedcontrollerconfiguration...................................................................349
13.12.1.Settingupthe dispatcher for annotationsupport................................................349
13.12.2.Definingacontroller with@Controller...........................................................349
13.12.3.Mappingrequestswith@RequestMapping.........................................................350
13.12.4.Bindingrequest parameters tomethodparameters with @RequestParam..............352
13.12.5.Providing a link to data fromthe model with @ModelAttribute.........................353
13.12.6.Specifying attributes to store in a Session with @SessionAttributes.................353
13.12.7.CustomizingWebDataBinderinitialization........................................................354
13.13.FurtherResources......................................................................................................354
14.Integratingviewtechnologies...............................................................................................356
14.1.Introduction................................................................................................................356
14.2.JSP&JSTL................................................................................................................356
14.2.1.Viewresolvers.................................................................................................356
14.2.2.'Plain-old'JSPsversusJSTL..............................................................................356
14.2.3.Additional tagsfacilitatingdevelopment............................................................357
14.3.Tiles...........................................................................................................................357
14.3.1.Dependencies...................................................................................................357
14.3.2.HowtointegrateTiles.......................................................................................357
14.4.Velocity&FreeMarker................................................................................................359
14.4.1.Dependencies...................................................................................................359
14.4.2.Contextconfiguration.......................................................................................359
14.4.3.Creatingtemplates............................................................................................360
14.4.4.Advancedconfiguration....................................................................................360
14.4.5.Bindsupport andformhandling.........................................................................361
14.5.XSLT.........................................................................................................................366
14.5.1.MyFirstWords................................................................................................366
14.5.2.Summary.........................................................................................................369
14.6.Documentviews(PDF/Excel)......................................................................................369
14.6.1.Introduction.....................................................................................................369
14.6.2.Configurationandsetup....................................................................................369
14.7.JasperReports..............................................................................................................371
14.7.1.Dependencies...................................................................................................372
14.7.2.Configuration...................................................................................................372
14.7.3.PopulatingtheModelAndView............................................................................374
14.7.4.WorkingwithSub-Reports................................................................................375
14.7.5.ConfiguringExporterParameters.......................................................................376
15.Integratingwithotherwebframeworks...............................................................................377
15.1.Introduction................................................................................................................377
15.2.Commonconfiguration................................................................................................377
15.3.JavaServerFaces.........................................................................................................379
15.3.1.DelegatingVariableResolver..............................................................................379
15.3.2.FacesContextUtils............................................................................................379
15.4.Struts..........................................................................................................................380
15.4.1.ContextLoaderPlugin........................................................................................380
15.4.2.ActionSupportClasses......................................................................................382
15.5.Tapestry......................................................................................................................382
15.5.1.InjectingSpring-managedbeans........................................................................383
15.6.WebWork...................................................................................................................389
15.7.FurtherResources........................................................................................................389
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) ix
16.PortletMVCFramework.....................................................................................................390
16.1.Introduction................................................................................................................390
16.1.1.Controllers - TheCinMVC..............................................................................391
16.1.2.Views - TheVinMVC.....................................................................................391
16.1.3.Web-scopedbeans............................................................................................391
16.2.TheDispatcherPortlet..............................................................................................391
16.3.TheViewRendererServlet..........................................................................................393
16.4.Controllers..................................................................................................................394
16.4.1.AbstractControllerandPortletContentGenerator........................................395
16.4.2.Othersimplecontrollers....................................................................................396
16.4.3.CommandControllers.......................................................................................396
16.4.4.PortletWrappingController............................................................................397
16.5.Handlermappings.......................................................................................................397
16.5.1.PortletModeHandlerMapping............................................................................398
16.5.2.ParameterHandlerMapping...............................................................................398
16.5.3.PortletModeParameterHandlerMapping............................................................399
16.5.4.AddingHandlerInterceptors...........................................................................399
16.5.5.HandlerInterceptorAdapter............................................................................400
16.5.6.ParameterMappingInterceptor........................................................................400
16.6.Viewsandresolvingthem............................................................................................400
16.7.Multipart (fileupload)support.....................................................................................400
16.7.1.UsingthePortletMultipartResolver..............................................................401
16.7.2.Handlinga file uploadina form........................................................................401
16.8.Handlingexceptions....................................................................................................404
16.9.Portletapplicationdeployment.....................................................................................404
IV.Integration.....................................................................................................................................406
17.Remotingandwebservices usingSpring..............................................................................407
17.1.Introduction................................................................................................................407
17.2.ExposingservicesusingRMI.......................................................................................408
17.2.1.Exportingtheserviceusingthe RmiServiceExporter.........................................408
17.2.2.Linkinginthe service at the client.....................................................................409
17.3.Using Hessian or Burlap to remotely call services via HTTP..........................................409
17.3.1.Wiringupthe DispatcherServlet for Hessianandco........................................409
17.3.2.Exposingyour beans byusingthe HessianServiceExporter..............................410
17.3.3.Linkinginthe service onthe client....................................................................410
17.3.4.UsingBurlap....................................................................................................411
17.3.5.Applying HTTP basic authentication to a service exposed through Hessian or
Burlap.........................................................................................................................411
17.4.ExposingservicesusingHTTPinvokers.......................................................................411
17.4.1.Exposingtheserviceobject...............................................................................412
17.4.2.Linkinginthe service at the client.....................................................................412
17.5.Webservices...............................................................................................................413
17.5.1.Exposingservlet-basedwebservices usingJAX-RPC.........................................413
17.5.2.AccessingwebservicesusingJAX-RPC............................................................414
17.5.3.RegisteringJAX-RPCBeanMappings...............................................................415
17.5.4.Registeringyour ownJAX-RPCHandler...........................................................416
17.5.5.Exposingservlet-basedwebservices usingJAX-WS..........................................416
17.5.6.Exportingstandalonewebservices usingJAX-WS.............................................417
17.5.7.Exporting web services using the JAX-WSRI's Spring support...........................418
17.5.8.AccessingwebservicesusingJAX-WS..............................................................418
17.5.9.ExposingwebservicesusingXFire....................................................................419
17.6.JMS............................................................................................................................420
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) x
17.6.1.Server-sideconfiguration..................................................................................420
17.6.2.Client-sideconfiguration...................................................................................421
17.7.Auto-detectionis not implementedfor remote interfaces................................................422
17.8.Considerationswhenchoosingatechnology..................................................................422
18.EnterpriseJavaBeans(EJB) integration..............................................................................423
18.1.Introduction................................................................................................................423
18.2.AccessingEJBs...........................................................................................................423
18.2.1.Concepts..........................................................................................................423
18.2.2.AccessinglocalSLSBs.....................................................................................423
18.2.3.AccessingremoteSLSBs..................................................................................425
18.2.4.AccessingEJB2.xSLSBs versus EJB3SLSBs..................................................425
18.3.UsingSpring's EJBimplementationsupport classes.......................................................426
18.3.1.EJB2.xbaseclasses.........................................................................................426
18.3.2.EJB3injectioninterceptor................................................................................427
19.JMS(JavaMessageService).................................................................................................429
19.1.Introduction................................................................................................................429
19.2.UsingSpringJMS.......................................................................................................430
19.2.1.JmsTemplate....................................................................................................430
19.2.2.Connections.....................................................................................................430
19.2.3.DestinationManagement...................................................................................431
19.2.4.MessageListenerContainers.............................................................................431
19.2.5.Transactionmanagement...................................................................................432
19.3.SendingaMessage.......................................................................................................433
19.3.1.UsingMessageConverters................................................................................434
19.3.2.SessionCallbackandProducerCallback..........................................................434
19.4.Receivingamessage....................................................................................................435
19.4.1.SynchronousReception.....................................................................................435
19.4.2.AsynchronousReception- Message-DrivenPOJOs............................................435
19.4.3.TheSessionAwareMessageListenerinterface....................................................436
19.4.4.TheMessageListenerAdapter..........................................................................436
19.4.5.Processingmessageswithintransactions............................................................438
19.5.Support for JCAMessageEndpoints.............................................................................438
19.6.JMSNamespaceSupport.............................................................................................439
20.JMX.....................................................................................................................................444
20.1.Introduction................................................................................................................444
20.2.Exportingyour beanstoJMX.......................................................................................444
20.2.1.CreatinganMBeanServer..................................................................................445
20.2.2.ReusinganexistingMBeanServer......................................................................446
20.2.3.Lazy-initializedMBeans...................................................................................446
20.2.4.AutomaticregistrationofMBeans.....................................................................447
20.2.5.Controllingtheregistrationbehavior..................................................................447
20.3.Controllingthe management interface of your beans......................................................448
20.3.1.TheMBeanInfoAssemblerInterface...................................................................448
20.3.2.Usingsource-Levelmetadata.............................................................................448
20.3.3.UsingJDK5.0Annotations...............................................................................450
20.3.4.Source-LevelMetadataTypes...........................................................................452
20.3.5.TheAutodetectCapableMBeanInfoAssemblerinterface......................................453
20.3.6.DefiningManagement interfaces usingJavainterfaces........................................454
20.3.7.UsingMethodNameBasedMBeanInfoAssembler....................................................455
20.4.Controllingthe ObjectNames for your beans..................................................................455
20.4.1.ReadingObjectNamesfromProperties.............................................................455
20.4.2.UsingtheMetadataNamingStrategy..................................................................456
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) xi
20.4.3.The<context:mbean-export/>element............................................................457
20.5.JSR-160Connectors....................................................................................................457
20.5.1.Server-sideConnectors.....................................................................................457
20.5.2.Client-sideConnectors......................................................................................458
20.5.3.JMXoverBurlap/Hessian/SOAP.......................................................................458
20.6.AccessingMBeansviaProxies.....................................................................................459
20.7.Notifications...............................................................................................................459
20.7.1.RegisteringListenersforNotifications...............................................................459
20.7.2.PublishingNotifications....................................................................................462
20.8.FurtherResources........................................................................................................463
21.JCACCI..............................................................................................................................464
21.1.Introduction................................................................................................................464
21.2.ConfiguringCCI.........................................................................................................464
21.2.1.Connectorconfiguration....................................................................................464
21.2.2.ConnectionFactoryconfigurationinSpring.......................................................465
21.2.3.ConfiguringCCIconnections............................................................................465
21.2.4.UsingasingleCCI connection...........................................................................466
21.3.UsingSpring'sCCI accesssupport................................................................................466
21.3.1.Recordconversion............................................................................................467
21.3.2.TheCciTemplate..............................................................................................467
21.3.3.DAOsupport....................................................................................................469
21.3.4.Automaticoutput recordgeneration...................................................................469
21.3.5.Summary.........................................................................................................469
21.3.6.Usinga CCI ConnectionandInteractiondirectly............................................470
21.3.7.Examplefor CciTemplateusage........................................................................471
21.4.ModelingCCI access as operationobjects.....................................................................473
21.4.1.MappingRecordOperation.................................................................................473
21.4.2.MappingCommAreaOperation.............................................................................473
21.4.3.Automaticoutput recordgeneration...................................................................474
21.4.4.Summary.........................................................................................................474
21.4.5.Examplefor MappingRecordOperationusage....................................................474
21.4.6.Examplefor MappingCommAreaOperationusage.................................................476
21.5.Transactions................................................................................................................477
22.Email....................................................................................................................................479
22.1.Introduction................................................................................................................479
22.2.Usage.........................................................................................................................479
22.2.1.BasicMailSenderandSimpleMailMessageusage...............................................479
22.2.2.UsingtheJavaMailSenderandtheMimeMessagePreparator..............................480
22.3.UsingtheJavaMail MimeMessageHelper.......................................................................481
22.3.1.Sendingattachmentsandinlineresources...........................................................482
22.3.2.Creatingemail content usinga templatinglibrary...............................................482
23.SchedulingandThreadPooling............................................................................................485
23.1.Introduction................................................................................................................485
23.2.UsingtheOpenSymphonyQuartzScheduler.................................................................485
23.2.1.UsingtheJobDetailBean...................................................................................485
23.2.2.UsingtheMethodInvokingJobDetailFactoryBean.............................................486
23.2.3.Wiringupjobs usingtriggers andthe SchedulerFactoryBean.............................486
23.3.UsingJDKTimersupport............................................................................................487
23.3.1.Creatingcustomtimers.....................................................................................487
23.3.2.UsingtheMethodInvokingTimerTaskFactoryBean.............................................488
23.3.3.Wrapping up:setting up the tasks using the TimerFactoryBean...........................488
23.4.TheSpringTaskExecutorabstraction...........................................................................488
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) xii
23.4.1.TaskExecutortypes..........................................................................................489
23.4.2.UsingaTaskExecutor......................................................................................490
24.Dynamiclanguagesupport...................................................................................................492
24.1.Introduction................................................................................................................492
24.2.Afirstexample............................................................................................................492
24.3.Definingbeans that are backedbydynamic languages...................................................494
24.3.1.Commonconcepts............................................................................................494
24.3.2.JRubybeans.....................................................................................................498
24.3.3.Groovybeans...................................................................................................500
24.3.4.BeanShellbeans...............................................................................................502
24.4.Scenarios....................................................................................................................503
24.4.1.ScriptedSpringMVCControllers......................................................................503
24.4.2.ScriptedValidators...........................................................................................504
24.5.Bitsandbobs..............................................................................................................505
24.5.1.AOP- advisingscriptedbeans...........................................................................505
24.5.2.Scoping............................................................................................................505
24.6.FurtherResources........................................................................................................506
25.Annotations andSourceLevel MetadataSupport................................................................507
25.1.Introduction................................................................................................................507
25.2.Spring'smetadatasupport............................................................................................508
25.3.Annotations................................................................................................................509
25.3.1.@Required......................................................................................................509
25.3.2.Other@AnnotationsinSpring...........................................................................510
25.4.IntegrationwithJakartaCommonsAttributes................................................................510
25.5.MetadataandSpringAOPautoproxying.......................................................................512
25.5.1.Fundamentals...................................................................................................512
25.5.2.Declarativetransactionmanagement..................................................................513
25.5.3.Pooling............................................................................................................513
25.5.4.Custommetadata..............................................................................................514
25.6.Usingattributes tominimize MVCwebtier configuration..............................................514
V.Sampleapplications........................................................................................................................517
26.Showcaseapplications..........................................................................................................518
26.1.Introduction................................................................................................................518
26.2.SpringMVCControllers implementedina dynamic language........................................518
26.2.1.Buildanddeployment.......................................................................................518
26.3.ImplementingDAOs usingSimpleJdbcTemplateand@Repository................................519
26.3.1.Thedomain......................................................................................................519
26.3.2.Thedataaccessobjects.....................................................................................519
26.3.3.Build...............................................................................................................519
A.XMLSchema-basedconfiguration...................................................................................................520
A.1.Introduction.........................................................................................................................520
A.2.XMLSchema-basedconfiguration........................................................................................520
A.2.1.Referencingtheschemas............................................................................................520
A.2.2.Theutilschema.......................................................................................................521
A.2.3.Thejeeschema.........................................................................................................527
A.2.4.Thelangschema.......................................................................................................530
A.2.5.Thejmsschema.........................................................................................................530
A.2.6.Thetx(transaction)schema.......................................................................................531
A.2.7.Theaopschema.........................................................................................................531
A.2.8.Thecontextschema..................................................................................................532
A.2.9.Thetoolschema.......................................................................................................533
A.2.10.Thebeansschema...................................................................................................533
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) xiii
A.3.SettingupyourIDE..............................................................................................................534
A.3.1.SettingupEclipse......................................................................................................534
A.3.2.SettingupIntelliJIDEA.............................................................................................537
A.3.3.Integrationissues.......................................................................................................540
B.ExtensibleXMLauthoring...............................................................................................................541
B.1.Introduction.........................................................................................................................541
B.2.Authoringtheschema...........................................................................................................541
B.3.CodingaNamespaceHandler.................................................................................................542
B.4.CodingaBeanDefinitionParser..........................................................................................543
B.5.Registeringthehandler andtheschema..................................................................................544
B.5.1.'META-INF/spring.handlers'...................................................................................544
B.5.2.'META-INF/spring.schemas'.....................................................................................544
B.6.Using a customextension in your Spring XMLconfiguration..................................................544
B.7.Meatierexamples.................................................................................................................545
B.7.1.Nestingcustomtags withincustomtags......................................................................545
B.7.2.Customattributeson'normal'elements........................................................................548
B.8.FurtherResources.................................................................................................................549
C.spring-beans-2.0.dtd...................................................................................................................551
D.spring.tld........................................................................................................................................560
D.1.Introduction.........................................................................................................................560
D.2.Thebindtag........................................................................................................................560
D.3.TheescapeBodytag..............................................................................................................560
D.4.ThehasBindErrorstag........................................................................................................561
D.5.ThehtmlEscapetag..............................................................................................................561
D.6.Themessagetag...................................................................................................................561
D.7.ThenestedPathtag..............................................................................................................562
D.8.Thethemetag.......................................................................................................................562
D.9.Thetransformtag...............................................................................................................563
E.spring-form.tld................................................................................................................................564
E.1.Introduction..........................................................................................................................564
E.2.Thecheckboxtag..................................................................................................................564
E.3.Thecheckboxestag..............................................................................................................566
E.4.Theerrorstag.....................................................................................................................567
E.5.Theformtag.........................................................................................................................569
E.6.Thehiddentag.....................................................................................................................570
E.7.Theinputtag.......................................................................................................................570
E.8.Thelabeltag.......................................................................................................................572
E.9.Theoptiontag.....................................................................................................................573
E.10.Theoptionstag..................................................................................................................574
E.11.Thepasswordtag................................................................................................................575
E.12.Theradiobuttontag...........................................................................................................577
E.13.Theradiobuttonstag.........................................................................................................579
E.14.Theselecttag...................................................................................................................580
E.15.Thetextareatag................................................................................................................582
The Spring Framework - Reference Documentation
Spring Framework (2.5.1) xiv
Preface
Developing software applications is hard enough even with good tools and technologies.Implementing
applications using platforms which promise everything but turn out to be heavy-weight,hard to control and not
very efficient during the development cycle makes it even harder.Spring provides a light-weight solution for
building enterprise-ready applications,while still supporting the possibility of using declarative transaction
management,remote access to your logic using RMI or web services,and various options for persisting your
data to a database.Spring provides a full-featured
MVC
framework,and transparent ways of integrating
AOP
into your software.
Spring could potentially be a one-stop-shop for all your enterprise applications;however,Spring is modular,
allowing you to use just those parts of it that you need,without having to bring in the rest.You can use the IoC
container,with Struts on top,but you could also choose to use just the
Hibernate
integration
code or the
JDBC
abstraction
layer.Spring has been (and continues to be) designed to be non-intrusive,meaning dependencies on
the framework itself are generally none (or absolutely minimal,depending on the area of use).
This document provides a reference guide to Spring's features.Since this document is still to be considered
very much work-in-progress,if you have any requests or comments,please post themon the user mailing list or
on the support forums at
http://forum.springframework.org/.
Before we go on,a few words of gratitude are due to Christian Bauer (of the
Hibernate team),who prepared
and adapted the DocBook-XSL software in order to be able to create Hibernate's reference guide,thus also
allowing us to create this one.Also thanks to Russell Healy for doing an extensive and valuable review of some
of the material.
Spring Framework (2.5.1) xv
Chapter 1.Introduction
Background
In early 2004,Martin Fowler asked the readers of his site:when talking about Inversion of Control: the
question is,what aspect of control are [they] inverting?.Fowler then suggested renaming the principle
(or at least giving it a more self-explanatory name),and started to use the term Dependency Injection.His
article then continued to explain the ideas underpinning the Inversion of Control (IoC) and Dependency
Injection (DI) principle.
If you need a decent insight into IoC and DI,please do refer to said article:
http://martinfowler.com/articles/injection.html.
Java applications (a loose term which runs the gamut from constrained applets to full-fledged n-tier server-side
enterprise applications) typically are composed of a number of objects that collaborate with one another to form
the application proper.The objects in an application can thus be said to have dependencies between themselves.
The Java language and platform provides a wealth of functionality for architecting and building applications,
ranging all the way from the very basic building blocks of primitive types and classes (and the means to define
new classes),to rich full-featured application servers and web frameworks.One area that is decidedly
conspicuous by its absence is any means of taking the basic building blocks and composing them into a
coherent whole;this area has typically been left to the purvey of the architects and developers tasked with
building an application (or applications).Now to be fair,there are a number of design patterns devoted to the
business of composing the various classes and object instances that makeup an all-singing,all-dancing
application.Design patterns such as Factory,Abstract Factory,Builder,Decorator,and Service Locator (to
name but a few) have widespread recognition and acceptance within the software development industry
(presumably that is why these patterns have been formalized as patterns in the first place).This is all very well,
but these patterns are just that:best practices given a name,typically together with a description of what the
pattern does,where the pattern is typically best applied,the problems that the application of the pattern
addresses,and so forth.Notice that the last paragraph used the phrase ...a description of what the pattern
does...;pattern books and wikis are typically listings of such formalized best practice that you can certainly
take away,mull over,and then implement yourself in your application.
The IoC component of the Spring Framework addresses the enterprise concern of taking the classes,objects,
and services that are to compose an application,by providing a formalized means of composing these various
disparate components into a fully working application ready for use.The Spring Framework takes best
practices that have been proven over the years in numerous applications and formalized as design patterns,and
actually codifies these patterns as first class objects that you as an architect and developer can take away and
integrate into your own application(s).This is a Very Good Thing Indeed as attested to by the numerous
organizations and institutions that have used the Spring Framework to engineer robust,maintainable
applications.
1.1.Overview
The Spring Framework contains a lot of features,which are well-organized in six modules shown in the
diagrambelow.This chapter discusses each of the modules in turn.
Spring Framework (2.5.1) 16
Overview of the Spring Framework
Introduction
Spring Framework (2.5.1) 17
The
Core package is the most fundamental part of the framework and provides the IoC and Dependency
Injection features.The basic concept here is the BeanFactory,which provides a sophisticated implementation
of the factory pattern which removes the need for programmatic singletons and allows you to decouple the
configuration and specification of dependencies fromyour actual programlogic.
The
Context package build on the solid base provided by the
Core package:it provides a way to access objects
in a framework-style manner in a fashion somewhat reminiscent of a JNDI-registry.The context package
inherits its features from the beans package and adds support for internationalization (I18N) (using for example
resource bundles),event-propagation,resource-loading,and the transparent creation of contexts by,for
example,a servlet container.
The
DAO package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and
parsing of database-vendor specific error codes.Also,the
JDBC package provides a way to do programmatic as
well as declarative transaction management,not only for classes implementing special interfaces,but for all
your POJOs (plain old Java objects).
The
ORMpackage provides integration layers for popular object-relational mapping APIs,including
JPA,
JDO,
Hibernate,and
iBatis.Using the ORMpackage you can use all those O/R-mappers in combination with all the
other features Spring offers,such as the simple declarative transaction management feature mentioned
previously.
Spring's
AOP package provides an AOP Alliance-compliant aspect-oriented programming implementation
allowing you to define,for example,method-interceptors and pointcuts to cleanly decouple code implementing
functionality that should logically speaking be separated.Using source-level metadata functionality you can
also incorporate all kinds of behavioral information into your code,in a manner similar to that of.NET
attributes.
Spring's Web package provides basic web-oriented integration features,such as multipart file-upload
functionality,the initialization of the IoC container using servlet listeners and a web-oriented application
context.When using Spring together with WebWork or Struts,this is the package to integrate with.
Spring's
MVC package provides a Model-View-Controller (MVC) implementation for web-applications.
Spring's MVC framework is not just any old implementation;it provides a clean separation between domain
model code and web forms,and allows you to use all the other features of the Spring Framework.
1.2.Usage scenarios
With the building blocks described above you can use Spring in all sorts of scenarios,from applets up to
fully-fledged enterprise applications using Spring's transaction management functionality and web framework
integration.
Introduction
Spring Framework (2.5.1) 18
Typical full-fledged Spring web application
By using Spring's
declarative
transaction
management
features the web application is fully transactional,just as
it would be when using container managed transactions as provided by Enterprise JavaBeans.All your custom
business logic can be implemented using simple POJOs,managed by Spring's IoC container.Additional
services include support for sending email,and validation that is independent of the web layer enabling you to
choose where to execute validation rules.Spring's ORM support is integrated with JPA,Hibernate,JDO and
iBatis;for example,when using Hibernate,you can continue to use your existing mapping files and standard
Hibernate SessionFactory configuration.Form controllers seamlessly integrate the web-layer with the domain
model,removing the need for ActionForms or other classes that transform HTTP parameters to values for your
domain model.
Spring middle-tier using a third-party web framework
Sometimes the current circumstances do not allow you to completely switch to a different framework.The
Introduction
Spring Framework (2.5.1) 19
Spring Framework does not force you to use everything within it;it is not an all-or-nothing solution.Existing
front-ends built using WebWork,Struts,Tapestry,or other UI frameworks can be integrated perfectly well with
a Spring-based middle-tier,allowing you to use the transaction features that Spring offers.The only thing you
need to do is wire up your business logic using an ApplicationContext and integrate your web layer using a
WebApplicationContext.
Remoting usage scenario
When you need to access existing code via web services,you can use Spring's Hessian-,Burlap-,Rmi- or