Spring Framework Reference Documentation · 4.1.8.RELEASE Rod Johnson , Juergen Hoeller , Keith...

843
Spring Framework Reference Documentation 4.1.8.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 , Rob Winch , Brian Clozel , Stephane Nicoll , Sebastien Deleuze

Transcript of Spring Framework Reference Documentation · 4.1.8.RELEASE Rod Johnson , Juergen Hoeller , Keith...

  • Spring Framework Reference Documentation

    4.1.8.RELEASE

    Rod Johnson , Juergen Hoeller , Keith Donald , Colin Sampaleanu , Rob Harrop , Thomas Risberg , AlefArendsen , Darren Davison , Dmitriy Kopylenko , Mark Pollack , Thierry Templier , Erwin Vervaet , Portia

    Tung , Ben Hale , Adrian Colyer , John Lewis , Costin Leau , Mark Fisher , Sam Brannen , RamnivasLaddad , Arjen Poutsma , Chris Beams , Tareq Abedrabbo , Andy Clement , Dave Syer , Oliver Gierke ,

    Rossen Stoyanchev , Phillip Webb , Rob Winch , Brian Clozel , Stephane Nicoll , Sebastien Deleuze

  • Copyright © 2004-2014

    Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any feefor such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework iii

    Table of Contents

    I. Overview of Spring Framework ................................................................................................ 11. Getting Started with Spring ............................................................................................. 22. Introduction to the Spring Framework .............................................................................. 3

    2.1. Dependency Injection and Inversion of Control ...................................................... 32.2. Modules .............................................................................................................. 3

    Core Container .................................................................................................. 4AOP and Instrumentation ................................................................................... 5Messaging ......................................................................................................... 5Data Access/Integration ...................................................................................... 5Web .................................................................................................................. 5Test ................................................................................................................... 6

    2.3. Usage scenarios ................................................................................................. 6Dependency Management and Naming Conventions ............................................ 9

    Spring Dependencies and Depending on Spring ......................................... 11Maven Dependency Management ............................................................. 11Maven "Bill Of Materials" Dependency ....................................................... 12Gradle Dependency Management ............................................................. 12Ivy Dependency Management ................................................................... 13Distribution Zip Files ................................................................................. 13

    Logging ............................................................................................................ 13Not Using Commons Logging ................................................................... 14Using SLF4J ............................................................................................ 14Using Log4J ............................................................................................. 15

    II. What’s New in Spring Framework 4.x .................................................................................... 173. New Features and Enhancements in Spring Framework 4.0 ............................................ 18

    3.1. Improved Getting Started Experience .................................................................. 183.2. Removed Deprecated Packages and Methods .................................................... 183.3. Java 8 (as well as 6 and 7) ............................................................................... 183.4. Java EE 6 and 7 ............................................................................................... 193.5. Groovy Bean Definition DSL .............................................................................. 193.6. Core Container Improvements ............................................................................ 193.7. General Web Improvements ............................................................................... 203.8. WebSocket, SockJS, and STOMP Messaging ..................................................... 203.9. Testing Improvements ........................................................................................ 21

    4. New Features and Enhancements in Spring Framework 4.1 ............................................ 224.1. JMS Improvements ............................................................................................ 224.2. Caching Improvements ...................................................................................... 224.3. Web Improvements ............................................................................................ 234.4. WebSocket STOMP Messaging Improvements .................................................... 244.5. Testing Improvements ........................................................................................ 24

    III. Core Technologies .............................................................................................................. 265. The IoC container ........................................................................................................ 27

    5.1. Introduction to the Spring IoC container and beans .............................................. 275.2. Container overview ............................................................................................ 27

    Configuration metadata ..................................................................................... 28Instantiating a container .................................................................................... 29

    Composing XML-based configuration metadata .......................................... 30

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework iv

    Using the container .......................................................................................... 315.3. Bean overview ................................................................................................... 31

    Naming beans .................................................................................................. 32Aliasing a bean outside the bean definition ................................................ 33

    Instantiating beans ........................................................................................... 34Instantiation with a constructor .................................................................. 34Instantiation with a static factory method .................................................... 35Instantiation using an instance factory method ........................................... 35

    5.4. Dependencies ................................................................................................... 36Dependency injection ....................................................................................... 36

    Constructor-based dependency injection .................................................... 37Setter-based dependency injection ............................................................ 39Dependency resolution process ................................................................. 40Examples of dependency injection ............................................................. 41

    Dependencies and configuration in detail ........................................................... 43Straight values (primitives, Strings, and so on) ........................................... 43References to other beans (collaborators) .................................................. 44Inner beans .............................................................................................. 45Collections ............................................................................................... 45Null and empty string values ..................................................................... 48XML shortcut with the p-namespace .......................................................... 48XML shortcut with the c-namespace .......................................................... 49Compound property names ....................................................................... 50

    Using depends-on ............................................................................................ 51Lazy-initialized beans ....................................................................................... 51Autowiring collaborators .................................................................................... 52

    Limitations and disadvantages of autowiring ............................................... 53Excluding a bean from autowiring .............................................................. 53

    Method injection ............................................................................................... 54Lookup method injection ........................................................................... 55Arbitrary method replacement ................................................................... 56

    5.5. Bean scopes ..................................................................................................... 57The singleton scope ......................................................................................... 58The prototype scope ......................................................................................... 59Singleton beans with prototype-bean dependencies ............................................ 60Request, session, and global session scopes .................................................... 60

    Initial web configuration ............................................................................ 61Request scope ......................................................................................... 61Session scope .......................................................................................... 62Global session scope ............................................................................... 62Application scope ..................................................................................... 62Scoped beans as dependencies ................................................................ 62

    Custom scopes ................................................................................................ 64Creating a custom scope .......................................................................... 64Using a custom scope .............................................................................. 65

    5.6. Customizing the nature of a bean ....................................................................... 66Lifecycle callbacks ............................................................................................ 66

    Initialization callbacks ............................................................................... 67Destruction callbacks ................................................................................ 67Default initialization and destroy methods .................................................. 68

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework v

    Combining lifecycle mechanisms ............................................................... 69Startup and shutdown callbacks ................................................................ 70Shutting down the Spring IoC container gracefully in non-web applications................................................................................................................. 72

    ApplicationContextAware and BeanNameAware ................................................. 72Other Aware interfaces ..................................................................................... 73

    5.7. Bean definition inheritance ................................................................................. 745.8. Container Extension Points ................................................................................ 76

    Customizing beans using a BeanPostProcessor ................................................. 76Example: Hello World, BeanPostProcessor-style ........................................ 77Example: The RequiredAnnotationBeanPostProcessor ............................... 79

    Customizing configuration metadata with a BeanFactoryPostProcessor ................ 79Example: the Class name substitution PropertyPlaceholderConfigurer .......... 80Example: the PropertyOverrideConfigurer .................................................. 81

    Customizing instantiation logic with a FactoryBean ............................................. 825.9. Annotation-based container configuration ............................................................ 82

    @Required ....................................................................................................... 84@Autowired ..................................................................................................... 84Fine-tuning annotation-based autowiring with qualifiers ....................................... 87Using generics as autowiring qualifiers .............................................................. 92CustomAutowireConfigurer ................................................................................ 92@Resource ...................................................................................................... 93@PostConstruct and @PreDestroy .................................................................... 94

    5.10. Classpath scanning and managed components ................................................. 94@Component and further stereotype annotations ............................................... 95Meta-annotations .............................................................................................. 95Automatically detecting classes and registering bean definitions .......................... 96Using filters to customize scanning ................................................................... 97Defining bean metadata within components ....................................................... 98Naming autodetected components ................................................................... 100Providing a scope for autodetected components ............................................... 100Providing qualifier metadata with annotations ................................................... 101

    5.11. Using JSR 330 Standard Annotations ............................................................. 102Dependency Injection with @Inject and @Named ............................................. 102@Named: a standard equivalent to the @Component annotation ....................... 103Limitations of the standard approach ............................................................... 104

    5.12. Java-based container configuration ................................................................. 104Basic concepts: @Bean and @Configuration ................................................... 104Instantiating the Spring container using AnnotationConfigApplicationContext ....... 105

    Simple construction ................................................................................ 105Building the container programmatically using register(Class…) ........... 106Enabling component scanning with scan(String…) .................................... 106Support for web applications with AnnotationConfigWebApplicationContext............................................................................................................... 107

    Using the @Bean annotation .......................................................................... 108Declaring a bean .................................................................................... 108Receiving lifecycle callbacks ................................................................... 109Specifying bean scope ............................................................................ 110Customizing bean naming ....................................................................... 111Bean aliasing ......................................................................................... 111

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework vi

    Bean description ..................................................................................... 111Using the @Configuration annotation ............................................................... 112

    Injecting inter-bean dependencies ............................................................ 112Lookup method injection ......................................................................... 112Further information about how Java-based configuration works internally .... 113

    Composing Java-based configurations ............................................................. 114Using the @Import annotation ................................................................. 114Conditionally including @Configuration classes or @Beans ....................... 117Combining Java and XML configuration ................................................... 117

    5.13. Environment abstraction ................................................................................. 119Bean definition profiles ................................................................................... 120

    @Profile ................................................................................................. 121XML Bean definition profiles ............................................................................ 122

    Enabling a profile ................................................................................... 123Default profile ......................................................................................... 123

    PropertySource Abstraction ............................................................................. 123@PropertySource ........................................................................................... 124Placeholder resolution in statements ................................................................ 125

    5.14. Registering a LoadTimeWeaver ...................................................................... 1255.15. Additional Capabilities of the ApplicationContext .............................................. 126

    Internationalization using MessageSource ........................................................ 126Standard and Custom Events .......................................................................... 129Convenient access to low-level resources ........................................................ 132Convenient ApplicationContext instantiation for web applications ....................... 133Deploying a Spring ApplicationContext as a Java EE RAR file ........................... 133

    5.16. The BeanFactory ........................................................................................... 134BeanFactory or ApplicationContext? ................................................................ 134Glue code and the evil singleton ..................................................................... 135

    6. Resources .................................................................................................................. 1376.1. Introduction ..................................................................................................... 1376.2. The Resource interface .................................................................................... 1376.3. Built-in Resource implementations .................................................................... 138

    UrlResource ................................................................................................... 138ClassPathResource ........................................................................................ 138FileSystemResource ....................................................................................... 139ServletContextResource .................................................................................. 139InputStreamResource ..................................................................................... 139ByteArrayResource ......................................................................................... 139

    6.4. The ResourceLoader ....................................................................................... 1396.5. The ResourceLoaderAware interface ................................................................ 1406.6. Resources as dependencies ............................................................................. 1416.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 ................................................................................... 143The Classpath*: portability classpath*: prefix ............................................ 143Other notes relating to wildcards ............................................................. 144

    FileSystemResource caveats .......................................................................... 1447. Validation, Data Binding, and Type Conversion ............................................................ 146

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework vii

    7.1. Introduction ..................................................................................................... 1467.2. Validation using Spring’s Validator interface ...................................................... 1467.3. Resolving codes to error messages .................................................................. 1487.4. Bean manipulation and the BeanWrapper ......................................................... 149

    Setting and getting basic and nested properties ............................................... 149Built-in PropertyEditor implementations ............................................................ 151

    Registering additional custom PropertyEditors .......................................... 1547.5. Spring Type Conversion ................................................................................... 156

    Converter SPI ................................................................................................ 156ConverterFactory ............................................................................................ 157GenericConverter ........................................................................................... 157

    ConditionalGenericConverter ................................................................... 158ConversionService API ................................................................................... 158Configuring a ConversionService ..................................................................... 159Using a ConversionService programmatically ................................................... 160

    7.6. Spring Field Formatting .................................................................................... 160Formatter SPI ................................................................................................. 161Annotation-driven Formatting ........................................................................... 162

    Format Annotation API ............................................................................ 163FormatterRegistry SPI ..................................................................................... 163FormatterRegistrar SPI ................................................................................... 164Configuring Formatting in Spring MVC ............................................................. 164

    7.7. Configuring a global date & time format ............................................................ 1667.8. Spring Validation ............................................................................................. 167

    Overview of the JSR-303 Bean Validation API ................................................. 167Configuring a Bean Validation Provider ............................................................ 168

    Injecting a Validator ................................................................................ 168Configuring Custom Constraints .............................................................. 169Spring-driven Method Validation .............................................................. 169Additional Configuration Options .............................................................. 170

    Configuring a DataBinder ................................................................................ 170Spring MVC 3 Validation ................................................................................. 170

    Triggering @Controller Input Validation .................................................... 170Configuring a Validator for use by Spring MVC ......................................... 171Configuring a JSR-303/JSR-349 Validator for use by Spring MVC .............. 171

    8. Spring Expression Language (SpEL) ........................................................................... 1738.1. Introduction ..................................................................................................... 1738.2. Feature Overview ............................................................................................ 1738.3. Expression Evaluation using Spring’s Expression Interface ................................. 174

    The EvaluationContext interface ...................................................................... 176Type Conversion .................................................................................... 176

    Parser configuration ........................................................................................ 177SpEL compilation ............................................................................................ 177

    Compiler configuration ............................................................................ 178Compiler limitations ................................................................................ 179

    8.4. Expression support for defining bean definitions ................................................ 179XML based configuration ................................................................................ 179Annotation-based configuration ........................................................................ 180

    8.5. Language Reference ........................................................................................ 181Literal expressions .......................................................................................... 181

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework viii

    Properties, Arrays, Lists, Maps, Indexers ......................................................... 181Inline lists ....................................................................................................... 182Inline Maps .................................................................................................... 182Array construction ........................................................................................... 183Methods ......................................................................................................... 183Operators ....................................................................................................... 183

    Relational operators ................................................................................ 183Logical operators .................................................................................... 184Mathematical operators ........................................................................... 184

    Assignment .................................................................................................... 185Types ............................................................................................................. 185Constructors ................................................................................................... 185Variables ........................................................................................................ 185

    The #this and #root variables .................................................................. 186Functions ....................................................................................................... 186Bean references ............................................................................................. 186Ternary Operator (If-Then-Else) ....................................................................... 187The Elvis Operator ......................................................................................... 187Safe Navigation operator ................................................................................ 187Collection Selection ........................................................................................ 188Collection Projection ....................................................................................... 188Expression templating ..................................................................................... 189

    8.6. Classes used in the examples .......................................................................... 1899. Aspect Oriented Programming with Spring ................................................................... 193

    9.1. Introduction ..................................................................................................... 193AOP concepts ................................................................................................ 193Spring AOP capabilities and goals ................................................................... 195AOP Proxies .................................................................................................. 196

    9.2. @AspectJ support ........................................................................................... 196Enabling @AspectJ Support ............................................................................ 196

    Enabling @AspectJ Support with Java configuration ................................. 196Enabling @AspectJ Support with XML configuration ................................. 197

    Declaring an aspect ........................................................................................ 197Declaring a pointcut ........................................................................................ 198

    Supported Pointcut Designators .............................................................. 198Combining pointcut expressions .............................................................. 200Sharing common pointcut definitions ........................................................ 200Examples ............................................................................................... 202Writing good pointcuts ............................................................................ 204

    Declaring advice ............................................................................................. 205Before advice ......................................................................................... 205After returning advice .............................................................................. 205After throwing advice .............................................................................. 206After (finally) advice ................................................................................ 207Around advice ........................................................................................ 207Advice parameters .................................................................................. 208Advice ordering ...................................................................................... 211

    Introductions ................................................................................................... 212Aspect instantiation models ............................................................................. 212Example ......................................................................................................... 213

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework ix

    9.3. Schema-based AOP support ............................................................................ 215Declaring an aspect ........................................................................................ 215Declaring a pointcut ........................................................................................ 216Declaring advice ............................................................................................. 217

    Before advice ......................................................................................... 217After returning advice .............................................................................. 218After throwing advice .............................................................................. 218After (finally) advice ................................................................................ 219Around advice ........................................................................................ 219Advice parameters .................................................................................. 220Advice ordering ...................................................................................... 221

    Introductions ................................................................................................... 222Aspect instantiation models ............................................................................. 222Advisors ......................................................................................................... 222Example ......................................................................................................... 223

    9.4. Choosing which AOP declaration style to use .................................................... 225Spring AOP or full AspectJ? ........................................................................... 225@AspectJ or XML for Spring AOP? ................................................................. 226

    9.5. Mixing aspect types ......................................................................................... 2269.6. Proxying mechanisms ...................................................................................... 227

    Understanding AOP proxies ............................................................................ 2279.7. Programmatic creation of @AspectJ Proxies ..................................................... 2309.8. Using AspectJ with Spring applications ............................................................. 230

    Using AspectJ to dependency inject domain objects with Spring ........................ 230Unit testing @Configurable objects .......................................................... 233Working with multiple application contexts ................................................ 233

    Other Spring aspects for AspectJ .................................................................... 233Configuring AspectJ aspects using Spring IoC ................................................. 234Load-time weaving with AspectJ in the Spring Framework ................................. 235

    A first example ....................................................................................... 235Aspects .................................................................................................. 238META-INF/aop.xml ................................................................................. 238Required libraries (JARS) ........................................................................ 239Spring configuration ................................................................................ 239Environment-specific configuration ........................................................... 241

    9.9. Further Resources ........................................................................................... 24310. Spring AOP APIs ...................................................................................................... 244

    10.1. Introduction .................................................................................................... 24410.2. Pointcut API in Spring .................................................................................... 244

    Concepts ........................................................................................................ 244Operations on pointcuts .................................................................................. 245AspectJ expression pointcuts .......................................................................... 245Convenience pointcut implementations ............................................................ 245

    Static pointcuts ....................................................................................... 245Dynamic pointcuts .................................................................................. 246

    Pointcut superclasses ..................................................................................... 247Custom pointcuts ............................................................................................ 247

    10.3. Advice API in Spring ...................................................................................... 247Advice lifecycles ............................................................................................. 247Advice types in Spring .................................................................................... 247

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework x

    Interception around advice ...................................................................... 247Before advice ......................................................................................... 248Throws advice ........................................................................................ 249After Returning advice ............................................................................ 250Introduction advice .................................................................................. 251

    10.4. Advisor API in Spring ..................................................................................... 25310.5. Using the ProxyFactoryBean to create AOP proxies ......................................... 253

    Basics ............................................................................................................ 253JavaBean properties ....................................................................................... 254JDK- and CGLIB-based proxies ...................................................................... 255Proxying interfaces ......................................................................................... 255Proxying classes ............................................................................................ 257Using global advisors ...................................................................................... 258

    10.6. Concise proxy definitions ................................................................................ 25810.7. Creating AOP proxies programmatically with the ProxyFactory .......................... 25910.8. Manipulating advised objects .......................................................................... 26010.9. Using the "auto-proxy" facility ......................................................................... 261

    Autoproxy bean definitions .............................................................................. 261BeanNameAutoProxyCreator ................................................................... 261DefaultAdvisorAutoProxyCreator .............................................................. 262AbstractAdvisorAutoProxyCreator ............................................................ 263

    Using metadata-driven auto-proxying ............................................................... 26310.10. Using TargetSources .................................................................................... 265

    Hot swappable target sources ......................................................................... 265Pooling target sources .................................................................................... 265Prototype target sources ................................................................................. 267ThreadLocal target sources ............................................................................. 267

    10.11. Defining new Advice types ............................................................................ 26710.12. Further resources ......................................................................................... 268

    11. Testing ..................................................................................................................... 26911.1. Introduction to Spring Testing ......................................................................... 26911.2. Unit Testing ................................................................................................... 269

    Mock Objects ................................................................................................. 269Environment ........................................................................................... 269JNDI ...................................................................................................... 269Servlet API ............................................................................................. 269Portlet API ............................................................................................. 269

    Unit Testing support Classes .......................................................................... 270General utilities ...................................................................................... 270Spring MVC ........................................................................................... 270

    11.3. Integration Testing ......................................................................................... 270Overview ........................................................................................................ 270Goals of Integration Testing ............................................................................ 271

    Context management and caching ........................................................... 271Dependency Injection of test fixtures ....................................................... 271Transaction management ........................................................................ 272Support classes for integration testing ..................................................... 272

    JDBC Testing Support .................................................................................... 273Annotations .................................................................................................... 273

    Spring Testing Annotations ..................................................................... 273

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework xi

    Standard Annotation Support .................................................................. 279Spring JUnit Testing Annotations ............................................................. 280Meta-Annotation Support for Testing ........................................................ 281

    Spring TestContext Framework ....................................................................... 282Key abstractions ..................................................................................... 283TestExecutionListener configuration ......................................................... 284Context management .............................................................................. 286Dependency injection of test fixtures ........................................................ 305Testing request and session scoped beans .............................................. 307Transaction management ........................................................................ 309Executing SQL scripts ............................................................................ 313TestContext Framework support classes .................................................. 317

    Spring MVC Test Framework .......................................................................... 319Server-Side Tests ................................................................................... 320Client-Side REST Tests .......................................................................... 325

    PetClinic Example .......................................................................................... 32511.4. Further Resources ......................................................................................... 327

    IV. Data Access ..................................................................................................................... 32812. Transaction Management .......................................................................................... 329

    12.1. Introduction to Spring Framework transaction management .............................. 32912.2. Advantages of the Spring Framework’s transaction support model ..................... 329

    Global transactions ......................................................................................... 329Local transactions ........................................................................................... 330Spring Framework’s consistent programming model ......................................... 330

    12.3. Understanding the Spring Framework transaction abstraction ............................ 33112.4. Synchronizing resources with transactions ....................................................... 334

    High-level synchronization approach ................................................................ 334Low-level synchronization approach ................................................................. 335TransactionAwareDataSourceProxy ................................................................. 335

    12.5. Declarative transaction management ............................................................... 335Understanding the Spring Framework’s declarative transaction implementation ... 337Example of declarative transaction implementation ........................................... 337Rolling back a declarative transaction .............................................................. 341Configuring different transactional semantics for different beans ........................ 342 settings ....................................................................................... 344Using @Transactional ..................................................................................... 345

    @Transactional settings .......................................................................... 350Multiple Transaction Managers with @Transactional ................................. 351Custom shortcut annotations ................................................................... 352

    Transaction propagation .................................................................................. 352Required ................................................................................................ 352RequiresNew .......................................................................................... 353Nested ................................................................................................... 353

    Advising transactional operations ..................................................................... 353Using @Transactional with AspectJ ................................................................. 356

    12.6. Programmatic transaction management ........................................................... 357Using the TransactionTemplate ....................................................................... 357

    Specifying transaction settings ................................................................ 359Using the PlatformTransactionManager ............................................................ 359

    12.7. Choosing between programmatic and declarative transaction management ........ 360

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework xii

    12.8. Application server-specific integration .............................................................. 360IBM WebSphere ............................................................................................. 360Oracle WebLogic Server ................................................................................. 360

    12.9. Solutions to common problems ....................................................................... 361Use of the wrong transaction manager for a specific DataSource ....................... 361

    12.10. Further Resources ....................................................................................... 36113. DAO support ............................................................................................................ 362

    13.1. Introduction .................................................................................................... 36213.2. Consistent exception hierarchy ....................................................................... 36213.3. Annotations used for configuring DAO or Repository classes ............................ 363

    14. Data access with JDBC ............................................................................................ 36514.1. Introduction to Spring Framework JDBC .......................................................... 365

    Choosing an approach for JDBC database access ........................................... 365Package hierarchy .......................................................................................... 366

    14.2. Using the JDBC core classes to control basic JDBC processing and errorhandling ................................................................................................................. 367

    JdbcTemplate ................................................................................................. 367Examples of JdbcTemplate class usage ................................................... 367JdbcTemplate best practices ................................................................... 369

    NamedParameterJdbcTemplate ....................................................................... 371SQLExceptionTranslator .................................................................................. 373Executing statements ...................................................................................... 374Running queries ............................................................................................. 375Updating the database .................................................................................... 376Retrieving auto-generated keys ....................................................................... 376

    14.3. Controlling database connections .................................................................... 376DataSource .................................................................................................... 376DataSourceUtils .............................................................................................. 378SmartDataSource ........................................................................................... 378AbstractDataSource ........................................................................................ 378SingleConnectionDataSource .......................................................................... 378DriverManagerDataSource .............................................................................. 378TransactionAwareDataSourceProxy ................................................................. 379DataSourceTransactionManager ...................................................................... 379NativeJdbcExtractor ........................................................................................ 379

    14.4. JDBC batch operations .................................................................................. 380Basic batch operations with the JdbcTemplate ................................................. 380Batch operations with a List of objects ............................................................. 381Batch operations with multiple batches ............................................................ 382

    14.5. Simplifying JDBC operations with the SimpleJdbc classes ................................ 382Inserting data using SimpleJdbcInsert .............................................................. 383Retrieving auto-generated keys using SimpleJdbcInsert .................................... 383Specifying columns for a SimpleJdbcInsert ...................................................... 384Using SqlParameterSource to provide parameter values ................................... 385Calling a stored procedure with SimpleJdbcCall ............................................... 385Explicitly declaring parameters to use for a SimpleJdbcCall ............................... 387How to define SqlParameters .......................................................................... 388Calling a stored function using SimpleJdbcCall ................................................. 388Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................... 389

    14.6. Modeling JDBC operations as Java objects ..................................................... 390

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework xiii

    SqlQuery ........................................................................................................ 390MappingSqlQuery ........................................................................................... 391SqlUpdate ...................................................................................................... 392StoredProcedure ............................................................................................. 392

    14.7. Common problems with parameter and data value handling .............................. 395Providing SQL type information for parameters ................................................. 395Handling BLOB and CLOB objects .................................................................. 396Passing in lists of values for IN clause ............................................................ 397Handling complex types for stored procedure calls ........................................... 397

    14.8. Embedded database support .......................................................................... 398Why use an embedded database? .................................................................. 399Creating an embedded database instance using Spring XML ............................ 399Creating an embedded database instance programmatically .............................. 399Extending the embedded database support ...................................................... 399Using HSQL ................................................................................................... 399Using H2 ........................................................................................................ 399Using Derby ................................................................................................... 400Testing data access logic with an embedded database ..................................... 400

    14.9. Initializing a DataSource ................................................................................. 400Initializing a database instance using Spring XML ............................................. 400

    Initialization of Other Components that Depend on the Database ............... 40115. Object Relational Mapping (ORM) Data Access .......................................................... 403

    15.1. Introduction to ORM with Spring ..................................................................... 40315.2. General ORM integration considerations ......................................................... 404

    Resource and transaction management ........................................................... 404Exception translation ....................................................................................... 405

    15.3. Hibernate ....................................................................................................... 405SessionFactory setup in a Spring container ...................................................... 405Implementing DAOs based on plain Hibernate 3 API ........................................ 406Declarative transaction demarcation ................................................................ 407Programmatic transaction demarcation ............................................................ 409Transaction management strategies ................................................................ 410Comparing container-managed and locally defined resources ............................ 412Spurious application server warnings with Hibernate ......................................... 413

    15.4. JDO .............................................................................................................. 414PersistenceManagerFactory setup ................................................................... 414Implementing DAOs based on the plain JDO API ............................................. 415Transaction management ................................................................................ 417JdoDialect ...................................................................................................... 418

    15.5. JPA ............................................................................................................... 418Three options for JPA setup in a Spring environment ........................................ 418

    LocalEntityManagerFactoryBean .............................................................. 418Obtaining an EntityManagerFactory from JNDI ......................................... 419LocalContainerEntityManagerFactoryBean ............................................... 419Dealing with multiple persistence units ..................................................... 421

    Implementing DAOs based on plain JPA .......................................................... 422Transaction Management ................................................................................ 424JpaDialect ...................................................................................................... 424

    16. Marshalling XML using O/X Mappers ......................................................................... 42616.1. Introduction .................................................................................................... 426

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework xiv

    Ease of configuration ...................................................................................... 426Consistent Interfaces ...................................................................................... 426Consistent Exception Hierarchy ....................................................................... 426

    16.2. Marshaller and Unmarshaller .......................................................................... 426Marshaller ...................................................................................................... 426Unmarshaller .................................................................................................. 427XmlMappingException ..................................................................................... 428

    16.3. Using Marshaller and Unmarshaller ................................................................. 42816.4. XML Schema-based Configuration .................................................................. 43016.5. JAXB ............................................................................................................. 430

    Jaxb2Marshaller ............................................................................................. 430XML Schema-based Configuration ........................................................... 431

    16.6. Castor ........................................................................................................... 431CastorMarshaller ............................................................................................ 431Mapping ......................................................................................................... 432

    XML Schema-based Configuration ........................................................... 43216.7. XMLBeans ..................................................................................................... 433

    XmlBeansMarshaller ....................................................................................... 433XML Schema-based Configuration ........................................................... 433

    16.8. JiBX .............................................................................................................. 433JibxMarshaller ................................................................................................ 434

    XML Schema-based Configuration ........................................................... 43416.9. XStream ........................................................................................................ 434

    XStreamMarshaller ......................................................................................... 434V. The Web ........................................................................................................................... 436

    17. Web MVC framework ................................................................................................ 43717.1. Introduction to Spring Web MVC framework .................................................... 437

    Features of Spring Web MVC ......................................................................... 437Pluggability of other MVC implementations ...................................................... 439

    17.2. The DispatcherServlet .................................................................................... 439Special Bean Types In the WebApplicationContext ........................................... 442Default DispatcherServlet Configuration ........................................................... 443DispatcherServlet Processing Sequence .......................................................... 443

    17.3. Implementing Controllers ................................................................................ 445Defining a controller with @Controller .............................................................. 445Mapping Requests With @RequestMapping ..................................................... 446

    @Controller's and AOP Proxying ......................................................... 447New Support Classes for @RequestMapping methods in Spring MVC 3.1 .. 447URI Template Patterns ........................................................................... 448URI Template Patterns with Regular Expressions ..................................... 449Path Patterns ......................................................................................... 450Path Pattern Comparison ........................................................................ 450Path Patterns with Placeholders .............................................................. 450Path Pattern Matching By Suffix .............................................................. 450Matrix Variables ...................................................................................... 451Consumable Media Types ....................................................................... 452Producible Media Types .......................................................................... 453Request Parameters and Header Values ................................................. 453

    Defining @RequestMapping handler methods .................................................. 454Supported method argument types .......................................................... 454

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework xv

    Supported method return types ............................................................... 456Binding request parameters to method parameters with @RequestParam ... 457Mapping the request body with the @RequestBody annotation .................. 457Mapping the response body with the @ResponseBody annotation ............. 459Creating REST Controllers with the @RestController annotation ................ 459Using HttpEntity ...................................................................................... 459Using @ModelAttribute on a method ....................................................... 460Using @ModelAttribute on a method argument ......................................... 461Using @SessionAttributes to store model attributes in the HTTP sessionbetween requests ................................................................................... 462Specifying redirect and flash attributes ..................................................... 463Working with "application/x-www-form-urlencoded" data ............................ 463Mapping cookie values with the @CookieValue annotation ........................ 464Mapping request header attributes with the @RequestHeader annotation ... 464Method Parameters And Type Conversion ............................................... 465Customizing WebDataBinder initialization ................................................. 465Support for the Last-Modified Response Header To Facilitate ContentCaching ................................................................................................. 466Advising controllers with the @ControllerAdvice annotation ................. 467Jackson Serialization View Support ......................................................... 467Jackson JSONP Support ........................................................................ 468

    Asynchronous Request Processing .................................................................. 469Exception Handling for Async Requests ................................................... 470Intercepting Async Requests ................................................................... 470Configuration for Async Request Processing ............................................ 471

    Testing Controllers ......................................................................................... 47217.4. Handler mappings .......................................................................................... 472

    Intercepting requests with a HandlerInterceptor ................................................ 47317.5. Resolving views ............................................................................................. 475

    Resolving views with the ViewResolver interface .............................................. 475Chaining ViewResolvers ................................................................................. 477Redirecting to views ....................................................................................... 477

    RedirectView .......................................................................................... 478The redirect: prefix ................................................................................. 478The forward: prefix ................................................................................. 479

    ContentNegotiatingViewResolver ..................................................................... 47917.6. Using flash attributes ..................................................................................... 48117.7. Building URIs ................................................................................................. 482

    Building URIs to Controllers and methods ........................................................ 483Building URIs to Controllers and methods from views ....................................... 483

    17.8. Using locales ................................................................................................. 484Obtaining Time Zone Information .................................................................... 484AcceptHeaderLocaleResolver .......................................................................... 485CookieLocaleResolver ..................................................................................... 485SessionLocaleResolver ................................................................................... 485LocaleChangeInterceptor ................................................................................ 485

    17.9. Using themes ................................................................................................ 486Overview of themes ........................................................................................ 486Defining themes ............................................................................................. 486Theme resolvers ............................................................................................. 487

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework xvi

    17.10. Spring’s multipart (file upload) support ........................................................... 487Introduction .................................................................................................... 487Using a MultipartResolver with Commons FileUpload ........................................ 487Using a MultipartResolver with Servlet 3.0 ....................................................... 488Handling a file upload in a form ...................................................................... 488Handling a file upload request from programmatic clients .................................. 489

    17.11. Handling exceptions ..................................................................................... 490HandlerExceptionResolver .............................................................................. 490@ExceptionHandler ........................................................................................ 490Handling Standard Spring MVC Exceptions ...................................................... 491Annotating Business Exceptions With @ResponseStatus .................................. 492Customizing the Default Servlet Container Error Page ...................................... 492

    17.12. Web Security ............................................................................................... 49317.13. Convention over configuration support ........................................................... 493

    The Controller ControllerClassNameHandlerMapping ........................................ 493The Model ModelMap (ModelAndView) ............................................................ 494The View - RequestToViewNameTranslator ..................................................... 496

    17.14. ETag support ............................................................................................... 49717.15. Code-based Servlet container initialization ..................................................... 49717.16. Configuring Spring MVC ............................................................................... 499

    Enabling the MVC Java Config or the MVC XML Namespace ............................ 499Customizing the Provided Configuration ........................................................... 501Interceptors .................................................................................................... 501Content Negotiation ........................................................................................ 502View Controllers ............................................................................................. 503View Resolvers .............................................................................................. 503Serving of Resources ..................................................................................... 505Falling Back On the "Default" Servlet To Serve Resources ................................ 507Path Matching ................................................................................................ 508Advanced Customizations with MVC Java Config ............................................. 508Advanced Customizations with the MVC Namespace ........................................ 509

    18. View technologies ..................................................................................................... 51018.1. Introduction .................................................................................................... 51018.2. JSP & JSTL .................................................................................................. 510

    View resolvers ................................................................................................ 510Plain-old JSPs versus JSTL ............................................................................ 511Additional tags facilitating development ............................................................ 511Using Spring’s form tag library ........................................................................ 511

    Configuration .......................................................................................... 511The form tag .......................................................................................... 511The input tag .......................................................................................... 513The checkbox tag ................................................................................... 513The checkboxes tag ............................................................................... 515The radiobutton tag ................................................................................ 515The radiobuttons tag ............................................................................... 515The password tag ................................................................................... 516The select tag ........................................................................................ 516The option tag ........................................................................................ 516The options tag ...................................................................................... 517The textarea tag ..................................................................................... 518

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework xvii

    The hidden tag ....................................................................................... 518The errors tag ........................................................................................ 518HTTP Method Conversion ....................................................................... 520HTML5 Tags .......................................................................................... 521

    18.3. Tiles .............................................................................................................. 521Dependencies ................................................................................................ 521How to integrate Tiles ..................................................................................... 521

    UrlBasedViewResolver ............................................................................ 522ResourceBundleViewResolver ................................................................. 522SimpleSpringPreparerFactory and SpringBeanPreparerFactory ................. 523

    18.4. Velocity & FreeMarker .................................................................................... 523Dependencies ................................................................................................ 524Context configuration ...................................................................................... 524Creating templates ......................................................................................... 524Advanced configuration ................................................................................... 525

    velocity.properties ................................................................................... 525FreeMarker ............................................................................................. 525

    Bind support and form handling ....................................................................... 526The bind macros .................................................................................... 526Simple binding ........................................................................................ 526Form input generation macros ................................................................. 527HTML escaping and XHTML compliance ................................................. 530

    18.5. XSLT ............................................................................................................. 531My First Words ............................................................................................... 531

    Bean definitions ...................................................................................... 531Standard MVC controller code ................................................................. 531Convert the model data to XML ............................................................... 532Defining the view properties .................................................................... 532Document transformation ........................................................................ 533

    Summary ....................................................................................................... 53318.6. Document views (PDF/Excel) .......................................................................... 534

    Introduction .................................................................................................... 534Configuration and setup .................................................................................. 534

    Document view definitions ....................................................................... 534Controller code ....................................................................................... 534Subclassing for Excel views .................................................................... 534Subclassing for PDF views ..................................................................... 536

    18.7. JasperReports ............................................................................................... 536Dependencies ................................................................................................ 536Configuration .................................................................................................. 536

    Configuring the ViewResolver .................................................................. 537Configuring the Views ............................................................................. 537About Report Files .................................................................................. 537Using JasperReportsMultiFormatView ...................................................... 537

    Populating the ModelAndView ......................................................................... 538Working with Sub-Reports ............................................................................... 539

    Configuring Sub-Report Files .................................................................. 539Configuring Sub-Report Data Sources ..................................................... 540

    Configuring Exporter Parameters ..................................................................... 54018.8. Feed Views ................................................................................................... 541

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework xviii

    18.9. XML Marshalling View .................................................................................... 54118.10. JSON Mapping View .................................................................................... 54218.11. XML Mapping View ...................................................................................... 542

    19. Integrating with other web frameworks ....................................................................... 54319.1. Introduction .................................................................................................... 54319.2. Common configuration ................................................................................... 54419.3. JavaServer Faces 1.2 .................................................................................... 545

    SpringBeanFacesELResolver (JSF 1.2+) ......................................................... 545FacesContextUtils ........................................................................................... 545

    19.4. Apache Struts 2.x .......................................................................................... 54519.5. Tapestry 5.x .................................................................................................. 54619.6. Further Resources ......................................................................................... 546

    20. Portlet MVC Framework ............................................................................................ 54720.1. Introduction .................................................................................................... 547

    Controllers - The C in MVC ............................................................................ 548Views - The V in MVC .................................................................................... 548Web-scoped beans ......................................................................................... 548

    20.2. The DispatcherPortlet ..................................................................................... 54820.3. The ViewRendererServlet ............................................................................... 55020.4. Controllers ..................................................................................................... 551

    AbstractController and PortletContentGenerator ............................................... 552Other simple controllers .................................................................................. 553Command Controllers ..................................................................................... 553PortletWrappingController ................................................................................ 554

    20.5. Handler mappings .......................................................................................... 554PortletModeHandlerMapping ............................................................................ 555ParameterHandlerMapping .............................................................................. 555PortletModeParameterHandlerMapping ............................................................ 556Adding HandlerInterceptors ............................................................................. 556HandlerInterceptorAdapter ............................................................................... 557ParameterMappingInterceptor .......................................................................... 557

    20.6. Views and resolving them .............................................................................. 55720.7. Multipart (file upload) support ......................................................................... 557

    Using the PortletMultipartResolver ................................................................... 558Handling a file upload in a form ...................................................................... 558

    20.8. Handling exceptions ....................................................................................... 56220.9. Annotation-based controller configuration ........................................................ 562

    Setting up the dispatcher for annotation support ............................................... 562Defining a controller with @Controller .............................................................. 563Mapping requests with @RequestMapping ....................................................... 563Supported handler method arguments ............................................................. 565Binding request parameters to method parameters with @RequestParam .......... 567Providing a link to data from the model with @ModelAttribute ............................ 567Specifying attributes to store in a Session with @SessionAttributes .................... 568Customizing WebDataBinder initialization ......................................................... 568

    Customizing data binding with @InitBinder ............................................... 568Configuring a custom WebBindingInitializer .............................................. 569

    20.10. Portlet application deployment ...................................................................... 56921. WebSocket Support .................................................................................................. 570

    21.1. Introduction .................................................................................................... 570

  • Spring Framework Reference Documentation

    4.1.8.RELEASE Spring Framework xix

    WebSocket Fallback Options ........................................................................... 570A Messaging Architecture ............................................................................... 571Sub-Protocol Support in WebSocket ................................................................ 571Should I Use WebSocket? .............................................................................. 571

    21.2. WebSocket API ............................................................................................. 572Create and Configure a WebSocketHandler ..................................................... 572Customizing the WebSocket Handshake .......................................................... 573WebSocketHan