Spring Java

helpflightInternet and Web Development

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

827 views

Reference Documentation
3.0
Copyright © 2004-2010 Rod Johnson,Juergen Hoeller,Keith Donald,Colin Sampaleanu,Rob
Harrop,Alef Arendsen,Thomas Risberg,Darren Davison,Dmitriy Kopylenko,Mark Pollack,
Thierry Templier,Erwin Vervaet,Portia Tung,Ben Hale,Adrian Colyer,John Lewis,Costin
Leau,Mark Fisher,Sam Brannen,Ramnivas Laddad,Arjen Poutsma,Chris Beams,Tareq
Abedrabbo,Andy Clement,Dave Syer,Oliver Gierke
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.
Table of Contents
I.Overview of Spring Framework..............................................................................................1
1.Introduction to Spring Framework..................................................................................2
1.1.Dependency Injection and Inversion of Control....................................................2
1.2.Modules............................................................................................................3
Core Container.................................................................................................3
Data Access/Integration....................................................................................4
Web.................................................................................................................4
AOP and Instrumentation..................................................................................5
Test.................................................................................................................5
1.3.Usage scenarios.................................................................................................5
Dependency Management and Naming Conventions...........................................9
Spring Dependencies and Depending on Spring........................................11
Maven Dependency Management............................................................12
Ivy Dependency Management.................................................................13
Logging.........................................................................................................14
Not Using Commons Logging.................................................................14
Using SLF4J..........................................................................................15
Using Log4J...........................................................................................16
II.What's New in Spring 3.0...................................................................................................18
2.New Features and Enhancements in Spring 3.0.............................................................19
2.1.Java 5..............................................................................................................19
2.2.Improved documentation..................................................................................19
2.3.New articles and tutorials..................................................................................19
2.4.New module organization and build system.......................................................20
2.5.Overview of new features.................................................................................21
Core APIs updated for Java 5..........................................................................22
Spring Expression Language...........................................................................22
The Inversion of Control (IoC) container..........................................................23
Java based bean metadata........................................................................23
Defining bean metadata within components..............................................24
General purpose type conversion systemand field formatting system.................24
The Data Tier.................................................................................................24
The Web Tier.................................................................................................25
Comprehensive REST support.................................................................25
@MVC additions...................................................................................25
Declarative model validation...........................................................................25
Early support for Java EE 6.............................................................................25
Support for embedded databases......................................................................25
III.Core Technologies............................................................................................................26
3.The IoC container.......................................................................................................27
Spring Framework
3.0 Reference Documentation ii
3.1.Introduction to the Spring IoC container and beans.............................................27
3.2.Container overview..........................................................................................27
Configuration metadata...................................................................................28
Instantiating a container..................................................................................30
Composing XML-based configuration metadata.......................................31
Using the container.........................................................................................32
3.3.Bean overview.................................................................................................32
Naming beans.................................................................................................34
Aliasing a bean outside the bean definition...............................................34
Instantiating beans..........................................................................................35
Instantiation with a constructor................................................................36
Instantiation with a static factory method.................................................36
Instantiation using an instance factory method..........................................37
3.4.Dependencies...................................................................................................38
Dependency injection......................................................................................38
Constructor-based dependency injection...................................................39
Setter-based dependency injection...........................................................40
Dependency resolution process................................................................41
Examples of dependency injection...........................................................43
Dependencies and configuration in detail.........................................................45
Straight values (primitives,Strings,and so on).........................................45
References to other beans (collaborators).................................................46
Inner beans.............................................................................................47
Collections.............................................................................................48
Null and empty string values...................................................................50
XML shortcut with the p-namespace........................................................51
Compound property names......................................................................52
Using depends-on...........................................................................................52
Lazy-initialized beans.....................................................................................53
Autowiring collaborators.................................................................................53
Limitations and disadvantages of autowiring............................................55
Excluding a bean fromautowiring...........................................................56
Checking for dependencies..............................................................................56
Method injection............................................................................................57
Lookup method injection.........................................................................58
Arbitrary method replacement.................................................................59
3.5.Bean scopes.....................................................................................................60
The singleton scope........................................................................................61
The prototype scope........................................................................................62
Singleton beans with prototype-bean dependencies...........................................63
Request,session,and global session scopes......................................................64
Initial web configuration.........................................................................64
Request scope.........................................................................................65
Session scope.........................................................................................65
Global session scope...............................................................................65
Spring Framework
3.0 Reference Documentation iii
Scoped beans as dependencies.................................................................66
Customscopes...............................................................................................68
Creating a customscope..........................................................................68
Using a customscope..............................................................................69
3.6.Customizing the nature of a bean.......................................................................70
Lifecycle callbacks.........................................................................................70
Initialization callbacks............................................................................71
Destruction callbacks..............................................................................71
Default initialization and destroy methods................................................72
Combining lifecycle mechanisms............................................................73
Startup and shutdown callbacks...............................................................74
Shutting down the Spring IoC container gracefully in non-web applications 76
ApplicationContextAware and BeanNameAware..............................................76
Other Aware interfaces...................................................................................77
3.7.Bean definition inheritance...............................................................................79
3.8.Container extension points................................................................................80
Customizing beans using the BeanPostProcessor Interface................................81
Example:Hello World,BeanPostProcessor-style......................................82
Example:The RequiredAnnotationBeanPostProcessor..............................83
Customizing configuration metadata with BeanFactoryPostProcessor interface...83
Example:the PropertyPlaceholderConfigurer...........................................84
Example:the PropertyOverrideConfigurer...............................................86
Customizing instantiation logic with the FactoryBean Interface.........................87
3.9.Annotation-based container configuration..........................................................88
@Required.....................................................................................................89
@Autowired and @Inject................................................................................89
Fine-tuning annotation-based autowiring with qualifiers...................................92
CustomAutowireConfigurer............................................................................97
@Resource.....................................................................................................98
@PostConstruct and @PreDestroy...................................................................99
3.10.Classpath scanning and managed components................................................100
@Component and further stereotype annotations............................................100
Automatically detecting classes and registering bean definitions......................101
Using filters to customize scanning................................................................102
Defining bean metadata within components....................................................103
Naming autodetected components..................................................................104
Providing a scope for autodetected components..............................................105
Providing qualifier metadata with annotations................................................106
3.11.Java-based container configuration................................................................106
Basic concepts:@Configuration and @Bean..................................................106
Instantiating the Spring container using AnnotationConfigApplicationContext.107
Simple construction..............................................................................107
Building the container programmatically using register(Class<?>...)........108
Enabling component scanning with scan(String...)..................................108
Support for web applications with AnnotationConfigWebApplicationContext
Spring Framework
3.0 Reference Documentation iv
.............................................................................................................109
Composing Java-based configurations............................................................110
Using the @Import annotation...............................................................110
Combining Java and XML configuration................................................112
Using the @Bean annotation.........................................................................115
Declaring a bean...................................................................................115
Injecting dependencies..........................................................................115
Receiving lifecycle callbacks.................................................................116
Specifying bean scope...........................................................................117
Customizing bean naming.....................................................................118
Bean aliasing........................................................................................119
Further information about how Java-based configuration works internally........119
3.12.Registering a LoadTimeWeaver....................................................................120
3.13.Additional Capabilities of the ApplicationContext..........................................120
Internationalization using MessageSource......................................................121
Standard and CustomEvents.........................................................................124
Convenient access to low-level resources.......................................................126
Convenient ApplicationContext instantiation for web applications...................127
Deploying a Spring ApplicationContext as a J2EE RAR file............................128
3.14.The BeanFactory..........................................................................................128
BeanFactory or ApplicationContext?.............................................................129
Glue code and the evil singleton....................................................................130
4.Resources.................................................................................................................132
4.1.Introduction...................................................................................................132
4.2.The Resource interface...................................................................................132
4.3.Built-in Resource implementations..................................................................133
UrlResource.................................................................................................133
ClassPathResource.......................................................................................134
FileSystemResource.....................................................................................134
ServletContextResource................................................................................134
InputStreamResource....................................................................................134
ByteArrayResource......................................................................................135
4.4.The ResourceLoader.......................................................................................135
4.5.The ResourceLoaderAware interface...............................................................136
4.6.Resources as dependencies.............................................................................137
4.7.Application contexts and Resource paths.........................................................137
Constructing application contexts..................................................................137
Constructing ClassPathXmlApplicationContext instances - shortcuts.......138
Wildcards in application context constructor resource paths............................139
Ant-style Patterns.................................................................................139
The classpath*:prefix...........................................................................140
Other notes relating to wildcards............................................................140
FileSystemResource caveats..........................................................................141
5.Validation,Data Binding,and Type Conversion..........................................................143
5.1.Introduction...................................................................................................143
Spring Framework
3.0 Reference Documentation v
5.2.Validation using Spring's Validator interface....................................................143
5.3.Resolving codes to error messages..................................................................145
5.4.Bean manipulation and the BeanWrapper........................................................145
Setting and getting basic and nested properties...............................................146
Built-in PropertyEditor implementations........................................................147
Registering additional customPropertyEditors.......................................150
5.5.Spring 3 Type Conversion..............................................................................153
Converter SPI...............................................................................................153
ConverterFactory..........................................................................................154
GenericConverter.........................................................................................155
ConditionalGenericConverter................................................................155
ConversionService API.................................................................................156
Configuring a ConversionService..................................................................156
Using a ConversionService programatically...................................................157
5.6.Spring 3 Field Formatting...............................................................................157
Formatter SPI...............................................................................................158
Annotation-driven Formatting.......................................................................159
Format Annotation API.........................................................................160
FormatterRegistry SPI..................................................................................161
Configuring Formatting in Spring MVC.........................................................161
5.7.Spring 3 Validation........................................................................................162
Overview of the JSR-303 Bean Validation API...............................................163
Configuring a Bean Validation Implementation..............................................163
Injecting a Validator.............................................................................164
Configuring CustomConstraints............................................................164
Additional Configuration Options..........................................................165
Configuring a DataBinder.............................................................................165
Spring MVC 3 Validation.............................................................................166
Triggering @Controller Input Validation...............................................166
Configuring a Validator for use by Spring MVC.....................................166
Configuring a JSR-303 Validator for use by Spring MVC.......................167
6.Spring Expression Language (SpEL)..........................................................................168
6.1.Introduction...................................................................................................168
6.2.Feature Overview...........................................................................................168
6.3.Expression Evaluation using Spring's Expression Interface...............................169
The EvaluationContext interface....................................................................172
Type Conversion..................................................................................172
6.4.Expression support for defining bean definitions..............................................172
XML based configuration.............................................................................173
Annotation-based configuration.....................................................................173
6.5.Language Reference.......................................................................................175
Literal expressions........................................................................................175
Properties,Arrays,Lists,Maps,Indexers........................................................175
Methods.......................................................................................................176
Operators.....................................................................................................176
Spring Framework
3.0 Reference Documentation vi
Relational operators..............................................................................176
Logical operators..................................................................................177
Mathematical operators.........................................................................177
Assignment..................................................................................................178
Types...........................................................................................................178
Constructors.................................................................................................179
Variables......................................................................................................179
The#this and#root variables.................................................................179
Functions.....................................................................................................180
Ternary Operator (If-Then-Else)....................................................................180
The Elvis Operator.......................................................................................181
Safe Navigation operator...............................................................................181
Collection Selection......................................................................................182
Collection Projection....................................................................................182
Expression templating...................................................................................183
6.6.Classes used in the examples...........................................................................183
7.Aspect Oriented Programming with Spring.................................................................186
7.1.Introduction...................................................................................................186
AOP concepts...............................................................................................186
Spring AOP capabilities and goals.................................................................188
AOP Proxies................................................................................................189
7.2.@AspectJ support..........................................................................................190
Enabling @AspectJ Support..........................................................................190
Declaring an aspect.......................................................................................190
Declaring a pointcut......................................................................................191
Supported Pointcut Designators.............................................................192
Combining pointcut expressions............................................................194
Sharing common pointcut definitions.....................................................194
Examples.............................................................................................195
Writing good pointcuts..........................................................................198
Declaring advice...........................................................................................199
Before advice.......................................................................................199
After returning advice...........................................................................199
After throwing advice...........................................................................200
After (finally) advice............................................................................201
Around advice......................................................................................201
Advice parameters................................................................................202
Advice ordering....................................................................................206
Introductions................................................................................................206
Aspect instantiation models...........................................................................207
Example.......................................................................................................208
7.3.Schema-based AOP support............................................................................209
Declaring an aspect.......................................................................................210
Declaring a pointcut......................................................................................210
Declaring advice...........................................................................................212
Spring Framework
3.0 Reference Documentation vii
Before advice.......................................................................................212
After returning advice...........................................................................213
After throwing advice...........................................................................213
After (finally) advice............................................................................214
Around advice......................................................................................214
Advice parameters................................................................................215
Advice ordering....................................................................................217
Introductions................................................................................................217
Aspect instantiation models...........................................................................218
Advisors......................................................................................................218
Example.......................................................................................................218
7.4.Choosing which AOP declaration style to use..................................................220
Spring AOP or full AspectJ?.........................................................................220
@AspectJ or XML for Spring AOP?..............................................................221
7.5.Mixing aspect types........................................................................................222
7.6.Proxying mechanisms.....................................................................................222
Understanding AOP proxies..........................................................................223
7.7.Programmatic creation of @AspectJ Proxies....................................................226
7.8.Using AspectJ with Spring applications...........................................................226
Using AspectJ to dependency inject domain objects with Spring......................226
Unit testing @Configurable objects.......................................................229
Working with multiple application contexts............................................229
Other Spring aspects for AspectJ...................................................................230
Configuring AspectJ aspects using Spring IoC................................................230
Load-time weaving with AspectJ in the Spring Framework.............................231
A first example.....................................................................................232
Aspects................................................................................................235
'META-INF/aop.xml'............................................................................235
Required libraries (JARS).....................................................................235
Spring configuration.............................................................................236
Environment-specific configuration.......................................................238
7.9.Further Resources..........................................................................................241
8.Spring AOP APIs......................................................................................................242
8.1.Introduction...................................................................................................242
8.2.Pointcut API in Spring....................................................................................242
Concepts......................................................................................................242
Operations on pointcuts.................................................................................243
AspectJ expression pointcuts.........................................................................243
Convenience pointcut implementations..........................................................243
Static pointcuts.....................................................................................244
Dynamic pointcuts................................................................................245
Pointcut superclasses....................................................................................245
Custompointcuts..........................................................................................246
8.3.Advice API in Spring.....................................................................................246
Advice lifecycles..........................................................................................246
Spring Framework
3.0 Reference Documentation viii
Advice types in Spring..................................................................................246
Interception around advice....................................................................246
Before advice.......................................................................................247
Throws advice......................................................................................248
After Returning advice..........................................................................249
Introduction advice...............................................................................250
8.4.Advisor API in Spring....................................................................................253
8.5.Using the ProxyFactoryBean to create AOP proxies.........................................253
Basics..........................................................................................................253
JavaBean properties......................................................................................254
JDK- and CGLIB-based proxies....................................................................255
Proxying interfaces.......................................................................................256
Proxying classes...........................................................................................258
Using'global'advisors..................................................................................258
8.6.Concise proxy definitions...............................................................................259
8.7.Creating AOP proxies programmatically with the ProxyFactory........................260
8.8.Manipulating advised objects..........................................................................260
8.9.Using the"autoproxy"facility.........................................................................262
Autoproxy bean definitions...........................................................................262
BeanNameAutoProxyCreator................................................................262
DefaultAdvisorAutoProxyCreator..........................................................263
AbstractAdvisorAutoProxyCreator........................................................264
Using metadata-driven auto-proxying............................................................264
8.10.Using TargetSources....................................................................................266
Hot swappable target sources.........................................................................267
Pooling target sources...................................................................................268
Prototype target sources................................................................................269
ThreadLocal target sources............................................................................269
8.11.Defining new Advice types...........................................................................270
8.12.Further resources..........................................................................................270
9.Testing.....................................................................................................................271
9.1.Introduction to testing.....................................................................................271
9.2.Unit testing....................................................................................................271
Mock objects................................................................................................271
JNDI....................................................................................................271
Servlet API..........................................................................................271
Portlet API...........................................................................................272
Unit testing support classes...........................................................................272
General utilities....................................................................................272
Spring MVC.........................................................................................272
9.3.Integration testing..........................................................................................272
Overview.....................................................................................................272
Goals of integration testing............................................................................273
Context management and caching..........................................................273
Dependency Injection of test fixtures.....................................................274
Spring Framework
3.0 Reference Documentation ix
Transaction management.......................................................................274
Support classes for integration testing....................................................275
JDBC testing support....................................................................................275
Annotations..................................................................................................275
Spring TestContext Framework.....................................................................281
Key abstractions...................................................................................281
Context management and caching..........................................................282
Dependency Injection of test fixtures.....................................................284
Transaction management.......................................................................287
TestContext support classes...................................................................289
PetClinic example.........................................................................................292
9.4.Further Resources..........................................................................................294
IV.Data Access....................................................................................................................295
10.Transaction Management.........................................................................................296
10.1.Introduction to Spring Framework transaction management............................296
10.2.Advantages of the Spring Framework's transaction support model...................296
Global transactions.......................................................................................297
Local transactions.........................................................................................297
Spring Framework's consistent programming model.......................................297
10.3.Understanding the Spring Framework transaction abstraction..........................298
10.4.Synchronizing resources with transactions.....................................................302
High-level synchronization approach.............................................................302
Low-level synchronization approach..............................................................302
TransactionAwareDataSourceProxy...............................................................303
10.5.Declarative transaction management..............................................................303
Understanding the Spring Framework's declarative transaction implementation 305
Example of declarative transaction implementation.........................................306
Rolling back a declarative transaction............................................................310
Configuring different transactional semantics for different beans.....................311
<tx:advice/> settings.....................................................................................313
Using @Transactional...................................................................................314
@Transactional settings........................................................................318
Multiple Transaction Managers with @Transactional..............................319
Customshortcut annotations..................................................................320
Transaction propagation................................................................................320
Required..............................................................................................321
RequiresNew........................................................................................321
Nested.................................................................................................322
Advising transactional operations..................................................................322
Using @Transactional with AspectJ...............................................................325
10.6.Programmatic transaction management..........................................................326
Using the TransactionTemplate.....................................................................326
Specifying transaction settings...............................................................327
Using the PlatformTransactionManager.........................................................328
10.7.Choosing between programmatic and declarative transaction management.......329
Spring Framework
3.0 Reference Documentation x
10.8.Application server-specific integration...........................................................329
IBMWebSphere...........................................................................................330
BEA WebLogic Server.................................................................................330
Oracle OC4J.................................................................................................330
10.9.Solutions to common problems.....................................................................330
Use of the wrong transaction manager for a specific DataSource......................330
10.10.Further Resources.......................................................................................330
11.DAO support..........................................................................................................332
11.1.Introduction.................................................................................................332
11.2.Consistent exception hierarchy......................................................................332
11.3.Annotations used for configuring DAO or Repository classes..........................333
12.Data access with JDBC............................................................................................335
12.1.Introduction to Spring Framework JDBC.......................................................335
Choosing an approach for JDBC database access............................................335
Package hierarchy.........................................................................................336
12.2.Using the JDBC core classes to control basic JDBC processing and error handling
.............................................................................................................................337
JdbcTemplate...............................................................................................337
Examples of JdbcTemplate class usage..................................................338
JdbcTemplate best practices..................................................................340
NamedParameterJdbcTemplate......................................................................341
SimpleJdbcTemplate.....................................................................................343
SQLExceptionTranslator...............................................................................345
Executing statements....................................................................................346
Running queries...........................................................................................347
Updating the database...................................................................................348
Retrieving auto-generated keys......................................................................348
12.3.Controlling database connections..................................................................349
DataSource..................................................................................................349
DataSourceUtils...........................................................................................350
SmartDataSource..........................................................................................350
AbstractDataSource......................................................................................351
SingleConnectionDataSource........................................................................351
DriverManagerDataSource............................................................................351
TransactionAwareDataSourceProxy...............................................................351
DataSourceTransactionManager....................................................................352
NativeJdbcExtractor.....................................................................................352
12.4.JDBC batch operations.................................................................................353
Batch operations with the JdbcTemplate.........................................................353
Batch operations with the SimpleJdbcTemplate..............................................354
12.5.Simplifying JDBC operations with the SimpleJdbc classes..............................355
Inserting data using SimpleJdbcInsert............................................................355
Retrieving auto-generated keys using SimpleJdbcInsert...................................356
Specifying columns for a SimpleJdbcInsert....................................................356
Using SqlParameterSource to provide parameter values..................................357
Spring Framework
3.0 Reference Documentation xi
Calling a stored procedure with SimpleJdbcCall.............................................358
Explicitly declaring parameters to use for a SimpleJdbcCall............................360
How to define SqlParameters.........................................................................361
Calling a stored function using SimpleJdbcCall..............................................361
Returning ResultSet/REF Cursor froma SimpleJdbcCall.................................362
12.6.Modeling JDBC operations as Java objects....................................................363
SqlQuery......................................................................................................364
MappingSqlQuery........................................................................................364
SqlUpdate....................................................................................................365
StoredProcedure...........................................................................................366
12.7.Common problems with parameter and data value handling............................369
Providing SQL type information for parameters..............................................369
Handling BLOB and CLOB objects...............................................................369
Passing in lists of values for IN clause...........................................................371
Handling complex types for stored procedure calls.........................................371
12.8.Embedded database support..........................................................................373
Why use an embedded database?...................................................................373
Creating an embedded database instance using Spring XML...........................373
Creating an embedded database instance programmatically.............................373
Extending the embedded database support......................................................373
Using HSQL................................................................................................374
Using H2.....................................................................................................374
Using Derby.................................................................................................374
Testing data access logic with an embedded database......................................374
12.9.Initializing a DataSource...............................................................................375
Initializing a database instance using Spring XML..........................................375
Initialization of Other Components that Depend on the Database.............376
13.Object Relational Mapping (ORM) Data Access.......................................................378
13.1.Introduction to ORMwith Spring..................................................................378
13.2.General ORMintegration considerations........................................................379
Resource and transaction management...........................................................379
Exception translation....................................................................................380
13.3.Hibernate.....................................................................................................381
SessionFactory setup in a Spring container.....................................................381
Implementing DAOs based on plain Hibernate 3 API......................................382
Declarative transaction demarcation...............................................................383
Programmatic transaction demarcation...........................................................385
Transaction management strategies................................................................386
Comparing container-managed and locally defined resources..........................388
Spurious application server warnings with Hibernate......................................389
13.4.JDO.............................................................................................................390
PersistenceManagerFactory setup..................................................................390
Implementing DAOs based on the plain JDO API...........................................391
Transaction management...............................................................................393
JdoDialect....................................................................................................394
Spring Framework
3.0 Reference Documentation xii
13.5.JPA.............................................................................................................395
Three options for JPA setup in a Spring environment......................................395
LocalEntityManagerFactoryBean...........................................................395
Obtaining an EntityManagerFactory fromJNDI......................................396
LocalContainerEntityManagerFactoryBean............................................396
Dealing with multiple persistence units..................................................399
Implementing DAOs based on plain JPA........................................................399
Transaction Management..............................................................................402
JpaDialect....................................................................................................403
13.6.iBATIS SQL Maps.......................................................................................403
Setting up the SqlMapClient..........................................................................403
Using SqlMapClientTemplate and SqlMapClientDaoSupport..........................405
Implementing DAOs based on plain iBATIS API...........................................406
14.Marshalling XML using O/X Mappers.....................................................................407
14.1.Introduction.................................................................................................407
14.2.Marshaller and Unmarshaller........................................................................407
Marshaller....................................................................................................407
Unmarshaller................................................................................................408
XmlMappingException.................................................................................409
14.3.Using Marshaller and Unmarshaller...............................................................409
14.4.XML Schema-based Configuration................................................................411
14.5.JAXB..........................................................................................................412
Jaxb2Marshaller...........................................................................................412
XML Schema-based Configuration........................................................412
14.6.Castor..........................................................................................................413
CastorMarshaller..........................................................................................413
Mapping......................................................................................................413
14.7.XMLBeans..................................................................................................414
XmlBeansMarshaller....................................................................................414
XML Schema-based Configuration........................................................414
14.8.JiBX............................................................................................................415
JibxMarshaller..............................................................................................415
XML Schema-based Configuration........................................................415
14.9.XStream......................................................................................................416
XStreamMarshaller.......................................................................................416
V.The Web..........................................................................................................................417
15.Web MVC framework.............................................................................................418
15.1.Introduction to Spring Web MVC framework.................................................418
Features of Spring Web MVC.......................................................................419
Pluggability of other MVC implementations...................................................420
15.2.The DispatcherServlet..................................................................................420
15.3.Implementing Controllers.............................................................................425
Defining a controller with @Controller..........................................................426
Mapping requests with @RequestMapping.....................................................426
URI Templates.....................................................................................428
Spring Framework
3.0 Reference Documentation xiii
Advanced @RequestMapping options....................................................429
Supported handler method arguments and return types............................430
Binding request parameters to method parameters with @RequestParam..433
Mapping the request body with the @RequestBody annotation................434
Mapping the response body with the @ResponseBody annotation...........435
Using HttpEntity<?>.............................................................................435
Providing a link to data fromthe model with @ModelAttribute...............435
Specifying attributes to store in a session with @SessionAttributes..........436
Mapping cookie values with the @CookieValue annotation....................437
Mapping request header attributes with the @RequestHeader annotation..437
Customizing WebDataBinder initialization.............................................438
15.4.Handler mappings........................................................................................439
Intercepting requests - the HandlerInterceptor interface...................................440
15.5.Resolving views...........................................................................................441
Resolving views with the ViewResolver interface...........................................442
Chaining ViewResolvers...............................................................................443
Redirecting to views.....................................................................................444
RedirectView.......................................................................................445
The redirect:prefix...............................................................................445
The forward:prefix...............................................................................446
ContentNegotiatingViewResolver..................................................................446
15.6.Using locales...............................................................................................448
AcceptHeaderLocaleResolver........................................................................449
CookieLocaleResolver..................................................................................449
SessionLocaleResolver.................................................................................449
LocaleChangeInterceptor..............................................................................450
15.7.Using themes...............................................................................................450
Overview of themes......................................................................................450
Defining themes...........................................................................................450
Theme resolvers...........................................................................................451
15.8.Spring's multipart (fileupload) support...........................................................452
Introduction.................................................................................................452
Using the MultipartResolver..........................................................................452
Handling a file upload in a form....................................................................452
15.9.Handling exceptions.....................................................................................453
HandlerExceptionResolver............................................................................453
@ExceptionHandler......................................................................................454
15.10.Convention over configuration support........................................................455
The Controller ControllerClassNameHandlerMapping....................................455
The Model ModelMap (ModelAndView).......................................................456
The View - RequestToViewNameTranslator..................................................458
15.11.ETag support..............................................................................................459
15.12.Configuring Spring MVC............................................................................460
mvc:annotation-driven..................................................................................460
mvc:interceptors...........................................................................................461
Spring Framework
3.0 Reference Documentation xiv
mvc:view-controller......................................................................................461
15.13.More Spring Web MVC Resources..............................................................461
16.View technologies...................................................................................................463
16.1.Introduction.................................................................................................463
16.2.JSP &JSTL.................................................................................................463
View resolvers.............................................................................................463
'Plain-old'JSPs versus JSTL..........................................................................464
Additional tags facilitating development........................................................464
Using Spring's formtag library......................................................................464
Configuration.......................................................................................464
The formtag........................................................................................465
The input tag........................................................................................466
The checkbox tag..................................................................................466
The checkboxes tag..............................................................................468
The radiobutton tag...............................................................................468
The radiobuttons tag.............................................................................469
The password tag..................................................................................469
The select tag.......................................................................................469
The option tag......................................................................................470
The options tag.....................................................................................470
The textarea tag....................................................................................471
The hidden tag......................................................................................471
The errors tag.......................................................................................472
HTTP Method Conversion....................................................................474
16.3.Tiles............................................................................................................474
Dependencies...............................................................................................475
How to integrate Tiles...................................................................................475
UrlBasedViewResolver.........................................................................475
ResourceBundleViewResolver..............................................................476
SimpleSpringPreparerFactory and SpringBeanPreparerFactory................476
16.4.Velocity &FreeMarker.................................................................................477
Dependencies...............................................................................................477
Context configuration...................................................................................477
Creating templates........................................................................................478
Advanced configuration................................................................................478
velocity.properties................................................................................478
FreeMarker..........................................................................................479
Bind support and formhandling.....................................................................479
The bind macros...................................................................................479
Simple binding.....................................................................................480
Forminput generation macros...............................................................481
HTML escaping and XHTML compliance.............................................485
16.5.XSLT..........................................................................................................486
My First Words............................................................................................486
Bean definitions...................................................................................486
Spring Framework
3.0 Reference Documentation xv
Standard MVC controller code..............................................................486
Convert the model data to XML............................................................487
Defining the view properties..................................................................487
Document transformation......................................................................488
Summary.....................................................................................................488
16.6.Document views (PDF/Excel).......................................................................489
Introduction.................................................................................................489
Configuration and setup................................................................................489
Document view definitions....................................................................489
Controller code.....................................................................................489
Subclassing for Excel views..................................................................490
Subclassing for PDF views....................................................................491
16.7.JasperReports...............................................................................................492
Dependencies...............................................................................................492
Configuration...............................................................................................492
Configuring the ViewResolver..............................................................492
Configuring the Views..........................................................................493
About Report Files...............................................................................493
Using JasperReportsMultiFormatView...................................................493
Populating the ModelAndView......................................................................494
Working with Sub-Reports............................................................................495
Configuring Sub-Report Files................................................................495
Configuring Sub-Report Data Sources...................................................496
Configuring Exporter Parameters...................................................................496
16.8.Feed Views..................................................................................................497
16.9.XML Marshalling View................................................................................498
16.10.JSON Mapping View..................................................................................498
17.Integrating with other web frameworks.....................................................................499
17.1.Introduction.................................................................................................499
17.2.Common configuration.................................................................................500
17.3.JavaServer Faces 1.1 and 1.2.........................................................................501
DelegatingVariableResolver (JSF 1.1/1.2)......................................................501
SpringBeanVariableResolver (JSF 1.1/1.2).....................................................502
SpringBeanFacesELResolver (JSF 1.2+)........................................................502
FacesContextUtils........................................................................................503
17.4.Apache Struts 1.x and 2.x.............................................................................503
ContextLoaderPlugin....................................................................................504
DelegatingRequestProcessor.................................................................505
DelegatingActionProxy.........................................................................505
ActionSupport Classes..................................................................................506
17.5.WebWork 2.x...............................................................................................506
17.6.Tapestry 3.x and 4.x.....................................................................................507
Injecting Spring-managed beans....................................................................508
Dependency Injecting Spring Beans into Tapestry pages.........................509
Component definition files....................................................................510
Spring Framework
3.0 Reference Documentation xvi
Adding abstract accessors......................................................................511
Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style
.............................................................................................................513
17.7.Further Resources.........................................................................................514
18.Portlet MVC Framework.........................................................................................515
18.1.Introduction.................................................................................................515
Controllers - The C in MVC..........................................................................516
Views - The V in MVC.................................................................................516
Web-scoped beans........................................................................................517
18.2.The DispatcherPortlet...................................................................................517
18.3.The ViewRendererServlet.............................................................................519
18.4.Controllers...................................................................................................520
AbstractController and PortletContentGenerator.............................................520
Other simple controllers................................................................................522
Command Controllers...................................................................................522
PortletWrappingController............................................................................523
18.5.Handler mappings........................................................................................523
PortletModeHandlerMapping........................................................................524
ParameterHandlerMapping............................................................................525
PortletModeParameterHandlerMapping.........................................................525
Adding HandlerInterceptors..........................................................................526
HandlerInterceptorAdapter............................................................................526
ParameterMappingInterceptor.......................................................................526
18.6.Views and resolving them.............................................................................527
18.7.Multipart (file upload) support......................................................................527
Using the PortletMultipartResolver................................................................528
Handling a file upload in a form....................................................................528
18.8.Handling exceptions.....................................................................................531
18.9.Annotation-based controller configuration.....................................................532
Setting up the dispatcher for annotation support..............................................532
Defining a controller with @Controller..........................................................532
Mapping requests with @RequestMapping.....................................................533
Supported handler method arguments............................................................534
Binding request parameters to method parameters with @RequestParam..........536
Providing a link to data fromthe model with @ModelAttribute.......................537
Specifying attributes to store in a Session with @SessionAttributes.................537
Customizing WebDataBinder initialization.....................................................538
Customizing data binding with @InitBinder...........................................538
Configuring a customWebBindingInitializer..........................................538
18.10.Portlet application deployment....................................................................539
VI.Integration......................................................................................................................540
19.Remoting and web services using Spring..................................................................541
19.1.Introduction.................................................................................................541
19.2.Exposing services using RMI........................................................................542
Exporting the service using the RmiServiceExporter.......................................542
Spring Framework
3.0 Reference Documentation xvii
Linking in the service at the client.................................................................543
19.3.Using Hessian or Burlap to remotely call services via HTTP...........................544
Wiring up the DispatcherServlet for Hessian and co........................................544
Exposing your beans by using the HessianServiceExporter..............................544
Linking in the service on the client................................................................545
Using Burlap................................................................................................545
Applying HTTP basic authentication to a service exposed through Hessian or
Burlap..........................................................................................................546
19.4.Exposing services using HTTP invokers........................................................546
Exposing the service object...........................................................................546
Linking in the service at the client.................................................................547
19.5.Web services................................................................................................548
Exposing servlet-based web services using JAX-RPC.....................................549
Accessing web services using JAX-RPC........................................................549
Registering JAX-RPC Bean Mappings...........................................................551
Registering your own JAX-RPC Handler.......................................................552
Exposing servlet-based web services using JAX-WS......................................552
Exporting standalone web services using JAX-WS.........................................553
Exporting web services using the JAX-WS RI's Spring support.......................554
Accessing web services using JAX-WS..........................................................554
Exposing web services using XFire................................................................555
19.6.JMS.............................................................................................................556
Server-side configuration..............................................................................557
Client-side configuration...............................................................................558
19.7.Auto-detection is not implemented for remote interfaces.................................558
19.8.Considerations when choosing a technology...................................................559
19.9.Accessing RESTful services on the Client......................................................559
RestTemplate...............................................................................................560
Dealing with request and response headers.............................................562
HTTP Message Conversion...........................................................................562
StringHttpMessageConverter.................................................................563
FormHttpMessageConverter..................................................................563
ByteArrayMessageConverter.................................................................563
MarshallingHttpMessageConverter........................................................564
MappingJacksonHttpMessageConverter.................................................564
SourceHttpMessageConverter...............................................................564
BufferedImageHttpMessageConverter...................................................564
20.Enterprise JavaBeans (EJB) integration....................................................................565
20.1.Introduction.................................................................................................565
20.2.Accessing EJBs............................................................................................565
Concepts......................................................................................................565
Accessing local SLSBs.................................................................................566
Accessing remote SLSBs..............................................................................567
Accessing EJB 2.x SLSBs versus EJB 3 SLSBs..............................................568
20.3.Using Spring's EJB implementation support classes........................................568
Spring Framework
3.0 Reference Documentation xviii
EJB 2.x base classes.....................................................................................568
EJB 3 injection interceptor............................................................................570
21.JMS (Java Message Service)....................................................................................572
21.1.Introduction.................................................................................................572
21.2.Using Spring JMS........................................................................................572
JmsTemplate................................................................................................572
Connections.................................................................................................573
Caching Messaging Resources...............................................................574
SingleConnectionFactory......................................................................574
CachingConnectionFactory...................................................................574
Destination Management...............................................................................574
Message Listener Containers.........................................................................575
SimpleMessageListenerContainer..........................................................576
DefaultMessageListenerContainer.........................................................576
Transaction management...............................................................................576
21.3.Sending a Message.......................................................................................577
Using Message Converters............................................................................578
SessionCallback and ProducerCallback..........................................................579
21.4.Receiving a message.....................................................................................579
Synchronous Reception.................................................................................579
Asynchronous Reception - Message-Driven POJOs........................................579
The SessionAwareMessageListener interface.................................................580
The MessageListenerAdapter........................................................................580
Processing messages within transactions........................................................582
21.5.Support for JCA Message Endpoints..............................................................583
21.6.JMS Namespace Support..............................................................................585
22.JMX.......................................................................................................................590
22.1.Introduction.................................................................................................590
22.2.Exporting your beans to JMX........................................................................590
Creating an MBeanServer.............................................................................591
Reusing an existing MBeanServer.................................................................592
Lazy-initialized MBeans...............................................................................593
Automatic registration of MBeans.................................................................593
Controlling the registration behavior..............................................................593
22.3.Controlling the management interface of your beans.......................................595
The MBeanInfoAssembler Interface..............................................................595
Using Source-Level Metadata (JDK 5.0 annotations)......................................595
Source-Level Metadata Types.......................................................................597
The AutodetectCapableMBeanInfoAssembler interface...................................599
Defining management interfaces using Java interfaces....................................600
Using MethodNameBasedMBeanInfoAssembler............................................601
22.4.Controlling the ObjectNames for your beans..................................................601
Reading ObjectNames fromProperties...........................................................602
Using the MetadataNamingStrategy...............................................................603
The <context:mbean-export/> element...........................................................603
Spring Framework
3.0 Reference Documentation xix
22.5.JSR-160 Connectors.....................................................................................604
Server-side Connectors.................................................................................604
Client-side Connectors..................................................................................605
JMX over Burlap/Hessian/SOAP...................................................................605
22.6.Accessing MBeans via Proxies......................................................................606
22.7.Notifications................................................................................................606
Registering Listeners for Notifications...........................................................606
Publishing Notifications................................................................................610
22.8.Further Resources.........................................................................................611
23.JCA CCI.................................................................................................................612
23.1.Introduction.................................................................................................612
23.2.Configuring CCI..........................................................................................612
Connector configuration................................................................................612
ConnectionFactory configuration in Spring....................................................613
Configuring CCI connections........................................................................614
Using a single CCI connection.......................................................................614
23.3.Using Spring's CCI access support.................................................................615
Record conversion........................................................................................615
The CciTemplate..........................................................................................616
DAO support................................................................................................617
Automatic output record generation...............................................................618
Summary.....................................................................................................618
Using a CCI Connection and Interaction directly............................................619
Example for CciTemplate usage....................................................................620
23.4.Modeling CCI access as operation objects......................................................622
MappingRecordOperation.............................................................................622
MappingCommAreaOperation.......................................................................623
Automatic output record generation...............................................................623
Summary.....................................................................................................623
Example for MappingRecordOperation usage.................................................624
Example for MappingCommAreaOperation usage..........................................626
23.5.Transactions.................................................................................................627
24.Email.....................................................................................................................629
24.1.Introduction.................................................................................................629
24.2.Usage..........................................................................................................629
Basic MailSender and SimpleMailMessage usage...........................................630
Using the JavaMailSender and the MimeMessagePreparator...........................631
24.3.Using the JavaMail MimeMessageHelper......................................................632
Sending attachments and inline resources.......................................................632
Attachments.........................................................................................632
Inline resources....................................................................................632
Creating email content using a templating library...........................................633
A Velocity-based example....................................................................634
25.Task Execution and Scheduling................................................................................636
25.1.Introduction.................................................................................................636
Spring Framework
3.0 Reference Documentation xx
25.2.The Spring TaskExecutor abstraction.............................................................636
TaskExecutor types.......................................................................................636
Using a TaskExecutor...................................................................................638
25.3.The Spring TaskScheduler abstraction...........................................................639