+ All Categories
Home > Documents > Spring Framework Reference

Spring Framework Reference

Date post: 03-Nov-2014
Category:
Upload: tania-ch
View: 129 times
Download: 5 times
Share this document with a friend
Popular Tags:
847
Spring Framework Reference Documentation 3.2.2.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-2012 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.
Transcript

Spring Framework Reference Documentation3.2.2.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-2012Copies 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

Table of ContentsI. 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

3.2.2.RELEASE

Spring Framework Reference Documentation

ii

Spring Framework

3.8. c: namespace for more concise constructor injection ............................................ 3.9. Support for injection against non-standard JavaBeans setters ............................... 3.10. Support for Servlet 3 code-based configuration of Servlet Container .................... 3.11. Support for Servlet 3 MultipartResolver ............................................................. 3.12. JPA EntityManagerFactory bootstrapping without persistence.xml ....................... 3.13. New HandlerMethod-based Support Classes For Annotated Controller Processing ............................................................................................................... 3.14. "consumes" and "produces" conditions in @RequestMapping ............................ 3.15. Flash Attributes and RedirectAttributes .................................................... 3.16. URI Template Variable Enhancements .............................................................. 3.17. @Valid On @RequestBody Controller Method Arguments ................................ 3.18. @RequestPart Annotation On Controller Method Arguments ............................. 3.19. UriComponentsBuilder and UriComponents .............................................. 4. New Features and Enhancements in Spring Framework 3.2 ............................................ 4.1. Support for Servlet 3 based asynchronous request processing .............................. 4.2. Spring MVC Test framework .............................................................................. 4.3. Content negotiation improvements ...................................................................... 4.4. @ControllerAdvice annotation ...................................................................... 4.5. Matrix variables ................................................................................................. 4.6. Abstract base class for code-based Servlet 3+ container initialization .................... 4.7. ResponseEntityExceptionHandler class ..................................................... 4.8. Support for generic types in the RestTemplate and in @RequestBody arguments ................................................................................................................ 4.9. Jackson JSON 2 and related improvements ........................................................ 4.10. Tiles 3 ............................................................................................................. 4.11. @RequestBody improvements ......................................................................... 4.12. HTTP PATCH method ...................................................................................... 4.13. Excluded patterns in mapped interceptors ......................................................... 4.14. Using meta-annotations for injection points and for bean definition methods ......... 4.15. Initial support for JCache 0.5 ............................................................................ 4.16. Support for @DateTimeFormat without Joda Time ........................................... 4.17. Global date & time formatting ........................................................................... 4.18. New Testing Features ...................................................................................... 4.19. Concurrency refinements across the framework ................................................. 4.20. New Gradle-based build and move to GitHub .................................................... 4.21. Refined Java SE 7 / OpenJDK 7 support .......................................................... III. Core Technologies .............................................................................................................. 5. The IoC container ........................................................................................................ 5.1. Introduction to the Spring IoC container and beans .............................................. 5.2. Container overview ............................................................................................ Configuration metadata ..................................................................................... Instantiating a container .................................................................................... Composing XML-based configuration metadata .......................................... Using the container .......................................................................................... 5.3. Bean overview ................................................................................................... Naming beans .................................................................................................. Aliasing a bean outside the bean definition ................................................ Instantiating beans ........................................................................................... Instantiation with a constructor .................................................................. Instantiation with a static factory method .................................................... Spring Framework Reference Documentation

25 25 26 26 26 26 27 27 27 28 28 28 29 29 29 29 29 30 30 30 30 30 31 31 31 31 31 31 31 31 32 32 32 32 33 34 34 34 35 36 37 38 39 40 40 41 41 42

3.2.2.RELEASE

iii

Spring Framework

Instantiation using an instance factory method ........................................... 5.4. Dependencies ................................................................................................... Dependency injection ....................................................................................... Constructor-based dependency injection .................................................... Setter-based dependency injection ............................................................ Dependency resolution process ................................................................. Examples of dependency injection ............................................................. Dependencies and configuration in detail ........................................................... Straight values (primitives, Strings, and so on) ....................................... References to other beans (collaborators) .................................................. Inner beans .............................................................................................. Collections ............................................................................................... Null and empty string values ..................................................................... XML shortcut with the p-namespace .......................................................... XML shortcut with the c-namespace .......................................................... Compound property names ....................................................................... Using depends-on .......................................................................................... Lazy-initialized beans ....................................................................................... Autowiring collaborators .................................................................................... Limitations and disadvantages of autowiring ............................................... Excluding a bean from autowiring .............................................................. Method injection ............................................................................................... Lookup method injection ........................................................................... Arbitrary method replacement ................................................................... 5.5. Bean scopes ..................................................................................................... The singleton scope ......................................................................................... The prototype scope ......................................................................................... Singleton beans with prototype-bean dependencies ............................................ Request, session, and global session scopes .................................................... Initial web configuration ............................................................................ Request scope ......................................................................................... Session scope .......................................................................................... Global session scope ............................................................................... Scoped beans as dependencies ................................................................ Custom scopes ................................................................................................ Creating a custom scope .......................................................................... Using a custom scope .............................................................................. 5.6. Customizing the nature of a bean ....................................................................... Lifecycle callbacks ............................................................................................ Initialization callbacks ............................................................................... Destruction callbacks ................................................................................ Default initialization and destroy methods .................................................. Combining lifecycle mechanisms ............................................................... Startup and shutdown callbacks ................................................................ Shutting down the Spring IoC container gracefully in non-web applications ................................................................................................................. ApplicationContextAware and BeanNameAware ........................................ Other Aware interfaces .................................................................................... 5.7. Bean definition inheritance ................................................................................. 5.8. Container Extension Points ................................................................................ Spring Framework Reference Documentation

42 44 44 44 46 47 48 50 50 52 53 53 56 56 58 58 59 59 60 61 61 62 63 64 65 66 67 68 68 69 69 70 70 70 72 72 73 74 74 75 75 76 77 78 80 80 81 82 84

3.2.2.RELEASE

iv

Spring Framework

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 Reference Documentation

3.2.2.RELEASE

v

Spring Framework

5.14. Additional Capabilities of the ApplicationContext ...................................... Internationalization using MessageSource ...................................................... Standard and Custom Events .......................................................................... Convenient access to low-level resources ........................................................ Convenient ApplicationContext instantiation for web applications ............... Deploying a Spring ApplicationContext as a J2EE RAR file ............................... 5.15. The BeanFactory ........................................................................................... BeanFactory or ApplicationContext? ..................................................... Glue code and the evil singleton ..................................................................... 6. Resources .................................................................................................................. 6.1. Introduction ..................................................................................................... 6.2. The Resource interface .................................................................................. 6.3. Built-in Resource implementations ................................................................... UrlResource ................................................................................................ ClassPathResource .................................................................................... FileSystemResource .................................................................................. ServletContextResource .......................................................................... InputStreamResource ................................................................................ ByteArrayResource .................................................................................... 6.4. The ResourceLoader .................................................................................... 6.5. The ResourceLoaderAware interface ............................................................. 6.6. Resources as dependencies ........................................................................... 6.7. Application contexts and Resource paths ........................................................ Constructing application contexts ..................................................................... Constructing ClassPathXmlApplicationContext instances shortcuts ................................................................................................ Wildcards in application context constructor resource paths ............................... Ant-style Patterns ................................................................................... The classpath*: prefix ........................................................................ Other notes relating to wildcards ............................................................. FileSystemResource caveats ..................................................................... 7. Validation, Data Binding, and Type Conversion ............................................................ 7.1. Introduction ..................................................................................................... 7.2. Validation using Spring's Validator interface .................................................. 7.3. Resolving codes to error messages .................................................................. 7.4. Bean manipulation and the BeanWrapper ........................................................ Setting and getting basic and nested properties ............................................... Built-in PropertyEditor implementations ..................................................... Registering additional custom PropertyEditors ................................... 7.5. Spring 3 Type Conversion ................................................................................ Converter SPI ................................................................................................ ConverterFactory ............................................................................................ GenericConverter ........................................................................................... ConditionalGenericConverter ................................................................... ConversionService API ................................................................................... Configuring a ConversionService ..................................................................... Using a ConversionService programmatically ................................................... 7.6. Spring 3 Field Formatting ................................................................................. Formatter SPI ................................................................................................. Annotation-driven Formatting ........................................................................... Spring Framework Reference Documentation

126 126 129 132 133 133 134 134 136 137 137 137 138 138 138 139 139 139 139 139 140 141 141 141 142 142 143 143 144 144 146 146 146 148 149 149 151 153 156 156 157 157 158 158 159 160 160 160 162

3.2.2.RELEASE

vi

Spring Framework

Format Annotation API ............................................................................ FormatterRegistry SPI ..................................................................................... FormatterRegistrar SPI ................................................................................... Configuring Formatting in Spring MVC ............................................................. 7.7. Configuring a global date & time format ............................................................ 7.8. Spring 3 Validation .......................................................................................... Overview of the JSR-303 Bean Validation API ................................................. Configuring a Bean Validation Implementation .................................................. Injecting a Validator ................................................................................ Configuring Custom Constraints .............................................................. Additional Configuration Options .............................................................. Configuring a DataBinder ................................................................................ Spring MVC 3 Validation ................................................................................. Triggering @Controller Input Validation .................................................... Configuring a Validator for use by Spring MVC ......................................... Configuring a JSR-303 Validator for use by Spring MVC ........................... 8. Spring Expression Language (SpEL) ........................................................................... 8.1. Introduction ..................................................................................................... 8.2. Feature Overview ............................................................................................ 8.3. Expression Evaluation using Spring's Expression Interface ................................. The EvaluationContext interface ...................................................................... Type Conversion .................................................................................... 8.4. Expression support for defining bean definitions ................................................ XML based configuration ................................................................................ Annotation-based configuration ........................................................................ 8.5. Language Reference ........................................................................................ Literal expressions .......................................................................................... Properties, Arrays, Lists, Maps, Indexers ......................................................... Inline lists ....................................................................................................... Array construction ........................................................................................... Methods ......................................................................................................... Operators ....................................................................................................... Relational operators ................................................................................ Logical operators .................................................................................... Mathematical operators ........................................................................... Assignment .................................................................................................... Types ............................................................................................................. Constructors ................................................................................................... Variables ........................................................................................................ The #this and #root variables .................................................................. Functions ....................................................................................................... Bean references ............................................................................................. Ternary Operator (If-Then-Else) ....................................................................... The Elvis Operator ......................................................................................... Safe Navigation operator ................................................................................ Collection Selection ........................................................................................ Collection Projection ....................................................................................... Expression templating ..................................................................................... 8.6. Classes used in the examples .......................................................................... 9. Aspect Oriented Programming with Spring ................................................................... Spring Framework Reference Documentation

163 164 164 164 166 168 168 169 169 169 170 170 171 171 171 172 173 173 173 174 176 176 177 177 178 179 179 180 181 181 181 182 182 182 183 184 184 185 185 185 186 186 187 187 188 188 189 189 190 194

3.2.2.RELEASE

vii

Spring Framework

9.1. Introduction ..................................................................................................... AOP concepts ................................................................................................ Spring AOP capabilities and goals ................................................................... AOP Proxies .................................................................................................. 9.2. @AspectJ support ........................................................................................... Enabling @AspectJ Support ............................................................................ Enabling @AspectJ Support with Java configuration ................................. Enabling @AspectJ Support with XML configuration ................................. Declaring an aspect ........................................................................................ Declaring a pointcut ........................................................................................ Supported Pointcut Designators .............................................................. Combining pointcut expressions .............................................................. Sharing common pointcut definitions ........................................................ Examples ............................................................................................... Writing good pointcuts ............................................................................ Declaring advice ............................................................................................. Before advice ......................................................................................... After returning advice .............................................................................. After throwing advice .............................................................................. After (finally) advice ................................................................................ Around advice ........................................................................................ Advice parameters .................................................................................. Advice ordering ...................................................................................... Introductions ................................................................................................... Aspect instantiation models ............................................................................. Example ......................................................................................................... 9.3. Schema-based AOP support ............................................................................ Declaring an aspect ........................................................................................ Declaring a pointcut ........................................................................................ Declaring advice ............................................................................................. Before advice ......................................................................................... After returning advice .............................................................................. After throwing advice .............................................................................. After (finally) advice ................................................................................ Around advice ........................................................................................ Advice parameters .................................................................................. Advice ordering ...................................................................................... Introductions ................................................................................................... Aspect instantiation models ............................................................................. Advisors ......................................................................................................... Example ......................................................................................................... 9.4. Choosing which AOP declaration style to use .................................................... Spring AOP or full AspectJ? ........................................................................... @AspectJ or XML for Spring AOP? ................................................................. 9.5. Mixing aspect types ......................................................................................... 9.6. Proxying mechanisms ...................................................................................... Understanding AOP proxies ............................................................................ 9.7. Programmatic creation of @AspectJ Proxies ..................................................... 9.8. Using AspectJ with Spring applications ............................................................. Using AspectJ to dependency inject domain objects with Spring ........................ Spring Framework Reference Documentation

194 194 196 197 197 197 197 198 198 199 199 201 201 203 205 206 206 206 207 208 208 209 213 213 214 214 216 216 217 218 218 219 220 220 221 221 223 224 224 224 225 227 227 228 229 229 230 232 233 233

3.2.2.RELEASE

viii

Spring Framework

Unit testing @Configurable objects ...................................................... Working with multiple application contexts ................................................ Other Spring aspects for AspectJ .................................................................... Configuring AspectJ aspects using Spring IoC ................................................. Load-time weaving with AspectJ in the Spring Framework ................................. A first example ....................................................................................... Aspects .................................................................................................. 'META-INF/aop.xml' ............................................................................. Required libraries (JARS) ........................................................................ Spring configuration ................................................................................ Environment-specific configuration ........................................................... 9.9. Further Resources ........................................................................................... 10. Spring AOP APIs ...................................................................................................... 10.1. Introduction .................................................................................................... 10.2. Pointcut API in Spring .................................................................................... Concepts ........................................................................................................ Operations on pointcuts .................................................................................. AspectJ expression pointcuts .......................................................................... Convenience pointcut implementations ............................................................ Static pointcuts ....................................................................................... Dynamic pointcuts .................................................................................. Pointcut superclasses ..................................................................................... Custom pointcuts ............................................................................................ 10.3. Advice API in Spring ...................................................................................... Advice lifecycles ............................................................................................. Advice types in Spring .................................................................................... Interception around advice ...................................................................... Before advice ......................................................................................... Throws advice ........................................................................................ After Returning advice ............................................................................ Introduction advice .................................................................................. 10.4. Advisor API in Spring ..................................................................................... 10.5. Using the ProxyFactoryBean to create AOP proxies ......................................... Basics ............................................................................................................ JavaBean properties ....................................................................................... JDK- and CGLIB-based proxies ...................................................................... Proxying interfaces ......................................................................................... Proxying classes ............................................................................................ Using 'global' advisors .................................................................................... 10.6. Concise proxy definitions ................................................................................ 10.7. Creating AOP proxies programmatically with the ProxyFactory .......................... 10.8. Manipulating advised objects .......................................................................... 10.9. Using the "auto-proxy" facility ......................................................................... Autoproxy bean definitions .............................................................................. BeanNameAutoProxyCreator ................................................................... DefaultAdvisorAutoProxyCreator .............................................................. AbstractAdvisorAutoProxyCreator ............................................................ Using metadata-driven auto-proxying ............................................................... 10.10. Using TargetSources .................................................................................... Hot swappable target sources ......................................................................... Spring Framework Reference Documentation

236 236 236 237 238 238 241 242 242 242 245 247 248 248 248 248 249 249 249 249 250 251 251 251 251 252 252 252 253 254 255 257 258 258 258 259 260 262 263 263 264 265 266 267 267 267 268 268 270 271

3.2.2.RELEASE

ix

Spring Framework

Pooling target sources .................................................................................... Prototype target sources ................................................................................. ThreadLocal target sources ......................................................................... 10.11. Defining new Advice types .......................................................................... 10.12. Further resources ......................................................................................... 11. Testing ..................................................................................................................... 11.1. Introduction to Spring Testing ......................................................................... 11.2. Unit Testing ................................................................................................... Mock Objects ................................................................................................. Environment ........................................................................................... JNDI ...................................................................................................... Servlet API ............................................................................................. Portlet API ............................................................................................. Unit Testing support Classes .......................................................................... General utilities ...................................................................................... Spring MVC ........................................................................................... 11.3. Integration Testing ......................................................................................... Overview ........................................................................................................ Goals of Integration Testing ............................................................................ Context management and caching ........................................................... Dependency Injection of test fixtures ....................................................... Transaction management ........................................................................ Support classes for integration testing ..................................................... JDBC Testing Support .................................................................................... Annotations .................................................................................................... Spring Testing Annotations ..................................................................... Standard Annotation Support .................................................................. Spring JUnit Testing Annotations ............................................................. Spring TestContext Framework ....................................................................... Key abstractions ..................................................................................... Context management .............................................................................. Dependency injection of test fixtures ........................................................ Testing request and session scoped beans .............................................. Transaction management ........................................................................ TestContext Framework support classes .................................................. Spring MVC Test Framework .......................................................................... Server-Side Tests ................................................................................... Client-Side REST Tests .......................................................................... PetClinic Example .......................................................................................... 11.4. Further Resources ......................................................................................... IV. Data Access ..................................................................................................................... 12. Transaction Management .......................................................................................... 12.1. Introduction to Spring Framework transaction management .............................. 12.2. Advantages of the Spring Framework's transaction support model ..................... Global transactions ......................................................................................... Local transactions ........................................................................................... Spring Framework's consistent programming model .......................................... 12.3. Understanding the Spring Framework transaction abstraction ............................ 12.4. Synchronizing resources with transactions ....................................................... High-level synchronization approach ................................................................ Spring Framework Reference Documentation

271 273 273 273 274 275 275 275 275 275 275 275 276 276 276 276 276 276 277 277 278 278 279 279 279 279 285 285 287 287 289 302 305 307 309 311 311 317 317 319 320 321 321 321 321 322 322 323 326 327

3.2.2.RELEASE

x

Spring Framework

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 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 Reference Documentation

3.2.2.RELEASE

xi

Spring Framework

DataSource .................................................................................................. DataSourceUtils ........................................................................................ SmartDataSource ........................................................................................ AbstractDataSource .................................................................................. SingleConnectionDataSource .................................................................. DriverManagerDataSource ........................................................................ TransactionAwareDataSourceProxy ........................................................ DataSourceTransactionManager .............................................................. NativeJdbcExtractor ........................................................................................ 14.4. JDBC batch operations .................................................................................. Basic batch operations with the JdbcTemplate ................................................. Batch operations with a List of objects ............................................................. Batch operations with multiple batches ............................................................ 14.5. Simplifying JDBC operations with the SimpleJdbc classes ................................ Inserting data using SimpleJdbcInsert .............................................................. Retrieving auto-generated keys using SimpleJdbcInsert .................................... Specifying columns for a SimpleJdbcInsert ...................................................... Using SqlParameterSource to provide parameter values ................................... Calling a stored procedure with SimpleJdbcCall ............................................... Explicitly declaring parameters to use for a SimpleJdbcCall ............................... How to define SqlParameters .......................................................................... Calling a stored function using SimpleJdbcCall ................................................. Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................... 14.6. Modeling JDBC operations as Java objects ..................................................... SqlQuery ...................................................................................................... MappingSqlQuery ........................................................................................ SqlUpdate .................................................................................................... StoredProcedure ........................................................................................ 14.7. Common problems with parameter and data value handling .............................. Providing SQL type information for parameters ................................................. Handling BLOB and CLOB objects .................................................................. Passing in lists of values for IN clause ............................................................ Handling complex types for stored procedure calls ........................................... 14.8. Embedded database support .......................................................................... Why use an embedded database? .................................................................. Creating an embedded database instance using Spring XML ............................ Creating an embedded database instance programmatically .............................. Extending the embedded database support ...................................................... Using HSQL ................................................................................................... Using H2 ........................................................................................................ Using Derby ................................................................................................... Testing data access logic with an embedded database ..................................... 14.9. Initializing a DataSource ................................................................................. Initializing a database instance using Spring XML ............................................. Initialization of Other Components that Depend on the Database ............... 15. Object Relational Mapping (ORM) Data Access .......................................................... 15.1. Introduction to ORM with Spring ..................................................................... 15.2. General ORM integration considerations ......................................................... Resource and transaction management ........................................................... Exception translation ....................................................................................... Spring Framework Reference Documentation

370 372 372 372 372 372 373 373 373 374 374 375 376 377 377 378 379 379 380 382 383 384 384 385 386 386 387 387 391 392 392 393 394 395 395 395 396 396 396 396 396 396 397 397 398 400 400 401 401 401

3.2.2.RELEASE

xii

Spring Framework

15.3. Hibernate ....................................................................................................... SessionFactory setup in a Spring container ................................................. Implementing DAOs based on plain Hibernate 3 API ........................................ Declarative transaction demarcation ................................................................ Programmatic transaction demarcation ............................................................ Transaction management strategies ................................................................ Comparing container-managed and locally defined resources ............................ Spurious application server warnings with Hibernate ......................................... 15.4. JDO .............................................................................................................. PersistenceManagerFactory setup ........................................................... Implementing DAOs based on the plain JDO API ............................................. Transaction management ................................................................................ JdoDialect .................................................................................................. 15.5. JPA ............................................................................................................... Three options for JPA setup in a Spring environment ........................................ LocalEntityManagerFactoryBean .................................................... Obtaining an EntityManagerFactory from JNDI .................................. LocalContainerEntityManagerFactoryBean .................................. Dealing with multiple persistence units ..................................................... Implementing DAOs based on plain JPA .......................................................... Transaction Management ................................................................................ JpaDialect .................................................................................................. 15.6. iBATIS SQL Maps ......................................................................................... Setting up the SqlMapClient ........................................................................ Using SqlMapClientTemplate and SqlMapClientDaoSupport ................. Implementing DAOs based on plain iBATIS API ............................................... 16. Marshalling XML using O/X Mappers ......................................................................... 16.1. Introduction .................................................................................................... 16.2. Marshaller and Unmarshaller .......................................................................... Marshaller ...................................................................................................... Unmarshaller .................................................................................................. XmlMappingException ..................................................................................... 16.3. Using Marshaller and Unmarshaller ................................................................. 16.4. XML Schema-based Configuration .................................................................. 16.5. JAXB ............................................................................................................. Jaxb2Marshaller ............................................................................................. XML Schema-based Configuration ........................................................... 16.6. Castor ........................................................................................................... CastorMarshaller ............................................................................................ Mapping ......................................................................................................... XML Schema-based Configuration ........................................................... 16.7. XMLBeans ..................................................................................................... XmlBeansMarshaller ....................................................................................... XML Schema-based Configuration ........................................................... 16.8. JiBX .............................................................................................................. JibxMarshaller ................................................................................................ XML Schema-based Configuration ........................................................... 16.9. XStream ........................................................................................................ XStreamMarshaller ......................................................................................... V. The Web ........................................................................................................................... Spring Framework Reference Documentation

402 402 403 405 407 408 410 411 412 412 413 415 416 417 417 417 418 418 420 421 423 424 425 425 426 427 429 429 429 429 430 431 431 433 433 434 434 435 435 435 435 436 436 436 437 437 437 438 438 439

3.2.2.RELEASE

xiii

Spring Framework

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 Reference Documentation

3.2.2.RELEASE

xiv

Spring Framework

Chaining ViewResolvers ................................................................................. Redirecting to views ....................................................................................... RedirectView ...................................................................................... The redirect: prefix ............................................................................ The forward: prefix ............................................................................. ContentNegotiatingViewResolver .......................................................... 17.6. Using flash attributes ..................................................................................... 17.7. Building URIs ................................................................................................ 17.8. Using locales ................................................................................................. AcceptHeaderLocaleResolver .................................................................. CookieLocaleResolver .............................................................................. SessionLocaleResolver ............................................................................ LocaleChangeInterceptor ........................................................................ 17.9. Using themes ................................................................................................ Overview of themes ........................................................................................ Defining themes ............................................................................................. Theme resolvers ............................................................................................. 17.10. Spring's multipart (file upload) support ........................................................... Introduction .................................................................................................... Using a MultipartResolver with Commons FileUpload ................................ Using a MultipartResolver with Servlet 3.0 ............................................... Handling a file upload in a form ...................................................................... Handling a file upload request from programmatic clients .................................. 17.11. Handling exceptions ..................................................................................... HandlerExceptionResolver ...................................................................... @ExceptionHandler .................................................................................... Handling Standard Spring MVC Exceptions ...................................................... Annotating Business Exceptions With @ResponseStatus ................................ Customizing the Default Servlet Container Error Page ...................................... 17.12. Convention over configuration support ........................................................... The Controller ControllerClassNameHandlerMapping .............................. The Model ModelMap (ModelAndView) .......................................................... The View - RequestToViewNameTranslator ............................................... 17.13. ETag support ............................................................................................... 17.14. Code-based Servlet container initialization ..................................................... 17.15. Configuring Spring MVC ............................................................................... Enabling the MVC Java Config or the MVC XML Namespace ............................ Customizing the Provided Configuration ........................................................... Configuring Interceptors .................................................................................. Configuring Content Negotiation ...................................................................... Configuring View Controllers ........................................................................... Configuring Serving of Resources ................................................................... mvc:default-servlet-handler .............................................................................. More Spring Web MVC Resources .................................................................. Advanced Customizations with MVC Java Config ............................................. Advanced Customizations with the MVC Namespace ........................................ 18. View technologies ..................................................................................................... 18.1. Introduction .................................................................................................... 18.2. JSP & JSTL .................................................................................................. View resolvers ................................................................................................ Spring Framework Reference Documentation

478 478 479 479 480 480 482 483 484 484 484 485 485 486 486 486 486 487 487 487 488 488 489 490 490 491 492 492 493 493 494 495 496 497 498 500 500 501 502 503 504 504 507 508 508 509 510 510 510 510

3.2.2.RELEASE

xv

Spring Framework

'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 Reference Documentation

3.2.2.RELEASE

xvi

Spring Framework

Controller code ....................................................................................... Subclassing for Excel views .................................................................... Subclassing for PDF views ..................................................................... 18.7. JasperReports ............................................................................................... Dependencies ................................................................................................ Configuration .................................................................................................. Configuring the ViewResolver .............................................................. Configuring the Views ............................................................................ About Report Files .................................................................................. Using JasperReportsMultiFormatView ............................................. Populating the ModelAndView ....................................................................... Working with Sub-Reports ............................................................................... Configuring Sub-Report Files .................................................................. Configuring Sub-Report Data Sources ..................................................... Configuring Exporter Parameters ..................................................................... 18.8. Feed Views ................................................................................................... 18.9. XML Marshalling View .................................................................................... 18.10. JSON Mapping View .................................................................................... 19. Integrating with other web frameworks ....................................................................... 19.1. Introduction .................................................................................................... 19.2. Common configuration ................................................................................... 19.3. JavaServer Faces 1.1 and 1.2 ........................................................................ DelegatingVariableResolver (JSF 1.1/1.2) ........................................................ SpringBeanVariableResolver (JSF 1.1/1.2) ....................................................... SpringBeanFacesELResolver (JSF 1.2+) ......................................................... FacesContextUtils ........................................................................................... 19.4. Apache Struts 1.x and 2.x .............................................................................. ContextLoaderPlugin ....................................................................................... DelegatingRequestProcessor ................................................................... DelegatingActionProxy ............................................................................ ActionSupport Classes .................................................................................... 19.5. WebWork 2.x ................................................................................................. 19.6. Tapestry 3.x and 4.x ...................................................................................... Injecting Spring-managed beans ..................................................................... Dependency Injecting Spring Beans into Tapestry pages ........................... Component definition files ....................................................................... Adding abstract accessors ...................................................................... Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style ....................................................................................................... 19.7. Further Resources ......................................................................................... 20. Portlet MVC Framework ............................................................................................ 20.1. Introduction .................................................................................................... Controllers - The C in MVC ............................................................................ Views - The V in MVC .................................................................................... Web-scoped beans ......................................................................................... 20.2. The DispatcherPortlet ............................................................................ 20.3. The ViewRendererServlet ........................................................................ 20.4. Controllers ..................................................................................................... AbstractController and PortletContentGenerator ............................. Other simple controllers .................................................................................. Spring Framework Reference Documentation

537 537 539 540 540 540 540 540 541 541 542 543 543 544 544 544 545 546 547 547 548 549 549 550 550 550 551 551 552 552 553 553 554 555 557 558 559 561 562 563 563 564 564 564 564 566 567 568 569

3.2.2.RELEASE

xvii

Spring Framework

Command Controllers ..................................................................................... PortletWrappingController .................................................................... 20.5. Handler mappings .......................................................................................... PortletModeHandlerMapping .................................................................... ParameterHandlerMapping ........................................................................ PortletModeParameterHandlerMapping .................................................. Adding HandlerInterceptors ..................................................................... HandlerInterceptorAdapter .................................................................... ParameterMappingInterceptor ................................................................ 20.6. Views and resolving them .............................................................................. 20.7. Multipart (file upload) support ......................................................................... Using the PortletMultipartResolver ....................................................... Handling a file upload in a form ...................................................................... 20.8. Handling exceptions ....................................................................................... 20.9. Annotation-based controller configuration ........................................................ Setting up the dispatcher for annotation support ............................................... Defining a controller with @Controller .......................................................... Mapping requests with @RequestMapping ..................................................... Supported handler method arguments ............................................................. Binding request parameters to method parameters with @RequestParam .......... Providing a link to data from the model with @ModelAttribute ....................... Specifying attributes to store in a Session with @SessionAttributes ............. Customizing WebDataBinder initialization ...................................................... Customizing data binding with @InitBinder .......................................... Configuring a custom WebBindingInitializer ................................... 20.10. Portlet application deployment ...................................................................... VI. Integration ......................................................................................................................... 21. Remoting and web services using Spring ................................................................... 21.1. Introduction .................................................................................................... 21.2. Exposing services using RMI .......................................................................... Exporting the service using the RmiServiceExporter ................................... Linking in the service at the client ................................................................... 21.3. Using Hessian or Burlap to remotely call services via HTTP .............................. Wiring up the DispatcherServlet for Hessian and co. ................................. Exposing your beans by using the


Recommended