Spring Reference
-
Upload
anaga1982234015838 -
Category
Documents
-
view
217 -
download
5
description
Transcript of Spring Reference
-
Spring Framework Reference Manual
Rod JohnsonJuergen Hoeller
Keith DonaldColin Sampaleanu
Rob HarropThomas RisbergAlef Arendsen
Darren DavisonDmitriy Kopylenko
Mark PollackThierry Templier
Erwin VervaetPortia Tung
Ben HaleAdrian ColyerJohn LewisCostin LeauMark Fisher
Sam BrannenRamnivas Laddad
Arjen PoutsmaChris Beams
Tareq AbedrabboAndy Clement
Dave SyerOliver Gierke
Rossen Stoyanchev
-
Spring Framework Reference Manualby 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, ChrisBeams, Tareq Abedrabbo, Andy Clement, Dave Syer, Oliver Gierke, and Rossen Stoyanchev
3.2.0.BUILD-SNAPSHOTCopyright 2004-2012 Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, Rob Harrop, AlefArendsen, 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, Rossen StoyanchevCopies 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 copiesand further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual iii
Table of ContentsI. Overview of Spring Framework .............................................................................................. 1
1. Introduction to Spring Framework ................................................................................... 21.1. Dependency Injection and Inversion of Control ..................................................... 21.2. Modules .............................................................................................................. 3
Core Container ................................................................................................... 3Data Access/Integration ...................................................................................... 4Web .................................................................................................................. 4AOP and Instrumentation ................................................................................... 4Test ................................................................................................................... 5
1.3. Usage scenarios ................................................................................................... 5Dependency Management and Naming Conventions ............................................ 8
Spring Dependencies and Depending on Spring .......................................... 10Maven Dependency Management .............................................................. 10Ivy Dependency Management ................................................................... 11
Logging ........................................................................................................... 12Not Using Commons Logging ................................................................... 13Using SLF4J ............................................................................................ 13Using Log4J ............................................................................................ 15
II. What's New in Spring 3 ....................................................................................................... 172. New Features and Enhancements in Spring 3.0 .............................................................. 18
2.1. Java 5 ............................................................................................................... 182.2. Improved documentation .................................................................................... 182.3. New articles and tutorials ................................................................................... 182.4. New module organization and build system ......................................................... 192.5. Overview of new features .................................................................................. 20
Core APIs updated for Java 5 ........................................................................... 20Spring Expression Language ............................................................................. 21The Inversion of Control (IoC) container ........................................................... 21
Java based bean metadata ......................................................................... 21Defining bean metadata within components ............................................... 23
General purpose type conversion system and field formatting system ................... 23The Data Tier .................................................................................................. 23The Web Tier .................................................................................................. 23
Comprehensive REST support ................................................................... 23@MVC additions ..................................................................................... 23
Declarative model validation ............................................................................. 24Early support for Java EE 6 .............................................................................. 24Support for embedded databases ....................................................................... 24
3. New Features and Enhancements in Spring 3.1 .............................................................. 253.1. Overview of new features .................................................................................. 25
Cache Abstraction ............................................................................................ 25Bean Definition Profiles ................................................................................... 25Environment Abstraction .................................................................................. 25
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual iv
PropertySource Abstraction ............................................................................... 25Code equivalents for Spring's XML namespaces ................................................ 25Support for Hibernate 4.x ................................................................................. 26TestContext framework support for @Configuration classes and bean definitionprofiles ............................................................................................................ 26c: namespace for more concise constructor injection ........................................... 27Support for injection against non-standard JavaBeans setters ............................... 27Support for Servlet 3 code-based configuration of Servlet Container .................... 27Support for Servlet 3 MultipartResolver ............................................................ 27JPA EntityManagerFactory bootstrapping without persistence.xml ....................... 27New HandlerMethod-based Support Classes For Annotated ControllerProcessing ........................................................................................................ 27"consumes" and "produces" conditions in @RequestMapping .............................. 28Flash Attributes and RedirectAttributes ................................................. 28URI Template Variable Enhancements .............................................................. 29@Valid On @RequestBody Controller Method Arguments ............................... 29@RequestPart Annotation On Controller Method Arguments ......................... 29UriComponentsBuilder and UriComponents ........................................ 29
III. Core Technologies .............................................................................................................. 304. The IoC container ........................................................................................................ 31
4.1. Introduction to the Spring IoC container and beans .............................................. 314.2. Container overview ............................................................................................ 31
Configuration metadata ..................................................................................... 32Instantiating a container .................................................................................... 33
Composing XML-based configuration metadata ......................................... 35Using the container .......................................................................................... 36
4.3. Bean overview .................................................................................................. 36Naming beans .................................................................................................. 37
Aliasing a bean outside the bean definition ................................................ 38Instantiating beans ............................................................................................ 38
Instantiation with a constructor ................................................................. 39Instantiation with a static factory method ................................................... 40Instantiation using an instance factory method ........................................... 40
4.4. Dependencies .................................................................................................... 41Dependency injection ....................................................................................... 41
Constructor-based dependency injection ..................................................... 42Setter-based dependency injection ............................................................. 44Dependency resolution process .................................................................. 45Examples of dependency injection ............................................................. 46
Dependencies and configuration in detail ........................................................... 48Straight values (primitives, Strings, and so on) ...................................... 48References to other beans (collaborators) ................................................... 50Inner beans .............................................................................................. 51Collections ............................................................................................... 51Null and empty string values .................................................................... 54
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual v
XML shortcut with the p-namespace ......................................................... 54XML shortcut with the c-namespace ......................................................... 55Compound property names ....................................................................... 56
Using depends-on ........................................................................................ 57Lazy-initialized beans ....................................................................................... 57Autowiring collaborators ................................................................................... 58
Limitations and disadvantages of autowiring .............................................. 59Excluding a bean from autowiring ............................................................. 60
Method injection .............................................................................................. 60Lookup method injection .......................................................................... 61Arbitrary method replacement ................................................................... 62
4.5. Bean scopes ...................................................................................................... 63The singleton scope .......................................................................................... 64The prototype scope ......................................................................................... 65Singleton beans with prototype-bean dependencies ............................................. 66Request, session, and global session scopes ....................................................... 67
Initial web configuration ........................................................................... 67Request scope .......................................................................................... 68Session scope ........................................................................................... 68Global session scope ................................................................................ 68Scoped beans as dependencies .................................................................. 68
Custom scopes ................................................................................................. 71Creating a custom scope ........................................................................... 71Using a custom scope ............................................................................... 71
4.6. Customizing the nature of a bean ....................................................................... 73Lifecycle callbacks ........................................................................................... 73
Initialization callbacks .............................................................................. 73Destruction callbacks ................................................................................ 74Default initialization and destroy methods .................................................. 74Combining lifecycle mechanisms .............................................................. 76Startup and shutdown callbacks ................................................................. 76Shutting down the Spring IoC container gracefully in non-webapplications .............................................................................................. 78
ApplicationContextAware and BeanNameAware .................................. 79Other Aware interfaces .................................................................................... 79
4.7. Bean definition inheritance ................................................................................. 814.8. Container Extension Points ................................................................................ 82
Customizing beans using a BeanPostProcessor .......................................... 83Example: Hello World, BeanPostProcessor-style ............................... 84Example: The RequiredAnnotationBeanPostProcessor .............. 85
Customizing configuration metadata with a BeanFactoryPostProcessor......................................................................................................................... 86
Example: the PropertyPlaceholderConfigurer ............................ 87Example: the PropertyOverrideConfigurer .................................. 88
Customizing instantiation logic with a FactoryBean ...................................... 89
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual vi
4.9. Annotation-based container configuration ............................................................ 90@Required .................................................................................................... 91@Autowired .................................................................................................. 92Fine-tuning annotation-based autowiring with qualifiers ...................................... 94CustomAutowireConfigurer ................................................................... 99@Resource .................................................................................................. 100@PostConstruct and @PreDestroy ........................................................ 101
4.10. Classpath scanning and managed components .................................................. 102@Component and further stereotype annotations ............................................. 102Automatically detecting classes and registering bean definitions ........................ 103Using filters to customize scanning ................................................................. 104Defining bean metadata within components ..................................................... 105Naming autodetected components .................................................................... 106Providing a scope for autodetected components ................................................ 107Providing qualifier metadata with annotations .................................................. 107
4.11. Using JSR 330 Standard Annotations .............................................................. 108Dependency Injection with @Inject and @Named ......................................... 109@Named: a standard equivalent to the @Component annotation ....................... 109Limitations of the standard approach ............................................................... 110
4.12. Java-based container configuration .................................................................. 111Basic concepts: @Configuration and @Bean ............................................. 111Instantiating the Spring container usingAnnotationConfigApplicationContext ........................................... 111
Simple construction ................................................................................ 111Building the container programmatically using register(Class
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual vii
Convenient ApplicationContext instantiation for web applications ........... 131Deploying a Spring ApplicationContext as a J2EE RAR file .............................. 132
4.15. The BeanFactory ............................................................................................ 133BeanFactory or ApplicationContext? ................................................ 133Glue code and the evil singleton ..................................................................... 135
5. Resources ................................................................................................................... 1365.1. Introduction ..................................................................................................... 1365.2. The Resource interface ................................................................................. 1365.3. Built-in Resource implementations ................................................................ 137
UrlResource .............................................................................................. 137ClassPathResource ................................................................................. 137FileSystemResource .............................................................................. 138ServletContextResource ...................................................................... 138InputStreamResource ............................................................................ 138ByteArrayResource ................................................................................. 138
5.4. The ResourceLoader .................................................................................. 1385.5. The ResourceLoaderAware interface ......................................................... 1405.6. Resources as dependencies .......................................................................... 1405.7. Application contexts and Resource paths ....................................................... 141
Constructing application contexts .................................................................... 141Constructing ClassPathXmlApplicationContext instances -shortcuts ................................................................................................. 142
Wildcards in application context constructor resource paths ............................... 142Ant-style Patterns ................................................................................... 142The classpath*: prefix ..................................................................... 143Other notes relating to wildcards ............................................................. 144
FileSystemResource caveats ................................................................... 1446. Validation, Data Binding, and Type Conversion ........................................................... 146
6.1. Introduction ..................................................................................................... 1466.2. Validation using Spring's Validator interface ............................................... 1466.3. Resolving codes to error messages .................................................................... 1486.4. Bean manipulation and the BeanWrapper ...................................................... 148
Setting and getting basic and nested properties ................................................. 149Built-in PropertyEditor implementations .......................................................... 150
Registering additional custom PropertyEditors ................................ 1536.5. Spring 3 Type Conversion ................................................................................ 156
Converter SPI ................................................................................................. 156ConverterFactory ............................................................................................ 157GenericConverter ............................................................................................ 158
ConditionalGenericConverter .................................................................. 158ConversionService API ................................................................................... 159Configuring a ConversionService .................................................................... 159Using a ConversionService programmatically ................................................... 160
6.6. Spring 3 Field Formatting ................................................................................ 160Formatter SPI ................................................................................................. 161
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual viii
Annotation-driven Formatting ......................................................................... 162Format Annotation API ........................................................................... 163
FormatterRegistry SPI ..................................................................................... 163FormatterRegistrar SPI .................................................................................... 164Configuring Formatting in Spring MVC .......................................................... 164
6.7. Spring 3 Validation .......................................................................................... 166Overview of the JSR-303 Bean Validation API ................................................ 166Configuring a Bean Validation Implementation ................................................ 166
Injecting a Validator ............................................................................... 167Configuring Custom Constraints .............................................................. 167Additional Configuration Options ............................................................ 168
Configuring a DataBinder ............................................................................... 168Spring MVC 3 Validation ............................................................................... 169
Triggering @Controller Input Validation ................................................. 169Configuring a Validator for use by Spring MVC ...................................... 169Configuring a JSR-303 Validator for use by Spring MVC ......................... 170
7. Spring Expression Language (SpEL) ........................................................................... 1717.1. Introduction ..................................................................................................... 1717.2. Feature Overview ............................................................................................ 1717.3. Expression Evaluation using Spring's Expression Interface ................................. 172
The EvaluationContext interface ...................................................................... 174Type Conversion .................................................................................... 175
7.4. Expression support for defining bean definitions ................................................ 175XML based configuration ............................................................................... 175Annotation-based configuration ....................................................................... 176
7.5. Language Reference ......................................................................................... 177Literal expressions .......................................................................................... 177Properties, Arrays, Lists, Maps, Indexers ......................................................... 178Inline lists ...................................................................................................... 179Array construction .......................................................................................... 179Methods ......................................................................................................... 179Operators ....................................................................................................... 180
Relational operators ................................................................................ 180Logical operators .................................................................................... 180Mathematical operators ........................................................................... 181
Assignment .................................................................................................... 181Types ............................................................................................................. 182Constructors ................................................................................................... 182Variables ........................................................................................................ 182
The #this and #root variables .................................................................. 182Functions ....................................................................................................... 183Bean references .............................................................................................. 183Ternary Operator (If-Then-Else) ...................................................................... 184The Elvis Operator ......................................................................................... 184Safe Navigation operator ................................................................................ 185
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual ix
Collection Selection ........................................................................................ 185Collection Projection ...................................................................................... 186Expression templating ..................................................................................... 186
7.6. Classes used in the examples ............................................................................ 1878. Aspect Oriented Programming with Spring .................................................................. 190
8.1. Introduction ..................................................................................................... 190AOP concepts ................................................................................................ 190Spring AOP capabilities and goals ................................................................... 192AOP Proxies .................................................................................................. 193
8.2. @AspectJ support ............................................................................................ 193Enabling @AspectJ Support ............................................................................ 193Declaring an aspect ........................................................................................ 194Declaring a pointcut ....................................................................................... 195
Supported Pointcut Designators ............................................................... 195Combining pointcut expressions .............................................................. 197Sharing common pointcut definitions ....................................................... 197Examples ............................................................................................... 199Writing good pointcuts ........................................................................... 201
Declaring advice ............................................................................................. 202Before advice ......................................................................................... 202After returning advice ............................................................................. 202After throwing advice ............................................................................. 203After (finally) advice .............................................................................. 204Around advice ........................................................................................ 204Advice parameters .................................................................................. 205Advice ordering ...................................................................................... 209
Introductions .................................................................................................. 209Aspect instantiation models ............................................................................. 210Example ......................................................................................................... 211
8.3. Schema-based AOP support ............................................................................. 212Declaring an aspect ........................................................................................ 213Declaring a pointcut ....................................................................................... 213Declaring advice ............................................................................................. 215
Before advice ......................................................................................... 215After returning advice ............................................................................. 216After throwing advice ............................................................................. 216After (finally) advice .............................................................................. 217Around advice ........................................................................................ 217Advice parameters .................................................................................. 218Advice ordering ...................................................................................... 220
Introductions .................................................................................................. 220Aspect instantiation models ............................................................................. 221Advisors ......................................................................................................... 221Example ......................................................................................................... 221
8.4. Choosing which AOP declaration style to use .................................................... 223
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual x
Spring AOP or full AspectJ? ........................................................................... 223@AspectJ or XML for Spring AOP? ............................................................... 224
8.5. Mixing aspect types ......................................................................................... 2258.6. Proxying mechanisms ...................................................................................... 225
Understanding AOP proxies ............................................................................ 2268.7. Programmatic creation of @AspectJ Proxies ...................................................... 2288.8. Using AspectJ with Spring applications ............................................................. 229
Using AspectJ to dependency inject domain objects with Spring ........................ 229Unit testing @Configurable objects .................................................... 231Working with multiple application contexts .............................................. 232
Other Spring aspects for AspectJ ..................................................................... 232Configuring AspectJ aspects using Spring IoC ................................................. 233Load-time weaving with AspectJ in the Spring Framework ............................... 234
A first example ...................................................................................... 234Aspects .................................................................................................. 237'META-INF/aop.xml' ......................................................................... 238Required libraries (JARS) ....................................................................... 238Spring configuration ............................................................................... 238Environment-specific configuration ......................................................... 240
8.9. Further Resources ............................................................................................ 2439. Spring AOP APIs ....................................................................................................... 244
9.1. Introduction ..................................................................................................... 2449.2. Pointcut API in Spring ..................................................................................... 244
Concepts ........................................................................................................ 244Operations on pointcuts .................................................................................. 245AspectJ expression pointcuts ........................................................................... 245Convenience pointcut implementations ............................................................ 245
Static pointcuts ....................................................................................... 245Dynamic pointcuts .................................................................................. 247
Pointcut superclasses ...................................................................................... 247Custom pointcuts ............................................................................................ 247
9.3. Advice API in Spring ...................................................................................... 248Advice lifecycles ............................................................................................ 248Advice types in Spring ................................................................................... 248
Interception around advice ...................................................................... 248Before advice ......................................................................................... 249Throws advice ........................................................................................ 250After Returning advice ............................................................................ 251Introduction advice ................................................................................. 251
9.4. Advisor API in Spring ..................................................................................... 2549.5. Using the ProxyFactoryBean to create AOP proxies ........................................... 254
Basics ............................................................................................................ 254JavaBean properties ........................................................................................ 255JDK- and CGLIB-based proxies ...................................................................... 256Proxying interfaces ......................................................................................... 257
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xi
Proxying classes ............................................................................................. 258Using 'global' advisors .................................................................................... 259
9.6. Concise proxy definitions ................................................................................. 2599.7. Creating AOP proxies programmatically with the ProxyFactory .......................... 2609.8. Manipulating advised objects ............................................................................ 2619.9. Using the "autoproxy" facility .......................................................................... 262
Autoproxy bean definitions ............................................................................. 263BeanNameAutoProxyCreator ................................................................... 263DefaultAdvisorAutoProxyCreator ............................................................ 263AbstractAdvisorAutoProxyCreator ........................................................... 265
Using metadata-driven auto-proxying .............................................................. 2659.10. Using TargetSources ...................................................................................... 267
Hot swappable target sources .......................................................................... 267Pooling target sources ..................................................................................... 268Prototype target sources .................................................................................. 269ThreadLocal target sources ........................................................................ 270
9.11. Defining new Advice types .......................................................................... 2709.12. Further resources ........................................................................................... 270
10. Testing ..................................................................................................................... 27110.1. Introduction to Spring Testing ........................................................................ 27110.2. Unit Testing .................................................................................................. 271
Mock Objects ................................................................................................. 271JNDI ...................................................................................................... 271Servlet API ............................................................................................ 271Portlet API ............................................................................................. 271
Unit Testing support Classes ........................................................................... 272General utilities ...................................................................................... 272Spring MVC .......................................................................................... 272
10.3. Integration Testing ......................................................................................... 272Overview ....................................................................................................... 272Goals of Integration Testing ............................................................................ 273
Context management and caching ............................................................ 273Dependency Injection of test fixtures ....................................................... 274Transaction management ......................................................................... 274Support classes for integration testing ...................................................... 275
JDBC Testing Support .................................................................................... 275Annotations .................................................................................................... 275
Spring Testing Annotations ..................................................................... 275Standard Annotation Support ................................................................... 279Spring JUnit Testing Annotations ............................................................ 280
Spring TestContext Framework ....................................................................... 281Key abstractions ..................................................................................... 282Context management .............................................................................. 283Dependency injection of test fixtures ....................................................... 291Transaction management ......................................................................... 293
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xii
TestContext support classes ..................................................................... 295PetClinic Example .......................................................................................... 298
10.4. Further Resources .......................................................................................... 299IV. Data Access ..................................................................................................................... 301
11. Transaction Management .......................................................................................... 30211.1. Introduction to Spring Framework transaction management .............................. 30211.2. Advantages of the Spring Framework's transaction support model ..................... 302
Global transactions ......................................................................................... 303Local transactions ........................................................................................... 303Spring Framework's consistent programming model ......................................... 303
11.3. Understanding the Spring Framework transaction abstraction ............................ 30411.4. Synchronizing resources with transactions ....................................................... 308
High-level synchronization approach ............................................................... 308Low-level synchronization approach ................................................................ 308TransactionAwareDataSourceProxy .................................................. 309
11.5. Declarative transaction management ................................................................ 309Understanding the Spring Framework's declarative transaction implementation....................................................................................................................... 310Example of declarative transaction implementation ........................................... 311Rolling back a declarative transaction .............................................................. 315Configuring different transactional semantics for different beans ....................... 316 settings ............................................................................... 318Using @Transactional ............................................................................. 319
@Transactional settings ................................................................... 323Multiple Transaction Managers with @Transactional ......................... 324Custom shortcut annotations .................................................................... 325
Transaction propagation .................................................................................. 325Required ................................................................................................ 326RequiresNew .......................................................................................... 327Nested .................................................................................................... 327
Advising transactional operations .................................................................... 327Using @Transactional with AspectJ ......................................................... 330
11.6. Programmatic transaction management ............................................................ 331Using the TransactionTemplate ............................................................. 331
Specifying transaction settings ................................................................. 333Using the PlatformTransactionManager .............................................. 333
11.7. Choosing between programmatic and declarative transaction management .......... 33411.8. Application server-specific integration ............................................................. 334
IBM WebSphere ............................................................................................. 335BEA WebLogic Server ................................................................................... 335Oracle OC4J .................................................................................................. 335
11.9. Solutions to common problems ....................................................................... 335Use of the wrong transaction manager for a specific DataSource ................... 335
11.10. Further Resources ........................................................................................ 33512. DAO support ............................................................................................................ 337
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xiii
12.1. Introduction ................................................................................................... 33712.2. Consistent exception hierarchy ........................................................................ 33712.3. Annotations used for configuring DAO or Repository classes ............................ 338
13. Data access with JDBC ............................................................................................. 34013.1. Introduction to Spring Framework JDBC ......................................................... 340
Choosing an approach for JDBC database access .............................................. 340Package hierarchy ........................................................................................... 341
13.2. Using the JDBC core classes to control basic JDBC processing and errorhandling ................................................................................................................. 342
JdbcTemplate ........................................................................................... 342Examples of JdbcTemplate class usage .................................................... 342JdbcTemplate best practices .............................................................. 344
NamedParameterJdbcTemplate ............................................................. 346SimpleJdbcTemplate .............................................................................. 348SQLExceptionTranslator ...................................................................... 350Executing statements ...................................................................................... 351Running queries ............................................................................................. 352Updating the database ..................................................................................... 352Retrieving auto-generated keys ........................................................................ 353
13.3. Controlling database connections .................................................................... 353DataSource ................................................................................................ 353DataSourceUtils ..................................................................................... 355SmartDataSource ..................................................................................... 355AbstractDataSource .............................................................................. 355SingleConnectionDataSource ............................................................. 355DriverManagerDataSource ................................................................... 356TransactionAwareDataSourceProxy .................................................. 356DataSourceTransactionManager ......................................................... 356NativeJdbcExtractor ........................................................................................ 357
13.4. JDBC batch operations ................................................................................... 357Basic batch operations with the JdbcTemplate .................................................. 357Batch operations with a List of objects ............................................................ 358Batch operations with multiple batches ............................................................ 359
13.5. Simplifying JDBC operations with the SimpleJdbc classes ................................ 360Inserting data using SimpleJdbcInsert .............................................................. 360Retrieving auto-generated keys using SimpleJdbcInsert ..................................... 361Specifying columns for a SimpleJdbcInsert ...................................................... 362Using SqlParameterSource to provide parameter values .................................... 362Calling a stored procedure with SimpleJdbcCall ............................................... 363Explicitly declaring parameters to use for a SimpleJdbcCall .............................. 365How to define SqlParameters .......................................................................... 366Calling a stored function using SimpleJdbcCall ................................................ 366Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................... 367
13.6. Modeling JDBC operations as Java objects ...................................................... 368SqlQuery .................................................................................................... 369
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xiv
MappingSqlQuery ..................................................................................... 369SqlUpdate .................................................................................................. 370StoredProcedure ..................................................................................... 371
13.7. Common problems with parameter and data value handling .............................. 374Providing SQL type information for parameters ............................................... 374Handling BLOB and CLOB objects ................................................................. 374Passing in lists of values for IN clause ............................................................ 376Handling complex types for stored procedure calls ........................................... 376
13.8. Embedded database support ............................................................................ 378Why use an embedded database? ..................................................................... 378Creating an embedded database instance using Spring XML .............................. 378Creating an embedded database instance programmatically ............................... 378Extending the embedded database support ....................................................... 378Using HSQL .................................................................................................. 379Using H2 ....................................................................................................... 379Using Derby ................................................................................................... 379Testing data access logic with an embedded database ....................................... 379
13.9. Initializing a DataSource ................................................................................ 379Initializing a database instance using Spring XML ............................................ 380
Initialization of Other Components that Depend on the Database ................ 38114. Object Relational Mapping (ORM) Data Access ......................................................... 382
14.1. Introduction to ORM with Spring ................................................................... 38214.2. General ORM integration considerations ......................................................... 383
Resource and transaction management ............................................................. 383Exception translation ...................................................................................... 384
14.3. Hibernate ....................................................................................................... 384SessionFactory setup in a Spring container .............................................. 385Implementing DAOs based on plain Hibernate 3 API ....................................... 386Declarative transaction demarcation ................................................................. 387Programmatic transaction demarcation ............................................................. 389Transaction management strategies .................................................................. 390Comparing container-managed and locally defined resources ............................. 392Spurious application server warnings with Hibernate ........................................ 393
14.4. JDO .............................................................................................................. 394PersistenceManagerFactory setup ...................................................... 394Implementing DAOs based on the plain JDO API ............................................ 395Transaction management ................................................................................. 397JdoDialect ................................................................................................ 398
14.5. JPA ............................................................................................................... 399Three options for JPA setup in a Spring environment ........................................ 399
LocalEntityManagerFactoryBean .............................................. 399Obtaining an EntityManagerFactory from JNDI ............................. 400LocalContainerEntityManagerFactoryBean ........................... 400Dealing with multiple persistence units .................................................... 402
Implementing DAOs based on plain JPA ......................................................... 403
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xv
Transaction Management ................................................................................ 405JpaDialect ................................................................................................ 406
14.6. iBATIS SQL Maps ........................................................................................ 407Setting up the SqlMapClient ...................................................................... 407Using SqlMapClientTemplate and SqlMapClientDaoSupport ......... 408Implementing DAOs based on plain iBATIS API ............................................. 409
15. Marshalling XML using O/X Mappers ....................................................................... 41115.1. Introduction ................................................................................................... 41115.2. Marshaller and Unmarshaller .......................................................................... 411
Marshaller ...................................................................................................... 411Unmarshaller .................................................................................................. 412XmlMappingException ................................................................................... 413
15.3. Using Marshaller and Unmarshaller ................................................................ 41315.4. XML Schema-based Configuration ................................................................. 41515.5. JAXB ............................................................................................................ 416
Jaxb2Marshaller ............................................................................................. 416XML Schema-based Configuration .......................................................... 416
15.6. Castor ............................................................................................................ 417CastorMarshaller ............................................................................................ 417Mapping ......................................................................................................... 417
15.7. XMLBeans .................................................................................................... 418XmlBeansMarshaller ....................................................................................... 418
XML Schema-based Configuration .......................................................... 41815.8. JiBX .............................................................................................................. 418
JibxMarshaller ................................................................................................ 419XML Schema-based Configuration .......................................................... 419
15.9. XStream ........................................................................................................ 419XStreamMarshaller ......................................................................................... 419
V. The Web ........................................................................................................................... 42116. Web MVC framework .............................................................................................. 422
16.1. Introduction to Spring Web MVC framework .................................................. 422Features of Spring Web MVC ......................................................................... 423Pluggability of other MVC implementations .................................................... 424
16.2. The DispatcherServlet ......................................................................... 424Special Bean Types In the WebApplicationContext ................................ 427Default DispatcherServlet Configuration .......................................................... 428DispatcherServlet Processing Sequence ............................................................ 428
16.3. Implementing Controllers ............................................................................... 429Defining a controller with @Controller ...................................................... 430Mapping Requests With @RequestMapping ................................................ 431
New Support Classes for @RequestMapping methods in Spring MVC3.1 ......................................................................................................... 432URI Template Patterns ............................................................................ 433URI Template Patterns with Regular Expressions ..................................... 435Path Patterns .......................................................................................... 435
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xvi
Consumable Media Types ....................................................................... 435Producible Media Types ......................................................................... 435Request Parameters and Header Values .................................................... 436
Defining @RequestMapping handler methods .................................................. 437Supported method argument types ........................................................... 437Supported method return types ................................................................ 439Binding request parameters to method parameters with @RequestParam............................................................................................................... 440Mapping the request body with the @RequestBody annotation .................. 440Mapping the response body with the @ResponseBody annotation ........... 441Using HttpEntity ....................................................................... 442Using @ModelAttribute on a method ................................................ 442Using @ModelAttribute on a method argument ................................. 443Using @SessionAttributes to store model attributes in the HTTPsession between requests ......................................................................... 445Specifying redirect and flash attributes ..................................................... 446Working with "application/x-www-form-urlencoded" data ..... 446Mapping cookie values with the @CookieValue annotation ....................... 447Mapping request header attributes with the @RequestHeader annotation ..... 447Method Parameters And Type Conversion ............................................... 448Customizing WebDataBinder initialization .......................................... 448Support for the 'Last-Modified' Response Header To Facilitate ContentCaching .................................................................................................. 449
16.4. Handler mappings .......................................................................................... 450Intercepting requests with a HandlerInterceptor ..................................... 451
16.5. Resolving views ............................................................................................. 452Resolving views with the ViewResolver interface ....................................... 453Chaining ViewResolvers ................................................................................. 454Redirecting to views ....................................................................................... 455
RedirectView .................................................................................... 456The redirect: prefix ......................................................................... 456The forward: prefix ........................................................................... 457
ContentNegotiatingViewResolver .................................................... 45716.6. Using flash attributes ..................................................................................... 45916.7. Building URIs ............................................................................................... 46016.8. Using locales ................................................................................................. 461
AcceptHeaderLocaleResolver ............................................................. 461CookieLocaleResolver .......................................................................... 461SessionLocaleResolver ........................................................................ 462LocaleChangeInterceptor ................................................................... 462
16.9. Using themes ................................................................................................. 463Overview of themes ........................................................................................ 463Defining themes ............................................................................................. 463Theme resolvers ............................................................................................. 464
16.10. Spring's multipart (file upload) support .......................................................... 464
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xvii
Introduction .................................................................................................... 464Using a MultipartResolver with Commons FileUpload ........................... 464Using a MultipartResolver with Servlet 3.0 ............................................ 465Handling a file upload in a form ..................................................................... 465Handling a file upload request from programmatic clients ................................. 466
16.11. Handling exceptions ..................................................................................... 467HandlerExceptionResolver ................................................................. 467@ExceptionHandler ................................................................................. 468
16.12. Convention over configuration support .......................................................... 469The Controller ControllerClassNameHandlerMapping ....................... 469The Model ModelMap (ModelAndView) ..................................................... 470The View - RequestToViewNameTranslator ......................................... 471
16.13. ETag support ............................................................................................... 47316.14. Configuring Spring MVC ............................................................................. 473
Enabling MVC Java Config or the MVC XML Namespace ............................... 474Customizing the Provided Configuration .......................................................... 475Configuring Interceptors ................................................................................. 476Configuring View Controllers ......................................................................... 476Configuring Serving of Resources ................................................................... 477mvc:default-servlet-handler ............................................................................. 479More Spring Web MVC Resources ................................................................. 480Advanced Customizations with MVC Java Config ............................................ 480Advanced Customizations with the MVC Namespace ....................................... 481
17. View technologies .................................................................................................... 48217.1. Introduction ................................................................................................... 48217.2. JSP & JSTL .................................................................................................. 482
View resolvers ............................................................................................... 482'Plain-old' JSPs versus JSTL ........................................................................... 483Additional tags facilitating development .......................................................... 483Using Spring's form tag library ....................................................................... 483
Configuration ......................................................................................... 483The form tag ........................................................................................ 484The input tag ...................................................................................... 485The checkbox tag ................................................................................ 485The checkboxes tag ........................................................................... 487The radiobutton tag ......................................................................... 487The radiobuttons tag ....................................................................... 488The password tag ................................................................................ 488The select tag .................................................................................... 488The option tag .................................................................................... 489The options tag .................................................................................. 489The textarea tag ................................................................................ 490The hidden tag .................................................................................... 490The errors tag .................................................................................... 490HTTP Method Conversion ...................................................................... 492
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xviii
HTML5 Tags ......................................................................................... 49317.3. Tiles .............................................................................................................. 493
Dependencies ................................................................................................. 494How to integrate Tiles .................................................................................... 494
UrlBasedViewResolver ................................................................ 494ResourceBundleViewResolver ................................................... 494SimpleSpringPreparerFactory andSpringBeanPreparerFactory ....................................................... 495
17.4. Velocity & FreeMarker .................................................................................. 496Dependencies ................................................................................................. 496Context configuration ..................................................................................... 496Creating templates .......................................................................................... 497Advanced configuration .................................................................................. 497
velocity.properties ................................................................................... 497FreeMarker ............................................................................................. 498
Bind support and form handling ...................................................................... 498The bind macros ..................................................................................... 498Simple binding ....................................................................................... 498Form input generation macros ................................................................. 499HTML escaping and XHTML compliance ............................................... 503
17.5. XSLT ............................................................................................................ 504My First Words .............................................................................................. 504
Bean definitions ..................................................................................... 504Standard MVC controller code ................................................................ 504Convert the model data to XML .............................................................. 505Defining the view properties ................................................................... 506Document transformation ........................................................................ 506
Summary ........................................................................................................ 50717.6. Document views (PDF/Excel) ......................................................................... 507
Introduction .................................................................................................... 507Configuration and setup .................................................................................. 507
Document view definitions ...................................................................... 508Controller code ....................................................................................... 508Subclassing for Excel views .................................................................... 508Subclassing for PDF views ..................................................................... 509
17.7. JasperReports ................................................................................................. 510Dependencies ................................................................................................. 510Configuration ................................................................................................. 510
Configuring the ViewResolver ........................................................... 511Configuring the Views ........................................................................... 511About Report Files ................................................................................. 511Using JasperReportsMultiFormatView ....................................... 512
Populating the ModelAndView ..................................................................... 512Working with Sub-Reports .............................................................................. 513
Configuring Sub-Report Files .................................................................. 514
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xix
Configuring Sub-Report Data Sources ..................................................... 514Configuring Exporter Parameters ..................................................................... 515
17.8. Feed Views ................................................................................................... 51517.9. XML Marshalling View ................................................................................. 51617.10. JSON Mapping View ................................................................................... 516
18. Integrating with other web frameworks ...................................................................... 51718.1. Introduction ................................................................................................... 51718.2. Common configuration ................................................................................... 51818.3. JavaServer Faces 1.1 and 1.2 .......................................................................... 519
DelegatingVariableResolver (JSF 1.1/1.2) ........................................................ 519SpringBeanVariableResolver (JSF 1.1/1.2) ....................................................... 520SpringBeanFacesELResolver (JSF 1.2+) .......................................................... 520FacesContextUtils ........................................................................................... 521
18.4. Apache Struts 1.x and 2.x .............................................................................. 521ContextLoaderPlugin ...................................................................................... 521
DelegatingRequestProcessor .................................................................... 522DelegatingActionProxy ........................................................................... 523
ActionSupport Classes .................................................................................... 52318.5. WebWork 2.x ................................................................................................ 52418.6. Tapestry 3.x and 4.x ...................................................................................... 524
Injecting Spring-managed beans ...................................................................... 525Dependency Injecting Spring Beans into Tapestry pages ........................... 527Component definition files ...................................................................... 528Adding abstract accessors ....................................................................... 529Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.xstyle ....................................................................................................... 531
18.7. Further Resources .......................................................................................... 53219. Portlet MVC Framework ........................................................................................... 533
19.1. Introduction ................................................................................................... 533Controllers - The C in MVC ........................................................................... 534Views - The V in MVC .................................................................................. 534Web-scoped beans .......................................................................................... 534
19.2. The DispatcherPortlet ......................................................................... 53519.3. The ViewRendererServlet ..................................................................... 53719.4. Controllers ..................................................................................................... 538
AbstractController and PortletContentGenerator ..................... 538Other simple controllers .................................................................................. 540Command Controllers ..................................................................................... 540PortletWrappingController ............................................................... 541
19.5. Handler mappings .......................................................................................... 541PortletModeHandlerMapping ............................................................... 542ParameterHandlerMapping ................................................................... 542PortletModeParameterHandlerMapping ........................................... 543Adding HandlerInterceptors ................................................................. 543HandlerInterceptorAdapter ............................................................... 544
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xx
ParameterMappingInterceptor ........................................................... 54419.6. Views and resolving them .............................................................................. 54419.7. Multipart (file upload) support ........................................................................ 545
Using the PortletMultipartResolver .................................................. 545Handling a file upload in a form ..................................................................... 546
19.8. Handling exceptions ....................................................................................... 54919.9. Annotation-based controller configuration ....................................................... 549
Setting up the dispatcher for annotation support ............................................... 549Defining a controller with @Controller ...................................................... 550Mapping requests with @RequestMapping .................................................. 551Supported handler method arguments .............................................................. 552Binding request parameters to method parameters with @RequestParam ........ 553Providing a link to data from the model with @ModelAttribute ................... 554Specifying attributes to store in a Session with @SessionAttributes .......... 555Customizing WebDataBinder initialization .................................................. 555
Customizing data binding with @InitBinder ....................................... 555Configuring a custom WebBindingInitializer ............................... 556
19.10. Portlet application deployment ...................................................................... 556VI. Integration ........................................................................................................................ 557
20. Remoting and web services using Spring ................................................................... 55820.1. Introduction ................................................................................................... 55820.2. Exposing services using RMI ......................................................................... 559
Exporting the service using the RmiServiceExporter ................................ 559Linking in the service at the client .................................................................. 560
20.3. Using Hessian or Burlap to remotely call services via HTTP ............................. 560Wiring up the DispatcherServlet for Hessian and co. .............................. 561Exposing your beans by using the HessianServiceExporter ................... 561Linking in the service on the client ................................................................. 562Using Burlap .................................................................................................. 562Applying HTTP basic authentication to a service exposed through Hessian orBurlap ............................................................................................................ 562
20.4. Exposing services using HTTP invokers .......................................................... 563Exposing the service object ............................................................................. 563Linking in the service at the client .................................................................. 564
20.5. Web services ................................................................................................. 565Exposing servlet-based web services using JAX-RPC ....................................... 565Accessing web services using JAX-RPC .......................................................... 566Registering JAX-RPC Bean Mappings ............................................................. 568Registering your own JAX-RPC Handler ......................................................... 568Exposing servlet-based web services using JAX-WS ........................................ 569Exporting standalone web services using JAX-WS ........................................... 570Exporting web services using the JAX-WS RI's Spring support ......................... 571Accessing web services using JAX-WS ........................................................... 571
20.6. JMS .............................................................................................................. 572Server-side configuration ................................................................................ 573
-
Spring Framework
3.2.0.BUILD-SNAPSHOTSpring FrameworkReference Manual xxi
Client-side configuration ................................................................................. 57320.7. Auto-detection is not implemented for remote interfaces ................................... 57420.8. Considerations when choosing a technology .................................................... 57520.9. Accessing RESTful services on the Client ....................................................... 575
RestTemplate ................................................................................................. 576Working with the URI ............................................................................ 578Dealing with request and response headers ............................................... 579
HTTP Message Conversion ............................................................................. 579StringHttpMessageConverter ................................................................... 580FormHttpMessageConverter .................................................................... 580ByteArrayHttpMessageConverter ............................................................. 580MarshallingHttpMessageConverter .......................................................... 580MappingJackson2HttpMessageConverter (orMappingJacksonHttpMessageConverter with Jackson 1.x) ......................... 580SourceHttpMessageConverter .................................................................. 580BufferedImageHttpMessageConverter ...................................................... 580
21. Enterprise JavaBeans (EJB) integration ...................................................................... 58121.1. Introduction ................................................................................................... 58121.2. Accessing EJBs ............................................................................................. 581
Concepts ........................................................................................................ 581Accessing local SLSBs ................................................................................... 582Accessing remote SLSBs ................................................................................ 583Accessing EJB 2.x SLSBs versus EJB 3 SLSBs ............................................... 584
21.3. Using Spring's EJB implementation support classes .......................................... 584EJB 2.x base classes ................................................................