Spring Framework Reference Documentation

helpflightInternet και Εφαρμογές Web

10 Νοε 2013 (πριν από 4 χρόνια και 3 μέρες)

809 εμφανίσεις

Spring Framework Reference Documentation
3.2.5.RELEASE
Rod Johnson , Juergen Hoeller , Keith Donald , Colin Sampaleanu , Rob Harrop , Thomas
Risberg , Alef Arendsen , 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 , Rossen Stoyanchev , Phillip Webb
Copyright © 2004-2013
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.
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
ii
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 .............................................................................................................. 2
Core Container .................................................................................................. 3
Data Access/Integration ...................................................................................... 3
Web .................................................................................................................. 4
AOP and Instrumentation ................................................................................... 4
Test ................................................................................................................... 4
1.3. Usage scenarios ................................................................................................. 5
Dependency Management and Naming Conventions ............................................ 8
Spring Dependencies and Depending on Spring ......................................... 10
Maven Dependency Management ............................................................. 10
Ivy Dependency Management ................................................................... 11
Logging ............................................................................................................ 12
Not Using Commons Logging ................................................................... 13
Using SLF4J ............................................................................................ 13
Using Log4J ............................................................................................. 14
II. What's New in Spring 3 ........................................................................................................ 16
2. New Features and Enhancements in Spring Framework 3.0 ............................................ 17
2.1. Java 5 .............................................................................................................. 17
2.2. Improved documentation .................................................................................... 17
2.3. New articles and tutorials ................................................................................... 17
2.4. New module organization and build system ......................................................... 18
2.5. Overview of new features .................................................................................. 19
Core APIs updated for Java 5 ........................................................................... 19
Spring Expression Language ............................................................................ 19
The Inversion of Control (IoC) container ............................................................ 20
Java based bean metadata ....................................................................... 20
Defining bean metadata within components ............................................... 21
General purpose type conversion system and field formatting system .................. 22
The Data Tier .................................................................................................. 22
The Web Tier ................................................................................................... 22
Comprehensive REST support .................................................................. 22
@MVC additions ...................................................................................... 22
Declarative model validation ............................................................................. 22
Early support for Java EE 6 .............................................................................. 22
Support for embedded databases ...................................................................... 23
3. New Features and Enhancements in Spring Framework 3.1 ............................................ 24
3.1. Cache Abstraction ............................................................................................. 24
3.2. Bean Definition Profiles ...................................................................................... 24
3.3. Environment Abstraction .................................................................................... 24
3.4. PropertySource Abstraction ................................................................................ 24
3.5. Code equivalents for Spring's XML namespaces ................................................. 24
3.6. Support for Hibernate 4.x ................................................................................... 25
3.7. TestContext framework support for @Configuration classes and bean definition
profiles ..................................................................................................................... 25
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
iii
3.8. c: namespace for more concise constructor injection ............................................ 25
3.9. Support for injection against non-standard JavaBeans setters ............................... 25
3.10. Support for Servlet 3 code-based configuration of Servlet Container .................... 26
3.11. Support for Servlet 3 MultipartResolver ............................................................. 26
3.12. JPA EntityManagerFactory bootstrapping without persistence.xml ....................... 26
3.13. New HandlerMethod-based Support Classes For Annotated Controller
Processing ............................................................................................................... 26
3.14. "consumes" and "produces" conditions in @RequestMapping ............................ 27
3.15. Flash Attributes and RedirectAttributes .................................................... 27
3.16. URI Template Variable Enhancements .............................................................. 27
3.17. @Valid On @RequestBody Controller Method Arguments ................................ 28
3.18. @RequestPart Annotation On Controller Method Arguments ............................. 28
3.19. UriComponentsBuilder and UriComponents .............................................. 28
4. New Features and Enhancements in Spring Framework 3.2 ............................................ 29
4.1. Support for Servlet 3 based asynchronous request processing .............................. 29
4.2. Spring MVC Test framework .............................................................................. 29
4.3. Content negotiation improvements ...................................................................... 29
4.4. @ControllerAdvice annotation ...................................................................... 29
4.5. Matrix variables ................................................................................................. 30
4.6. Abstract base class for code-based Servlet 3+ container initialization .................... 30
4.7. ResponseEntityExceptionHandler class ..................................................... 30
4.8. Support for generic types in the RestTemplate and in @RequestBody
arguments ................................................................................................................ 30
4.9. Jackson JSON 2 and related improvements ........................................................ 30
4.10. Tiles 3 ............................................................................................................. 31
4.11. @RequestBody improvements ......................................................................... 31
4.12. HTTP PATCH method ...................................................................................... 31
4.13. Excluded patterns in mapped interceptors ......................................................... 31
4.14. Using meta-annotations for injection points and for bean definition methods ......... 31
4.15. Initial support for JCache 0.5 ............................................................................ 31
4.16. Support for @DateTimeFormat without Joda Time ........................................... 31
4.17. Global date & time formatting ........................................................................... 31
4.18. New Testing Features ...................................................................................... 32
4.19. Concurrency refinements across the framework ................................................. 32
4.20. New Gradle-based build and move to GitHub .................................................... 32
4.21. Refined Java SE 7 / OpenJDK 7 support .......................................................... 32
III. Core Technologies .............................................................................................................. 33
5. The IoC container ........................................................................................................ 34
5.1. Introduction to the Spring IoC container and beans .............................................. 34
5.2. Container overview ............................................................................................ 34
Configuration metadata ..................................................................................... 35
Instantiating a container .................................................................................... 36
Composing XML-based configuration metadata .......................................... 37
Using the container .......................................................................................... 38
5.3. Bean overview ................................................................................................... 39
Naming beans .................................................................................................. 40
Aliasing a bean outside the bean definition ................................................ 40
Instantiating beans ........................................................................................... 41
Instantiation with a constructor .................................................................. 41
Instantiation with a static factory method .................................................... 42
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
iv
Instantiation using an instance factory method ........................................... 42
5.4. Dependencies ................................................................................................... 44
Dependency injection ....................................................................................... 44
Constructor-based dependency injection .................................................... 44
Setter-based dependency injection ............................................................ 46
Dependency resolution process ................................................................. 47
Examples of dependency injection ............................................................. 48
Dependencies and configuration in detail ........................................................... 50
Straight values (primitives, Strings, and so on) ....................................... 50
References to other beans (collaborators) .................................................. 52
Inner beans .............................................................................................. 53
Collections ............................................................................................... 53
Null and empty string values ..................................................................... 56
XML shortcut with the p-namespace .......................................................... 56
XML shortcut with the c-namespace .......................................................... 58
Compound property names ....................................................................... 58
Using depends-on .......................................................................................... 59
Lazy-initialized beans ....................................................................................... 59
Autowiring collaborators .................................................................................... 60
Limitations and disadvantages of autowiring ............................................... 61
Excluding a bean from autowiring .............................................................. 61
Method injection ............................................................................................... 62
Lookup method injection ........................................................................... 63
Arbitrary method replacement ................................................................... 64
5.5. Bean scopes ..................................................................................................... 65
The singleton scope ......................................................................................... 66
The prototype scope ......................................................................................... 67
Singleton beans with prototype-bean dependencies ............................................ 68
Request, session, and global session scopes .................................................... 68
Initial web configuration ............................................................................ 69
Request scope ......................................................................................... 69
Session scope .......................................................................................... 70
Global session scope ............................................................................... 70
Scoped beans as dependencies ................................................................ 70
Custom scopes ................................................................................................ 72
Creating a custom scope .......................................................................... 72
Using a custom scope .............................................................................. 73
5.6. Customizing the nature of a bean ....................................................................... 74
Lifecycle callbacks ............................................................................................ 74
Initialization callbacks ............................................................................... 75
Destruction callbacks ................................................................................ 75
Default initialization and destroy methods .................................................. 76
Combining lifecycle mechanisms ............................................................... 77
Startup and shutdown callbacks ................................................................ 78
Shutting down the Spring IoC container gracefully in non-web applications
................................................................................................................. 80
ApplicationContextAware and BeanNameAware ........................................ 80
Other Aware interfaces .................................................................................... 81
5.7. Bean definition inheritance ................................................................................. 82
5.8. Container Extension Points ................................................................................ 84
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
v
Customizing beans using a BeanPostProcessor ............................................ 84
Example: Hello World, BeanPostProcessor-style .................................... 85
Example: The RequiredAnnotationBeanPostProcessor ..................... 87
Customizing configuration metadata with a BeanFactoryPostProcessor ........ 87
Example: the PropertyPlaceholderConfigurer ................................. 88
Example: the PropertyOverrideConfigurer ....................................... 89
Customizing instantiation logic with a FactoryBean .......................................... 90
5.9. Annotation-based container configuration ............................................................ 91
@Required ...................................................................................................... 92
@Autowired .................................................................................................... 92
Fine-tuning annotation-based autowiring with qualifiers ....................................... 95
CustomAutowireConfigurer ...................................................................... 100
@Resource .................................................................................................... 101
@PostConstruct and @PreDestroy ............................................................ 102
5.10. Classpath scanning and managed components ................................................ 102
@Component and further stereotype annotations .............................................. 103
Automatically detecting classes and registering bean definitions ........................ 103
Using filters to customize scanning .................................................................. 104
Defining bean metadata within components ..................................................... 105
Naming autodetected components ................................................................... 106
Providing a scope for autodetected components ............................................... 107
Providing qualifier metadata with annotations ................................................... 108
5.11. Using JSR 330 Standard Annotations ............................................................. 108
Dependency Injection with @Inject and @Named ............................................ 109
@Named: a standard equivalent to the @Component annotation ......................... 109
Limitations of the standard approach ............................................................... 110
5.12. Java-based container configuration ................................................................. 111
Basic concepts: @Bean and @Configuration ................................................ 111
Instantiating the Spring container using
AnnotationConfigApplicationContext .................................................. 112
Simple construction ................................................................................ 112
Building the container programmatically using register(Class<?>...)
............................................................................................................... 113
Enabling component scanning with scan(String...) ........................... 113
Support for web applications with
AnnotationConfigWebApplicationContext .................................... 113
Using the @Bean annotation ............................................................................ 114
Declaring a bean .................................................................................... 115
Receiving lifecycle callbacks ................................................................... 115
Specifying bean scope ............................................................................ 116
Customizing bean naming ....................................................................... 117
Bean aliasing ......................................................................................... 117
Using the @Configuration annotation .......................................................... 118
Injecting inter-bean dependencies ............................................................ 118
Lookup method injection ......................................................................... 118
Further information about how Java-based configuration works internally .... 119
Composing Java-based configurations ............................................................. 120
Using the @Import annotation ................................................................ 120
Combining Java and XML configuration ................................................... 123
5.13. Registering a LoadTimeWeaver .................................................................... 126
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
vi
5.14. Additional Capabilities of the ApplicationContext ...................................... 126
Internationalization using MessageSource ...................................................... 126
Standard and Custom Events .......................................................................... 129
Convenient access to low-level resources ........................................................ 132
Convenient ApplicationContext instantiation for web applications ............... 133
Deploying a Spring ApplicationContext as a J2EE RAR file ............................... 133
5.15. The BeanFactory ........................................................................................... 134
BeanFactory or ApplicationContext? ..................................................... 134
Glue code and the evil singleton ..................................................................... 136
6. Resources .................................................................................................................. 137
6.1. Introduction ..................................................................................................... 137
6.2. The Resource interface .................................................................................. 137
6.3. Built-in Resource implementations ................................................................... 138
UrlResource ................................................................................................ 138
ClassPathResource .................................................................................... 138
FileSystemResource .................................................................................. 139
ServletContextResource .......................................................................... 139
InputStreamResource ................................................................................ 139
ByteArrayResource .................................................................................... 139
6.4. The ResourceLoader .................................................................................... 139
6.5. The ResourceLoaderAware interface ............................................................. 140
6.6. Resources as dependencies ........................................................................... 141
6.7. Application contexts and Resource paths ........................................................ 141
Constructing application contexts ..................................................................... 141
Constructing ClassPathXmlApplicationContext instances -
shortcuts ................................................................................................ 142
Wildcards in application context constructor resource paths ............................... 142
Ant-style Patterns ................................................................................... 143
The classpath*: prefix ........................................................................ 143
Other notes relating to wildcards ............................................................. 144
FileSystemResource caveats ..................................................................... 144
7. Validation, Data Binding, and Type Conversion ............................................................ 146
7.1. Introduction ..................................................................................................... 146
7.2. Validation using Spring's Validator interface .................................................. 146
7.3. Resolving codes to error messages .................................................................. 148
7.4. Bean manipulation and the BeanWrapper ........................................................ 149
Setting and getting basic and nested properties ............................................... 149
Built-in PropertyEditor implementations ..................................................... 151
Registering additional custom PropertyEditors ................................... 153
7.5. Spring 3 Type Conversion ................................................................................ 156
Converter SPI ................................................................................................ 156
ConverterFactory ............................................................................................ 157
GenericConverter ........................................................................................... 157
ConditionalGenericConverter ................................................................... 158
ConversionService API ................................................................................... 158
Configuring a ConversionService ..................................................................... 159
Using a ConversionService programmatically ................................................... 160
7.6. Spring 3 Field Formatting ................................................................................. 160
Formatter SPI ................................................................................................. 160
Annotation-driven Formatting ........................................................................... 162
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
vii
Format Annotation API ............................................................................ 163
FormatterRegistry SPI ..................................................................................... 164
FormatterRegistrar SPI ................................................................................... 164
Configuring Formatting in Spring MVC ............................................................. 164
7.7. Configuring a global date & time format ............................................................ 166
7.8. Spring 3 Validation .......................................................................................... 168
Overview of the JSR-303 Bean Validation API ................................................. 168
Configuring a Bean Validation Implementation .................................................. 169
Injecting a Validator ................................................................................ 169
Configuring Custom Constraints .............................................................. 169
Additional Configuration Options .............................................................. 170
Configuring a DataBinder ................................................................................ 170
Spring MVC 3 Validation ................................................................................. 171
Triggering @Controller Input Validation .................................................... 171
Configuring a Validator for use by Spring MVC ......................................... 171
Configuring a JSR-303 Validator for use by Spring MVC ........................... 172
8. Spring Expression Language (SpEL) ........................................................................... 173
8.1. Introduction ..................................................................................................... 173
8.2. Feature Overview ............................................................................................ 173
8.3. Expression Evaluation using Spring's Expression Interface ................................. 174
The EvaluationContext interface ...................................................................... 176
Type Conversion .................................................................................... 176
8.4. Expression support for defining bean definitions ................................................ 177
XML based configuration ................................................................................ 177
Annotation-based configuration ........................................................................ 178
8.5. Language Reference ........................................................................................ 179
Literal expressions .......................................................................................... 179
Properties, Arrays, Lists, Maps, Indexers ......................................................... 180
Inline lists ....................................................................................................... 181
Array construction ........................................................................................... 181
Methods ......................................................................................................... 181
Operators ....................................................................................................... 182
Relational operators ................................................................................ 182
Logical operators .................................................................................... 182
Mathematical operators ........................................................................... 183
Assignment .................................................................................................... 184
Types ............................................................................................................. 184
Constructors ................................................................................................... 185
Variables ........................................................................................................ 185
The #this and #root variables .................................................................. 185
Functions ....................................................................................................... 186
Bean references ............................................................................................. 186
Ternary Operator (If-Then-Else) ....................................................................... 187
The Elvis Operator ......................................................................................... 187
Safe Navigation operator ................................................................................ 188
Collection Selection ........................................................................................ 188
Collection Projection ....................................................................................... 189
Expression templating ..................................................................................... 189
8.6. Classes used in the examples .......................................................................... 190
9. Aspect Oriented Programming with Spring ................................................................... 194
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
viii
9.1. Introduction ..................................................................................................... 194
AOP concepts ................................................................................................ 194
Spring AOP capabilities and goals ................................................................... 196
AOP Proxies .................................................................................................. 197
9.2. @AspectJ support ........................................................................................... 197
Enabling @AspectJ Support ............................................................................ 197
Enabling @AspectJ Support with Java configuration ................................. 197
Enabling @AspectJ Support with XML configuration ................................. 198
Declaring an aspect ........................................................................................ 198
Declaring a pointcut ........................................................................................ 199
Supported Pointcut Designators .............................................................. 199
Combining pointcut expressions .............................................................. 201
Sharing common pointcut definitions ........................................................ 201
Examples ............................................................................................... 203
Writing good pointcuts ............................................................................ 205
Declaring advice ............................................................................................. 206
Before advice ......................................................................................... 206
After returning advice .............................................................................. 206
After throwing advice .............................................................................. 207
After (finally) advice ................................................................................ 208
Around advice ........................................................................................ 208
Advice parameters .................................................................................. 209
Advice ordering ...................................................................................... 213
Introductions ................................................................................................... 213
Aspect instantiation models ............................................................................. 214
Example ......................................................................................................... 214
9.3. Schema-based AOP support ............................................................................ 216
Declaring an aspect ........................................................................................ 216
Declaring a pointcut ........................................................................................ 217
Declaring advice ............................................................................................. 218
Before advice ......................................................................................... 218
After returning advice .............................................................................. 219
After throwing advice .............................................................................. 220
After (finally) advice ................................................................................ 220
Around advice ........................................................................................ 221
Advice parameters .................................................................................. 221
Advice ordering ...................................................................................... 223
Introductions ................................................................................................... 224
Aspect instantiation models ............................................................................. 224
Advisors ......................................................................................................... 224
Example ......................................................................................................... 225
9.4. Choosing which AOP declaration style to use .................................................... 227
Spring AOP or full AspectJ? ........................................................................... 227
@AspectJ or XML for Spring AOP? ................................................................. 228
9.5. Mixing aspect types ......................................................................................... 229
9.6. Proxying mechanisms ...................................................................................... 229
Understanding AOP proxies ............................................................................ 230
9.7. Programmatic creation of @AspectJ Proxies ..................................................... 232
9.8. Using AspectJ with Spring applications ............................................................. 233
Using AspectJ to dependency inject domain objects with Spring ........................ 233
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
ix
Unit testing @Configurable objects ...................................................... 236
Working with multiple application contexts ................................................ 236
Other Spring aspects for AspectJ .................................................................... 236
Configuring AspectJ aspects using Spring IoC ................................................. 237
Load-time weaving with AspectJ in the Spring Framework ................................. 238
A first example ....................................................................................... 238
Aspects .................................................................................................. 241
'META-INF/aop.xml' ............................................................................. 242
Required libraries (JARS) ........................................................................ 242
Spring configuration ................................................................................ 242
Environment-specific configuration ........................................................... 245
9.9. Further Resources ........................................................................................... 247
10. Spring AOP APIs ...................................................................................................... 248
10.1. Introduction .................................................................................................... 248
10.2. Pointcut API in Spring .................................................................................... 248
Concepts ........................................................................................................ 248
Operations on pointcuts .................................................................................. 249
AspectJ expression pointcuts .......................................................................... 249
Convenience pointcut implementations ............................................................ 249
Static pointcuts ....................................................................................... 249
Dynamic pointcuts .................................................................................. 250
Pointcut superclasses ..................................................................................... 251
Custom pointcuts ............................................................................................ 251
10.3. Advice API in Spring ...................................................................................... 251
Advice lifecycles ............................................................................................. 251
Advice types in Spring .................................................................................... 252
Interception around advice ...................................................................... 252
Before advice ......................................................................................... 252
Throws advice ........................................................................................ 253
After Returning advice ............................................................................ 254
Introduction advice .................................................................................. 255
10.4. Advisor API in Spring ..................................................................................... 257
10.5. Using the ProxyFactoryBean to create AOP proxies ......................................... 258
Basics ............................................................................................................ 258
JavaBean properties ....................................................................................... 258
JDK- and CGLIB-based proxies ...................................................................... 259
Proxying interfaces ......................................................................................... 260
Proxying classes ............................................................................................ 262
Using 'global' advisors .................................................................................... 263
10.6. Concise proxy definitions ................................................................................ 263
10.7. Creating AOP proxies programmatically with the ProxyFactory .......................... 264
10.8. Manipulating advised objects .......................................................................... 265
10.9. Using the "auto-proxy" facility ......................................................................... 266
Autoproxy bean definitions .............................................................................. 267
BeanNameAutoProxyCreator ................................................................... 267
DefaultAdvisorAutoProxyCreator .............................................................. 267
AbstractAdvisorAutoProxyCreator ............................................................ 268
Using metadata-driven auto-proxying ............................................................... 268
10.10. Using TargetSources .................................................................................... 270
Hot swappable target sources ......................................................................... 271
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
x
Pooling target sources .................................................................................... 271
Prototype target sources ................................................................................. 273
ThreadLocal target sources ......................................................................... 273
10.11. Defining new Advice types .......................................................................... 273
10.12. Further resources ......................................................................................... 274
11. Testing ..................................................................................................................... 275
11.1. Introduction to Spring Testing ......................................................................... 275
11.2. Unit Testing ................................................................................................... 275
Mock Objects ................................................................................................. 275
Environment ........................................................................................... 275
JNDI ...................................................................................................... 275
Servlet API ............................................................................................. 275
Portlet API ............................................................................................. 276
Unit Testing support Classes .......................................................................... 276
General utilities ...................................................................................... 276
Spring MVC ........................................................................................... 276
11.3. Integration Testing ......................................................................................... 276
Overview ........................................................................................................ 276
Goals of Integration Testing ............................................................................ 277
Context management and caching ........................................................... 277
Dependency Injection of test fixtures ....................................................... 278
Transaction management ........................................................................ 278
Support classes for integration testing ..................................................... 279
JDBC Testing Support .................................................................................... 279
Annotations .................................................................................................... 279
Spring Testing Annotations ..................................................................... 279
Standard Annotation Support .................................................................. 285
Spring JUnit Testing Annotations ............................................................. 285
Spring TestContext Framework ....................................................................... 287
Key abstractions ..................................................................................... 287
Context management .............................................................................. 289
Dependency injection of test fixtures ........................................................ 302
Testing request and session scoped beans .............................................. 305
Transaction management ........................................................................ 307
TestContext Framework support classes .................................................. 309
Spring MVC Test Framework .......................................................................... 311
Server-Side Tests ................................................................................... 311
Client-Side REST Tests .......................................................................... 317
PetClinic Example .......................................................................................... 317
11.4. Further Resources ......................................................................................... 319
IV. Data Access ..................................................................................................................... 320
12. Transaction Management .......................................................................................... 321
12.1. Introduction to Spring Framework transaction management .............................. 321
12.2. Advantages of the Spring Framework's transaction support model ..................... 321
Global transactions ......................................................................................... 321
Local transactions ........................................................................................... 322
Spring Framework's consistent programming model .......................................... 322
12.3. Understanding the Spring Framework transaction abstraction ............................ 323
12.4. Synchronizing resources with transactions ....................................................... 326
High-level synchronization approach ................................................................ 327
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
xi
Low-level synchronization approach ................................................................. 327
TransactionAwareDataSourceProxy ........................................................ 327
12.5. Declarative transaction management ............................................................... 328
Understanding the Spring Framework's declarative transaction implementation ... 329
Example of declarative transaction implementation ........................................... 330
Rolling back a declarative transaction .............................................................. 333
Configuring different transactional semantics for different beans ........................ 334
<tx:advice/> settings ................................................................................. 336
Using @Transactional ................................................................................ 337
@Transactional settings ..................................................................... 342
Multiple Transaction Managers with @Transactional ............................. 343
Custom shortcut annotations ................................................................... 344
Transaction propagation .................................................................................. 344
Required ................................................................................................ 344
RequiresNew .......................................................................................... 345
Nested ................................................................................................... 345
Advising transactional operations ..................................................................... 345
Using @Transactional with AspectJ ............................................................ 349
12.6. Programmatic transaction management ........................................................... 349
Using the TransactionTemplate ................................................................. 350
Specifying transaction settings ................................................................ 351
Using the PlatformTransactionManager ................................................... 352
12.7. Choosing between programmatic and declarative transaction management ........ 352
12.8. Application server-specific integration .............................................................. 352
IBM WebSphere ............................................................................................. 353
BEA WebLogic Server .................................................................................... 353
Oracle OC4J .................................................................................................. 353
12.9. Solutions to common problems ....................................................................... 353
Use of the wrong transaction manager for a specific DataSource ..................... 353
12.10. Further Resources ....................................................................................... 354
13. DAO support ............................................................................................................ 355
13.1. Introduction .................................................................................................... 355
13.2. Consistent exception hierarchy ....................................................................... 355
13.3. Annotations used for configuring DAO or Repository classes ............................ 356
14. Data access with JDBC ............................................................................................ 358
14.1. Introduction to Spring Framework JDBC .......................................................... 358
Choosing an approach for JDBC database access ........................................... 358
Package hierarchy .......................................................................................... 359
14.2. Using the JDBC core classes to control basic JDBC processing and error
handling ................................................................................................................. 360
JdbcTemplate .............................................................................................. 360
Examples of JdbcTemplate class usage ................................................... 360
JdbcTemplate best practices ................................................................ 362
NamedParameterJdbcTemplate .................................................................. 364
SQLExceptionTranslator .......................................................................... 366
Executing statements ...................................................................................... 368
Running queries ............................................................................................. 368
Updating the database .................................................................................... 369
Retrieving auto-generated keys ....................................................................... 370
14.3. Controlling database connections .................................................................... 370
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
xii
DataSource .................................................................................................. 370
DataSourceUtils ........................................................................................ 372
SmartDataSource ........................................................................................ 372
AbstractDataSource .................................................................................. 372
SingleConnectionDataSource .................................................................. 372
DriverManagerDataSource ........................................................................ 372
TransactionAwareDataSourceProxy ........................................................ 373
DataSourceTransactionManager .............................................................. 373
NativeJdbcExtractor ........................................................................................ 373
14.4. JDBC batch operations .................................................................................. 374
Basic batch operations with the JdbcTemplate ................................................. 374
Batch operations with a List of objects ............................................................. 375
Batch operations with multiple batches ............................................................ 376
14.5. Simplifying JDBC operations with the SimpleJdbc classes ................................ 377
Inserting data using SimpleJdbcInsert .............................................................. 377
Retrieving auto-generated keys using SimpleJdbcInsert .................................... 378
Specifying columns for a SimpleJdbcInsert ...................................................... 379
Using SqlParameterSource to provide parameter values ................................... 379
Calling a stored procedure with SimpleJdbcCall ............................................... 380
Explicitly declaring parameters to use for a SimpleJdbcCall ............................... 382
How to define SqlParameters .......................................................................... 383
Calling a stored function using SimpleJdbcCall ................................................. 384
Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................... 384
14.6. Modeling JDBC operations as Java objects ..................................................... 385
SqlQuery ...................................................................................................... 386
MappingSqlQuery ........................................................................................ 386
SqlUpdate .................................................................................................... 387
StoredProcedure ........................................................................................ 387
14.7. Common problems with parameter and data value handling .............................. 391
Providing SQL type information for parameters ................................................. 392
Handling BLOB and CLOB objects .................................................................. 392
Passing in lists of values for IN clause ............................................................ 393
Handling complex types for stored procedure calls ........................................... 394
14.8. Embedded database support .......................................................................... 395
Why use an embedded database? .................................................................. 395
Creating an embedded database instance using Spring XML ............................ 395
Creating an embedded database instance programmatically .............................. 396
Extending the embedded database support ...................................................... 396
Using HSQL ................................................................................................... 396
Using H2 ........................................................................................................ 396
Using Derby ................................................................................................... 396
Testing data access logic with an embedded database ..................................... 396
14.9. Initializing a DataSource ................................................................................. 397
Initializing a database instance using Spring XML ............................................. 397
Initialization of Other Components that Depend on the Database ............... 398
15. Object Relational Mapping (ORM) Data Access .......................................................... 400
15.1. Introduction to ORM with Spring ..................................................................... 400
15.2. General ORM integration considerations ......................................................... 401
Resource and transaction management ........................................................... 401
Exception translation ....................................................................................... 401
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
xiii
15.3. Hibernate ....................................................................................................... 402
SessionFactory setup in a Spring container ................................................. 402
Implementing DAOs based on plain Hibernate 3 API ........................................ 403
Declarative transaction demarcation ................................................................ 405
Programmatic transaction demarcation ............................................................ 407
Transaction management strategies ................................................................ 408
Comparing container-managed and locally defined resources ............................ 410
Spurious application server warnings with Hibernate ......................................... 411
15.4. JDO .............................................................................................................. 412
PersistenceManagerFactory setup ........................................................... 412
Implementing DAOs based on the plain JDO API ............................................. 413
Transaction management ................................................................................ 415
JdoDialect .................................................................................................. 416
15.5. JPA ............................................................................................................... 417
Three options for JPA setup in a Spring environment ........................................ 417
LocalEntityManagerFactoryBean .................................................... 417
Obtaining an EntityManagerFactory from JNDI .................................. 418
LocalContainerEntityManagerFactoryBean .................................. 418
Dealing with multiple persistence units ..................................................... 420
Implementing DAOs based on plain JPA .......................................................... 421
Transaction Management ................................................................................ 423
JpaDialect .................................................................................................. 424
15.6. iBATIS SQL Maps ......................................................................................... 425
Setting up the SqlMapClient ........................................................................ 425
Using SqlMapClientTemplate and SqlMapClientDaoSupport ................. 426
Implementing DAOs based on plain iBATIS API ............................................... 427
16. Marshalling XML using O/X Mappers ......................................................................... 429
16.1. Introduction .................................................................................................... 429
16.2. Marshaller and Unmarshaller .......................................................................... 429
Marshaller ...................................................................................................... 429
Unmarshaller .................................................................................................. 430
XmlMappingException ..................................................................................... 431
16.3. Using Marshaller and Unmarshaller ................................................................. 431
16.4. XML Schema-based Configuration .................................................................. 433
16.5. JAXB ............................................................................................................. 433
Jaxb2Marshaller ............................................................................................. 434
XML Schema-based Configuration ........................................................... 434
16.6. Castor ........................................................................................................... 435
CastorMarshaller ............................................................................................ 435
Mapping ......................................................................................................... 435
XML Schema-based Configuration ........................................................... 435
16.7. XMLBeans ..................................................................................................... 436
XmlBeansMarshaller ....................................................................................... 436
XML Schema-based Configuration ........................................................... 436
16.8. JiBX .............................................................................................................. 437
JibxMarshaller ................................................................................................ 437
XML Schema-based Configuration ........................................................... 437
16.9. XStream ........................................................................................................ 438
XStreamMarshaller ......................................................................................... 438
V. The Web ........................................................................................................................... 439
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
xiv
17. Web MVC framework ................................................................................................ 440
17.1. Introduction to Spring Web MVC framework .................................................... 440
Features of Spring Web MVC ......................................................................... 441
Pluggability of other MVC implementations ...................................................... 442
17.2. The DispatcherServlet ............................................................................ 442
Special Bean Types In the WebApplicationContext .................................... 445
Default DispatcherServlet Configuration ........................................................... 446
DispatcherServlet Processing Sequence .......................................................... 446
17.3. Implementing Controllers ................................................................................ 447
Defining a controller with @Controller .......................................................... 448
Mapping Requests With @RequestMapping ................................................... 449
New Support Classes for @RequestMapping methods in Spring MVC 3.1
............................................................................................................... 451
URI Template Patterns ........................................................................... 452
URI Template Patterns with Regular Expressions ..................................... 453
Path Patterns ......................................................................................... 454
Patterns with Placeholders ...................................................................... 454
Matrix Variables ...................................................................................... 454
Consumable Media Types ....................................................................... 455
Producible Media Types .......................................................................... 456
Request Parameters and Header Values ................................................. 456
Defining @RequestMapping handler methods ................................................. 457
Supported method argument types .......................................................... 457
Supported method return types ............................................................... 459
Binding request parameters to method parameters with @RequestParam
............................................................................................................... 460
Mapping the request body with the @RequestBody annotation .................. 460
Mapping the response body with the @ResponseBody annotation ............. 462
Using HttpEntity<?> .......................................................................... 462
Using @ModelAttribute on a method .................................................. 462
Using @ModelAttribute on a method argument .................................... 463
Using @SessionAttributes to store model attributes in the HTTP
session between requests ....................................................................... 465
Specifying redirect and flash attributes ..................................................... 466
Working with "application/x-www-form-urlencoded" data ............. 466
Mapping cookie values with the @CookieValue annotation ........................ 467
Mapping request header attributes with the @RequestHeader annotation ... 467
Method Parameters And Type Conversion ............................................... 468
Customizing WebDataBinder initialization .............................................. 468
Support for the 'Last-Modified' Response Header To Facilitate Content
Caching ................................................................................................. 469
Asynchronous Request Processing .................................................................. 470
Exception Handling for Async Requests ................................................... 471
Intercepting Async Requests ................................................................... 472
Configuration for Async Request Processing ............................................ 472
Testing Controllers ......................................................................................... 473
17.4. Handler mappings .......................................................................................... 473
Intercepting requests with a HandlerInterceptor ........................................ 474
17.5. Resolving views ............................................................................................. 476
Resolving views with the ViewResolver interface .......................................... 476
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
xv
Chaining ViewResolvers ................................................................................. 478
Redirecting to views ....................................................................................... 478
RedirectView ...................................................................................... 479
The redirect: prefix ............................................................................ 479
The forward: prefix ............................................................................. 480
ContentNegotiatingViewResolver .......................................................... 480
17.6. Using flash attributes ..................................................................................... 482
17.7. Building URIs ................................................................................................ 483
17.8. Using locales ................................................................................................. 484
AcceptHeaderLocaleResolver .................................................................. 484
CookieLocaleResolver .............................................................................. 484
SessionLocaleResolver ............................................................................ 485
LocaleChangeInterceptor ........................................................................ 485
17.9. Using themes ................................................................................................ 486
Overview of themes ........................................................................................ 486
Defining themes ............................................................................................. 486
Theme resolvers ............................................................................................. 486
17.10. Spring's multipart (file upload) support ........................................................... 487
Introduction .................................................................................................... 487
Using a MultipartResolver with Commons FileUpload ................................ 487
Using a MultipartResolver with Servlet 3.0 ............................................... 488
Handling a file upload in a form ...................................................................... 488
Handling a file upload request from programmatic clients .................................. 489
17.11. Handling exceptions ..................................................................................... 490
HandlerExceptionResolver ...................................................................... 490
@ExceptionHandler .................................................................................... 491
Handling Standard Spring MVC Exceptions ...................................................... 492
Annotating Business Exceptions With @ResponseStatus ................................ 492
Customizing the Default Servlet Container Error Page ...................................... 493
17.12. Convention over configuration support ........................................................... 493
The Controller ControllerClassNameHandlerMapping .............................. 494
The Model ModelMap (ModelAndView) .......................................................... 495
The View - RequestToViewNameTranslator ............................................... 496
17.13. ETag support ............................................................................................... 497
17.14. Code-based Servlet container initialization ..................................................... 498
17.15. Configuring Spring MVC ............................................................................... 500
Enabling the MVC Java Config or the MVC XML Namespace ............................ 500
Customizing the Provided Configuration ........................................................... 501
Configuring Interceptors .................................................................................. 502
Configuring Content Negotiation ...................................................................... 503
Configuring View Controllers ........................................................................... 504
Configuring Serving of Resources ................................................................... 504
mvc:default-servlet-handler .............................................................................. 507
More Spring Web MVC Resources .................................................................. 508
Advanced Customizations with MVC Java Config ............................................. 508
Advanced Customizations with the MVC Namespace ........................................ 509
18. View technologies ..................................................................................................... 510
18.1. Introduction .................................................................................................... 510
18.2. JSP & JSTL .................................................................................................. 510
View resolvers ................................................................................................ 510
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
xvi
'Plain-old' JSPs versus JSTL ........................................................................... 511
Additional tags facilitating development ............................................................ 511
Using Spring's form tag library ........................................................................ 511
Configuration .......................................................................................... 511
The form tag ......................................................................................... 511
The input tag ....................................................................................... 513
The checkbox tag ................................................................................. 513
The checkboxes tag ............................................................................. 516
The radiobutton tag ........................................................................... 516
The radiobuttons tag ......................................................................... 517
The password tag ................................................................................. 517
The select tag ..................................................................................... 517
The option tag ..................................................................................... 518
The options tag ................................................................................... 518
The textarea tag ................................................................................. 519
The hidden tag ..................................................................................... 519
The errors tag ..................................................................................... 519
HTTP Method Conversion ....................................................................... 522
HTML5 Tags .......................................................................................... 523
18.3. Tiles .............................................................................................................. 523
Dependencies ................................................................................................ 523
How to integrate Tiles ..................................................................................... 523
UrlBasedViewResolver .................................................................... 524
ResourceBundleViewResolver ........................................................ 524
SimpleSpringPreparerFactory and
SpringBeanPreparerFactory ............................................................ 524
18.4. Velocity & FreeMarker .................................................................................... 525
Dependencies ................................................................................................ 525
Context configuration ...................................................................................... 525
Creating templates ......................................................................................... 526
Advanced configuration ................................................................................... 527
velocity.properties ................................................................................... 527
FreeMarker ............................................................................................. 527
Bind support and form handling ....................................................................... 528
The bind macros .................................................................................... 528
Simple binding ........................................................................................ 528
Form input generation macros ................................................................. 529
HTML escaping and XHTML compliance ................................................. 533
18.5. XSLT ............................................................................................................. 534
My First Words ............................................................................................... 534
Bean definitions ...................................................................................... 534
Standard MVC controller code ................................................................. 534
Convert the model data to XML ............................................................... 535
Defining the view properties .................................................................... 535
Document transformation ........................................................................ 536
Summary ....................................................................................................... 536
18.6. Document views (PDF/Excel) .......................................................................... 537
Introduction .................................................................................................... 537
Configuration and setup .................................................................................. 537
Document view definitions ....................................................................... 537
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
xvii
Controller code ....................................................................................... 537
Subclassing for Excel views .................................................................... 537
Subclassing for PDF views ..................................................................... 539
18.7. JasperReports ............................................................................................... 540
Dependencies ................................................................................................ 540
Configuration .................................................................................................. 540
Configuring the ViewResolver .............................................................. 540
Configuring the Views ............................................................................ 540
About Report Files .................................................................................. 541
Using JasperReportsMultiFormatView ............................................. 541
Populating the ModelAndView ....................................................................... 542
Working with Sub-Reports ............................................................................... 543
Configuring Sub-Report Files .................................................................. 543
Configuring Sub-Report Data Sources ..................................................... 544
Configuring Exporter Parameters ..................................................................... 544
18.8. Feed Views ................................................................................................... 544
18.9. XML Marshalling View .................................................................................... 545
18.10. JSON Mapping View .................................................................................... 546
19. Integrating with other web frameworks ....................................................................... 547
19.1. Introduction .................................................................................................... 547
19.2. Common configuration ................................................................................... 548
19.3. JavaServer Faces 1.1 and 1.2 ........................................................................ 549
DelegatingVariableResolver (JSF 1.1/1.2) ........................................................ 549
SpringBeanVariableResolver (JSF 1.1/1.2) ....................................................... 550
SpringBeanFacesELResolver (JSF 1.2+) ......................................................... 550
FacesContextUtils ........................................................................................... 550
19.4. Apache Struts 1.x and 2.x .............................................................................. 551
ContextLoaderPlugin ....................................................................................... 551
DelegatingRequestProcessor ................................................................... 552
DelegatingActionProxy ............................................................................ 552
ActionSupport Classes .................................................................................... 553
19.5. WebWork 2.x ................................................................................................. 553
19.6. Tapestry 3.x and 4.x ...................................................................................... 554
Injecting Spring-managed beans ..................................................................... 555
Dependency Injecting Spring Beans into Tapestry pages ........................... 557
Component definition files ....................................................................... 558
Adding abstract accessors ...................................................................... 559
Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x
style ....................................................................................................... 561
19.7. Further Resources ......................................................................................... 562
20. Portlet MVC Framework ............................................................................................ 563
20.1. Introduction .................................................................................................... 563
Controllers - The C in MVC ............................................................................ 564
Views - The V in MVC .................................................................................... 564
Web-scoped beans ......................................................................................... 564
20.2. The DispatcherPortlet ............................................................................ 564
20.3. The ViewRendererServlet ........................................................................ 566
20.4. Controllers ..................................................................................................... 567
AbstractController and PortletContentGenerator ............................. 568
Other simple controllers .................................................................................. 569
Spring Framework
3.2.5.RELEASE
Spring Framework
Reference Documentation
xviii
Command Controllers ..................................................................................... 569
PortletWrappingController .................................................................... 570
20.5. Handler mappings .......................................................................................... 570
PortletModeHandlerMapping .................................................................... 571
ParameterHandlerMapping ........................................................................ 571
PortletModeParameterHandlerMapping .................................................. 572
Adding HandlerInterceptors ..................................................................... 572
HandlerInterceptorAdapter .................................................................... 573
ParameterMappingInterceptor ................................................................ 573
20.6. Views and resolving them .............................................................................. 573
20.7. Multipart (file upload) support ......................................................................... 574
Using the PortletMultipartResolver ....................................................... 574
Handling a file upload in a form ...................................................................... 575
20.8. Handling exceptions ....................................................................................... 578
20.9. Annotation-based controller configuration ........................................................ 578
Setting up the dispatcher for annotation support ............................................... 578
Defining a controller with @Controller .......................................................... 579
Mapping requests with @RequestMapping ..................................................... 580
Supported handler method arguments ............................................................. 581
Binding request parameters to method parameters with @RequestParam .......... 583
Providing a link to data from the model with @ModelAttribute ....................... 583
Specifying attributes to store in a Session with @SessionAttributes ............. 584
Customizing WebDataBinder initialization ...................................................... 584
Customizing data binding with @InitBinder .......................................... 584
Configuring a custom WebBindingInitializer ................................... 585
20.10. Portlet application deployment ...................................................................... 585
VI. Integration ......................................................................................................................... 586
21. Remoting and web services using Spring ................................................................... 587
21.1. Introduction .................................................................................................... 587
21.2. Exposing services using RMI .......................................................................... 588
Exporting the service using the RmiServiceExporter ................................... 588
Linking in the service at the client ................................................................... 589
21.3. Using Hessian or Burlap to remotely call services via HTTP .............................. 589
Wiring up the DispatcherServlet for Hessian and co. ................................. 589
Exposing your beans by using the HessianServiceExporter ....................... 590
Linking in the service on the client .................................................................. 591
Using Burlap .................................................................................................. 591
Applying HTTP basic authentication to a service exposed through Hessian or
Burlap ............................................................................................................ 591
21.4. Exposing services using HTTP invokers .......................................................... 592
Exposing the service object ............................................................................ 592
Linking in the service at the client ................................................................... 593
21.5. Web services ................................................................................................. 593
Exposing servlet-based web services using JAX-RPC ....................................... 594
Accessing web services using JAX-RPC .......................................................... 595
Registering JAX-RPC Bean Mappings ............................................................. 597
Registering your own JAX-RPC Handler .......................................................... 597
Exposing servlet-based web services using JAX-WS ........................................ 598
Exporting standalone web services using JAX-WS ........................................... 599