+ All Categories
Home > Documents > Spring Framework Reference

Spring Framework Reference

Date post: 03-Nov-2014
Category:
Upload: evaldorw
View: 28 times
Download: 6 times
Share this document with a friend
Popular Tags:
840
Reference Documentation 3.1 Copyright © 2004-2012 Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, Rob Harrop, Alef Arendsen, Thomas Risberg, Darren Davison, Dmitriy Kopylenko, Mark Pollack, Thierry Templier, Erwin Vervaet, Portia Tung, Ben Hale, Adrian Colyer, John Lewis, Costin Leau, Mark Fisher, Sam Brannen, Ramnivas Laddad, Arjen Poutsma, Chris Beams, Tareq Abedrabbo, Andy Clement, Dave Syer, Oliver Gierke, Rossen Stoyanchev 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

Reference Documentation

3.1Copyright 2004-2012 Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, Rob Harrop, Alef Arendsen, Thomas Risberg, Darren Davison, Dmitriy Kopylenko, Mark Pollack, Thierry Templier, Erwin Vervaet, Portia Tung, Ben Hale, Adrian Colyer, John Lewis, Costin Leau, Mark Fisher, Sam Brannen, Ramnivas Laddad, Arjen Poutsma, Chris Beams, Tareq Abedrabbo, Andy Clement, Dave Syer, Oliver Gierke, Rossen Stoyanchev

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

Spring Framework

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 ............................................................................................................3 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 ...........................................6 Spring Dependencies and Depending on Spring ..........................................8 Maven Dependency Management ..............................................................8 Ivy Dependency Management .................................................................10 Logging .........................................................................................................10 Not Using Commons Logging .................................................................11 Using SLF4J ..........................................................................................11 Using Log4J ...........................................................................................13 II. What's New in Spring 3 ......................................................................................................15 2. New Features and Enhancements in Spring 3.0 .............................................................16 2.1. Java 5 ..............................................................................................................16 2.2. Improved documentation ..................................................................................16 2.3. New articles and tutorials ..................................................................................16 2.4. New module organization and build system .......................................................17 2.5. Overview of new features .................................................................................18 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 .................21 The Data Tier .................................................................................................21 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 ......................................................................22 3. New Features and Enhancements in Spring 3.1 .............................................................23 3.1. Overview of new features .................................................................................23

3.1

Reference Documentation

ii

Spring Framework

Cache Abstraction ..........................................................................................23 Bean Definition Profiles ..................................................................................23 Environment Abstraction ................................................................................23 PropertySource Abstraction .............................................................................23 Code equivalents for Spring's XML namespaces ...............................................24 Support for Hibernate 4.x ................................................................................24 TestContext framework support for @Configuration classes and bean definition profiles ..........................................................................................................24 c: namespace for more concise constructor injection .........................................25 Support for injection against non-standard JavaBeans setters .............................25 Support for Servlet 3 code-based configuration of Servlet Container ..................25 Support for Servlet 3 MultipartResolver ...........................................................25 JPA EntityManagerFactory bootstrapping without persistence.xml ....................25 New HandlerMethod-based Support Classes For Annotated Controller Processing .......................................................................................................................26 "consumes" and "produces" conditions in @RequestMapping ...........................27 Flash Attributes and RedirectAttributes ............................................................27 URI Template Variable Enhancements .............................................................27 @Valid On @RequestBody Controller Method Arguments ...............................27 @RequestPart Annotation On Controller Method Arguments ............................28 UriComponentsBuilder and UriComponents .....................................................28 III. Core Technologies ............................................................................................................29 4. The IoC container .......................................................................................................30 4.1. Introduction to the Spring IoC container and beans .............................................30 4.2. Container overview ..........................................................................................30 Configuration metadata ...................................................................................31 Instantiating a container ..................................................................................32 Composing XML-based configuration metadata .......................................34 Using the container .........................................................................................34 4.3. Bean overview .................................................................................................35 Naming beans .................................................................................................36 Aliasing a bean outside the bean definition ...............................................37 Instantiating beans ..........................................................................................38 Instantiation with a constructor ................................................................38 Instantiation with a static factory method .................................................39 Instantiation using an instance factory method ..........................................39 4.4. Dependencies ...................................................................................................41 Dependency injection ......................................................................................41 Constructor-based dependency injection ...................................................41 Setter-based dependency injection ...........................................................43 Dependency resolution process ................................................................44 Examples of dependency injection ...........................................................46 Dependencies and configuration in detail .........................................................48 Straight values (primitives, Strings, and so on) .........................................48 References to other beans (collaborators) .................................................49 3.1 Reference Documentation iii

Spring Framework

Inner beans .............................................................................................50 Collections .............................................................................................51 Null and empty string values ...................................................................53 XML shortcut with the p-namespace ........................................................54 XML shortcut with the c-namespace ........................................................55 Compound property names ......................................................................56 Using depends-on ...........................................................................................56 Lazy-initialized beans .....................................................................................57 Autowiring collaborators .................................................................................57 Limitations and disadvantages of autowiring ............................................59 Excluding a bean from autowiring ...........................................................59 Method injection ............................................................................................60 Lookup method injection .........................................................................61 Arbitrary method replacement .................................................................62 4.5. Bean scopes .....................................................................................................63 The singleton scope ........................................................................................64 The prototype scope ........................................................................................65 Singleton beans with prototype-bean dependencies ...........................................66 Request, session, and global session scopes ......................................................66 Initial web configuration .........................................................................66 Request scope .........................................................................................67 Session scope .........................................................................................67 Global session scope ...............................................................................68 Scoped beans as dependencies .................................................................68 Custom scopes ...............................................................................................70 Creating a custom scope ..........................................................................70 Using a custom scope ..............................................................................71 4.6. Customizing the nature of a bean .......................................................................72 Lifecycle callbacks .........................................................................................73 Initialization callbacks ............................................................................73 Destruction callbacks ..............................................................................74 Default initialization and destroy methods ................................................74 Combining lifecycle mechanisms ............................................................76 Startup and shutdown callbacks ...............................................................76 Shutting down the Spring IoC container gracefully in non-web applications 78 ApplicationContextAware and BeanNameAware ..............................................79 Other Aware interfaces ...................................................................................79 4.7. Bean definition inheritance ...............................................................................81 4.8. Container Extension Points ...............................................................................83 Customizing beans using a BeanPostProcessor .................................................83 Example: Hello World, BeanPostProcessor-style ......................................84 Example: The RequiredAnnotationBeanPostProcessor ..............................86 Customizing configuration metadata with a BeanFactoryPostProcessor ..............86 Example: the PropertyPlaceholderConfigurer ...........................................87 Example: the PropertyOverrideConfigurer ...............................................89 3.1 Reference Documentation iv

Spring Framework

Customizing instantiation logic with a FactoryBean ..........................................90 4.9. Annotation-based container configuration ..........................................................90 @Required .....................................................................................................92 @Autowired ...................................................................................................92 Fine-tuning annotation-based autowiring with qualifiers ...................................95 CustomAutowireConfigurer .......................................................................... 100 @Resource ................................................................................................... 100 @PostConstruct and @PreDestroy ................................................................. 102 4.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 .................................................................. 107 Providing a scope for autodetected components .............................................. 107 Providing qualifier metadata with annotations ................................................ 108 4.11. Using JSR 330 Standard Annotations ............................................................. 109 Dependency Injection with @Inject and @Named .......................................... 109 @Named: a standard equivalent to the @Component annotation ...................... 110 Limitations of the standard approach .............................................................. 111 4.12. Java-based container configuration ................................................................ 111 Basic concepts: @Configuration and @Bean .................................................. 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 ............................................................................................................. 114 Composing Java-based configurations ............................................................ 115 Using the @Import annotation ............................................................... 115 Combining Java and XML configuration ................................................ 117 Using the @Bean annotation ......................................................................... 120 Declaring a bean ................................................................................... 120 Injecting dependencies .......................................................................... 120 Receiving lifecycle callbacks ................................................................. 121 Specifying bean scope ........................................................................... 122 Customizing bean naming ..................................................................... 123 Bean aliasing ........................................................................................ 124 Further information about how Java-based configuration works internally ........ 124 4.13. Registering a LoadTimeWeaver .................................................................... 125 4.14. Additional Capabilities of the ApplicationContext .......................................... 125 Internationalization using MessageSource ...................................................... 126 Standard and Custom Events ......................................................................... 129 Convenient access to low-level resources ....................................................... 132 Convenient ApplicationContext instantiation for web applications ................... 132 3.1 Reference Documentation v

Spring Framework

Deploying a Spring ApplicationContext as a J2EE RAR file ............................ 133 4.15. The BeanFactory .......................................................................................... 134 BeanFactory or ApplicationContext? ............................................................. 134 Glue code and the evil singleton .................................................................... 136 5. Resources ................................................................................................................. 137 5.1. Introduction ................................................................................................... 137 5.2. The Resource interface ................................................................................... 137 5.3. Built-in Resource implementations .................................................................. 138 UrlResource ................................................................................................. 138 ClassPathResource ....................................................................................... 139 FileSystemResource ..................................................................................... 139 ServletContextResource ................................................................................ 139 InputStreamResource .................................................................................... 139 ByteArrayResource ...................................................................................... 140 5.4. The ResourceLoader ....................................................................................... 140 5.5. The ResourceLoaderAware interface ............................................................... 141 5.6. Resources as dependencies ............................................................................. 142 5.7. Application contexts and Resource paths ......................................................... 142 Constructing application contexts .................................................................. 142 Constructing ClassPathXmlApplicationContext instances - shortcuts ....... 143 Wildcards in application context constructor resource paths ............................ 144 Ant-style Patterns ................................................................................. 144 The classpath*: prefix ........................................................................... 145 Other notes relating to wildcards ............................................................ 145 FileSystemResource caveats .......................................................................... 146 6. Validation, Data Binding, and Type Conversion .......................................................... 148 6.1. Introduction ................................................................................................... 148 6.2. Validation using Spring's Validator interface .................................................... 148 6.3. Resolving codes to error messages .................................................................. 150 6.4. Bean manipulation and the BeanWrapper ........................................................ 150 Setting and getting basic and nested properties ............................................... 151 Built-in PropertyEditor implementations ........................................................ 152 Registering additional custom PropertyEditors ....................................... 155 6.5. Spring 3 Type Conversion .............................................................................. 158 Converter SPI ............................................................................................... 158 ConverterFactory .......................................................................................... 159 GenericConverter ......................................................................................... 160 ConditionalGenericConverter ................................................................ 160 ConversionService API ................................................................................. 161 Configuring a ConversionService .................................................................. 161 Using a ConversionService programatically ................................................... 162 6.6. Spring 3 Field Formatting ............................................................................... 162 Formatter SPI ............................................................................................... 163 Annotation-driven Formatting ....................................................................... 164 Format Annotation API ......................................................................... 165 3.1 Reference Documentation vi

Spring Framework

FormatterRegistry SPI .................................................................................. 166 FormatterRegistrar SPI ................................................................................. 166 Configuring Formatting in Spring MVC ......................................................... 167 6.7. Spring 3 Validation ........................................................................................ 168 Overview of the JSR-303 Bean Validation API ............................................... 168 Configuring a Bean Validation Implementation .............................................. 169 Injecting a Validator ............................................................................. 169 Configuring Custom Constraints ............................................................ 170 Additional Configuration Options .......................................................... 170 Configuring a DataBinder ............................................................................. 170 Spring MVC 3 Validation ............................................................................. 171 Triggering @Controller Input Validation ............................................... 171 Configuring a Validator for use by Spring MVC ..................................... 171 Configuring a JSR-303 Validator for use by Spring MVC ....................... 172 7. Spring Expression Language (SpEL) .......................................................................... 173 7.1. Introduction ................................................................................................... 173 7.2. Feature Overview ........................................................................................... 173 7.3. Expression Evaluation using Spring's Expression Interface ............................... 174 The EvaluationContext interface .................................................................... 177 Type Conversion .................................................................................. 177 7.4. Expression support for defining bean definitions .............................................. 178 XML based configuration ............................................................................. 178 Annotation-based configuration ..................................................................... 178 7.5. Language Reference ....................................................................................... 180 Literal expressions ........................................................................................ 180 Properties, Arrays, Lists, Maps, Indexers ........................................................ 180 Inline lists .................................................................................................... 181 Array construction ........................................................................................ 181 Methods ....................................................................................................... 182 Operators ..................................................................................................... 182 Relational operators .............................................................................. 182 Logical operators .................................................................................. 183 Mathematical operators ......................................................................... 183 Assignment .................................................................................................. 184 Types ........................................................................................................... 184 Constructors ................................................................................................. 184 Variables ...................................................................................................... 185 The #this and #root variables ................................................................. 185 Functions ..................................................................................................... 185 Bean references ............................................................................................ 186 Ternary Operator (If-Then-Else) .................................................................... 186 The Elvis Operator ....................................................................................... 187 Safe Navigation operator ............................................................................... 187 Collection Selection ...................................................................................... 188 Collection Projection .................................................................................... 188 3.1 Reference Documentation vii

Spring Framework

Expression templating ................................................................................... 189 7.6. Classes used in the examples ........................................................................... 189 8. Aspect Oriented Programming with Spring ................................................................. 193 8.1. Introduction ................................................................................................... 193 AOP concepts ............................................................................................... 193 Spring AOP capabilities and goals ................................................................. 195 AOP Proxies ................................................................................................ 196 8.2. @AspectJ support .......................................................................................... 197 Enabling @AspectJ Support .......................................................................... 197 Declaring an aspect ....................................................................................... 197 Declaring a pointcut ...................................................................................... 198 Supported Pointcut Designators ............................................................. 199 Combining pointcut expressions ............................................................ 201 Sharing common pointcut definitions ..................................................... 201 Examples ............................................................................................. 202 Writing good pointcuts .......................................................................... 205 Declaring advice ........................................................................................... 206 Before advice ....................................................................................... 206 After returning advice ........................................................................... 206 After throwing advice ........................................................................... 207 After (finally) advice ............................................................................ 208 Around advice ...................................................................................... 208 Advice parameters ................................................................................ 209 Advice ordering .................................................................................... 213 Introductions ................................................................................................ 213 Aspect instantiation models ........................................................................... 214 Example ....................................................................................................... 215 8.3. Schema-based AOP support ............................................................................ 216 Declaring an aspect ....................................................................................... 217 Declaring a pointcut ...................................................................................... 217 Declaring advice ........................................................................................... 219 Before advice ....................................................................................... 219 After returning advice ........................................................................... 220 After throwing advice ........................................................................... 220 After (finally) advice ............................................................................ 221 Around advice ...................................................................................... 221 Advice parameters ................................................................................ 222 Advice ordering .................................................................................... 224 Introductions ................................................................................................ 224 Aspect instantiation models ........................................................................... 225 Advisors ...................................................................................................... 225 Example ....................................................................................................... 225 8.4. Choosing which AOP declaration style to use .................................................. 227 Spring AOP or full AspectJ? ......................................................................... 227 @AspectJ or XML for Spring AOP? .............................................................. 228 3.1 Reference Documentation viii

Spring Framework

8.5. Mixing aspect types ........................................................................................ 229 8.6. Proxying mechanisms ..................................................................................... 229 Understanding AOP proxies .......................................................................... 230 8.7. Programmatic creation of @AspectJ Proxies .................................................... 232 8.8. Using AspectJ with Spring applications ........................................................... 232 Using AspectJ to dependency inject domain objects with Spring ...................... 233 Unit testing @Configurable objects ....................................................... 235 Working with multiple application contexts ............................................ 236 Other Spring aspects for AspectJ ................................................................... 236 Configuring AspectJ aspects using Spring IoC ................................................ 237 Load-time weaving with AspectJ in the Spring Framework ............................. 238 A first example ..................................................................................... 238 Aspects ................................................................................................ 241 'META-INF/aop.xml' ............................................................................ 242 Required libraries (JARS) ..................................................................... 242 Spring configuration ............................................................................. 242 Environment-specific configuration ....................................................... 245 8.9. Further Resources .......................................................................................... 248 9. Spring AOP APIs ...................................................................................................... 249 9.1. Introduction ................................................................................................... 249 9.2. Pointcut API in Spring .................................................................................... 249 Concepts ...................................................................................................... 249 Operations on pointcuts ................................................................................. 250 AspectJ expression pointcuts ......................................................................... 250 Convenience pointcut implementations .......................................................... 250 Static pointcuts ..................................................................................... 251 Dynamic pointcuts ................................................................................ 252 Pointcut superclasses .................................................................................... 252 Custom pointcuts .......................................................................................... 253 9.3. Advice API in Spring ..................................................................................... 253 Advice lifecycles .......................................................................................... 253 Advice types in Spring .................................................................................. 253 Interception around advice .................................................................... 253 Before advice ....................................................................................... 254 Throws advice ...................................................................................... 255 After Returning advice .......................................................................... 256 Introduction advice ............................................................................... 257 9.4. Advisor API in Spring .................................................................................... 260 9.5. Using the ProxyFactoryBean to create AOP proxies ......................................... 260 Basics .......................................................................................................... 260 JavaBean properties ...................................................................................... 261 JDK- and CGLIB-based proxies .................................................................... 262 Proxying interfaces ....................................................................................... 263 Proxying classes ........................................................................................... 265 Using 'global' advisors .................................................................................. 265 3.1 Reference Documentation ix

Spring Framework

9.6. Concise proxy definitions ............................................................................... 266 9.7. Creating AOP proxies programmatically with the ProxyFactory ........................ 267 9.8. Manipulating advised objects .......................................................................... 267 9.9. Using the "autoproxy" facility ......................................................................... 269 Autoproxy bean definitions ........................................................................... 269 BeanNameAutoProxyCreator ................................................................ 269 DefaultAdvisorAutoProxyCreator .......................................................... 270 AbstractAdvisorAutoProxyCreator ........................................................ 271 Using metadata-driven auto-proxying ............................................................ 271 9.10. Using TargetSources .................................................................................... 273 Hot swappable target sources ......................................................................... 274 Pooling target sources ................................................................................... 275 Prototype target sources ................................................................................ 276 ThreadLocal target sources ............................................................................ 276 9.11. Defining new Advice types ........................................................................... 277 9.12. Further resources .......................................................................................... 277 10. Testing ................................................................................................................... 278 10.1. Introduction to Spring Testing ....................................................................... 278 10.2. Unit Testing ................................................................................................. 278 Mock Objects ............................................................................................... 278 JNDI .................................................................................................... 278 Servlet API .......................................................................................... 278 Portlet API ........................................................................................... 279 Unit Testing support Classes ......................................................................... 279 General utilities .................................................................................... 279 Spring MVC ......................................................................................... 279 10.3. Integration Testing ....................................................................................... 279 Overview ..................................................................................................... 279 Goals of Integration Testing .......................................................................... 280 Context management and caching .......................................................... 281 Dependency Injection of test fixtures ..................................................... 281 Transaction management ....................................................................... 282 Support classes for integration testing .................................................... 282 JDBC Testing Support .................................................................................. 283 Annotations .................................................................................................. 283 Spring Testing Annotations ................................................................... 283 Standard Annotation Support ................................................................. 287 Spring JUnit Testing Annotations .......................................................... 287 Spring TestContext Framework ..................................................................... 289 Key abstractions ................................................................................... 289 Context management ............................................................................ 290 Dependency injection of test fixtures ..................................................... 298 Transaction management ....................................................................... 301 TestContext support classes ................................................................... 303 PetClinic Example ........................................................................................ 305 3.1 Reference Documentation x

Spring Framework

10.4. Further Resources ......................................................................................... 307 IV. Data Access .................................................................................................................... 308 11. Transaction Management ......................................................................................... 309 11.1. Introduction to Spring Framework transaction management ............................ 309 11.2. Advantages of the Spring Framework's transaction support model ................... 309 Global transactions ....................................................................................... 310 Local transactions ......................................................................................... 310 Spring Framework's consistent programming model ....................................... 310 11.3. Understanding the Spring Framework transaction abstraction .......................... 311 11.4. Synchronizing resources with transactions ..................................................... 315 High-level synchronization approach ............................................................. 315 Low-level synchronization approach .............................................................. 315 TransactionAwareDataSourceProxy ............................................................... 316 11.5. Declarative transaction management .............................................................. 316 Understanding the Spring Framework's declarative transaction implementation 318 Example of declarative transaction implementation ......................................... 318 Rolling back a declarative transaction ............................................................ 322 Configuring different transactional semantics for different beans ..................... 323 settings ..................................................................................... 325 Using @Transactional ................................................................................... 326 @Transactional settings ........................................................................ 330 Multiple Transaction Managers with @Transactional .............................. 331 Custom shortcut annotations .................................................................. 332 Transaction propagation ................................................................................ 333 Required .............................................................................................. 333 RequiresNew ........................................................................................ 333 Nested ................................................................................................. 333 Advising transactional operations .................................................................. 334 Using @Transactional with AspectJ ............................................................... 336 11.6. Programmatic transaction management .......................................................... 337 Using the TransactionTemplate ..................................................................... 338 Specifying transaction settings ............................................................... 339 Using the PlatformTransactionManager ......................................................... 340 11.7. Choosing between programmatic and declarative transaction management ....... 340 11.8. Application server-specific integration ........................................................... 340 IBM WebSphere ........................................................................................... 341 BEA WebLogic Server ................................................................................. 341 Oracle OC4J ................................................................................................. 341 11.9. Solutions to common problems ..................................................................... 342 Use of the wrong transaction manager for a specific DataSource ...................... 342 11.10. Further Resources ....................................................................................... 342 12. DAO support .......................................................................................................... 343 12.1. Introduction ................................................................................................. 343 12.2. Consistent exception hierarchy ...................................................................... 343 12.3. Annotations used for configuring DAO or Repository classes .......................... 344 3.1 Reference Documentation xi

Spring Framework

13. Data access with JDBC ............................................................................................ 346 13.1. Introduction to Spring Framework JDBC ....................................................... 346 Choosing an approach for JDBC database access ............................................ 346 Package hierarchy ......................................................................................... 347 13.2. Using the JDBC core classes to control basic JDBC processing and error handling ............................................................................................................................. 348 JdbcTemplate ............................................................................................... 348 Examples of JdbcTemplate class usage .................................................. 349 JdbcTemplate best practices .................................................................. 351 NamedParameterJdbcTemplate ...................................................................... 352 SimpleJdbcTemplate ..................................................................................... 354 SQLExceptionTranslator ............................................................................... 356 Executing statements .................................................................................... 357 Running queries ........................................................................................... 358 Updating the database ................................................................................... 359 Retrieving auto-generated keys ...................................................................... 359 13.3. Controlling database connections .................................................................. 360 DataSource .................................................................................................. 360 DataSourceUtils ........................................................................................... 361 SmartDataSource .......................................................................................... 361 AbstractDataSource ...................................................................................... 362 SingleConnectionDataSource ........................................................................ 362 DriverManagerDataSource ............................................................................ 362 TransactionAwareDataSourceProxy ............................................................... 362 DataSourceTransactionManager .................................................................... 363 NativeJdbcExtractor ..................................................................................... 363 13.4. JDBC batch operations ................................................................................. 364 Basic batch operations with the JdbcTemplate ................................................ 364 Batch operations with a List of objects ........................................................... 365 Batch operations with multiple batches .......................................................... 366 13.5. Simplifying JDBC operations with the SimpleJdbc classes .............................. 367 Inserting data using SimpleJdbcInsert ............................................................ 367 Retrieving auto-generated keys using SimpleJdbcInsert ................................... 368 Specifying columns for a SimpleJdbcInsert .................................................... 368 Using SqlParameterSource to provide parameter values .................................. 369 Calling a stored procedure with SimpleJdbcCall ............................................. 370 Explicitly declaring parameters to use for a SimpleJdbcCall ............................ 372 How to define SqlParameters ......................................................................... 373 Calling a stored function using SimpleJdbcCall .............................................. 373 Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................. 374 13.6. Modeling JDBC operations as Java objects .................................................... 375 SqlQuery ...................................................................................................... 376 MappingSqlQuery ........................................................................................ 376 SqlUpdate .................................................................................................... 377 StoredProcedure ........................................................................................... 378 3.1 Reference Documentation xii

Spring Framework

13.7. Common problems with parameter and data value handling ............................ 381 Providing SQL type information for parameters .............................................. 381 Handling BLOB and CLOB objects ............................................................... 381 Passing in lists of values for IN clause ........................................................... 383 Handling complex types for stored procedure calls ......................................... 383 13.8. Embedded database support .......................................................................... 385 Why use an embedded database? ................................................................... 385 Creating an embedded database instance using Spring XML ........................... 385 Creating an embedded database instance programmatically ............................. 385 Extending the embedded database support ...................................................... 385 Using HSQL ................................................................................................ 386 Using H2 ..................................................................................................... 386 Using Derby ................................................................................................. 386 Testing data access logic with an embedded database ...................................... 386 13.9. Initializing a DataSource ............................................................................... 387 Initializing a database instance using Spring XML .......................................... 387 Initialization of Other Components that Depend on the Database ............. 388 14. Object Relational Mapping (ORM) Data Access ....................................................... 390 14.1. Introduction to ORM with Spring .................................................................. 390 14.2. General ORM integration considerations ........................................................ 391 Resource and transaction management ........................................................... 391 Exception translation .................................................................................... 392 14.3. Hibernate ..................................................................................................... 393 SessionFactory setup in a Spring container ..................................................... 393 Implementing DAOs based on plain Hibernate 3 API ...................................... 394 Declarative transaction demarcation ............................................................... 395 Programmatic transaction demarcation ........................................................... 397 Transaction management strategies ................................................................ 398 Comparing container-managed and locally defined resources .......................... 400 Spurious application server warnings with Hibernate ...................................... 401 14.4. JDO ............................................................................................................. 402 PersistenceManagerFactory setup .................................................................. 402 Implementing DAOs based on the plain JDO API ........................................... 403 Transaction management ............................................................................... 405 JdoDialect .................................................................................................... 406 14.5. JPA ............................................................................................................. 407 Three options for JPA setup in a Spring environment ...................................... 407 LocalEntityManagerFactoryBean ........................................................... 407 Obtaining an EntityManagerFactory from JNDI ...................................... 408 LocalContainerEntityManagerFactoryBean ............................................ 408 Dealing with multiple persistence units .................................................. 411 Implementing DAOs based on plain JPA ........................................................ 411 Transaction Management .............................................................................. 414 JpaDialect .................................................................................................... 415 14.6. iBATIS SQL Maps ....................................................................................... 415 3.1 Reference Documentation xiii

Spring Framework

Setting up the SqlMapClient .......................................................................... 415 Using SqlMapClientTemplate and SqlMapClientDaoSupport .......................... 417 Implementing DAOs based on plain iBATIS API ........................................... 418 15. Marshalling XML using O/X Mappers ..................................................................... 419 15.1. Introduction ................................................................................................. 419 15.2. Marshaller and Unmarshaller ........................................................................ 419 Marshaller .................................................................................................... 419 Unmarshaller ................................................................................................ 420 XmlMappingException ................................................................................. 421 15.3. Using Marshaller and Unmarshaller ............................................................... 421 15.4. XML Schema-based Configuration ................................................................ 423 15.5. JAXB .......................................................................................................... 424 Jaxb2Marshaller ........................................................................................... 424 XML Schema-based Configuration ........................................................ 424 15.6. Castor .......................................................................................................... 425 CastorMarshaller .......................................................................................... 425 Mapping ...................................................................................................... 425 15.7. XMLBeans .................................................................................................. 426 XmlBeansMarshaller .................................................................................... 426 XML Schema-based Configuration ........................................................ 426 15.8. JiBX ............................................................................................................ 427 JibxMarshaller .............................................................................................. 427 XML Schema-based Configuration ........................................................ 427 15.9. XStream ...................................................................................................... 428 XStreamMarshaller ....................................................................................... 428 V. The Web .......................................................................................................................... 429 16. Web MVC framework ............................................................................................. 430 16.1. Introduction to Spring Web MVC framework ................................................. 430 Features of Spring Web MVC ....................................................................... 431 Pluggability of other MVC implementations ................................................... 432 16.2. The DispatcherServlet .................................................................................. 432 Special Bean Types In the WebApplicationContext ........................................ 435 Default DispatcherServlet Configuration ........................................................ 436 DispatcherServlet Processing Sequence .......................................................... 436 16.3. Implementing Controllers ............................................................................. 437 Defining a controller with @Controller .......................................................... 438 Mapping Requests With @RequestMapping ................................................... 439 New Support Classes for @RequestMapping methods in Spring MVC 3.1 441 URI Template Patterns .......................................................................... 441 URI Template Patterns with Regular Expressions ................................... 443 Path Patterns ........................................................................................ 443 Consumable Media Types ..................................................................... 443 Producible Media Types ........................................................................ 444 Request Parameters and Header Values .................................................. 444 Defining @RequestMapping handler methods ................................................ 445 3.1 Reference Documentation xiv

Spring Framework

Supported method argument types ......................................................... 445 Supported method return types .............................................................. 447 Binding request parameters to method parameters with @RequestParam .. 448 Mapping the request body with the @RequestBody annotation ................ 449 Mapping the response body with the @ResponseBody annotation ........... 450 Using HttpEntity ............................................................................. 450 Using @ModelAttribute on a method ..................................................... 451 Using @ModelAttribute on a method argument ...................................... 452 Using @SessionAttributes to store model attributes in the HTTP session between requests .................................................................................. 454 Specifying redirect and flash attributes ................................................... 454 Working with "application/x-www-form-urlencoded" data ...................... 455 Mapping cookie values with the @CookieValue annotation .................... 456 Mapping request header attributes with the @RequestHeader annotation .. 456 Method Parameters And Type Conversion ............................................. 457 Customizing WebDataBinder initialization ............................................. 457 Support for the 'Last-Modified' Response Header To Facilitate Content Caching ............................................................................................... 458 16.4. Handler mappings ........................................................................................ 459 Intercepting requests with a HandlerInterceptor .............................................. 460 16.5. Resolving views ........................................................................................... 461 Resolving views with the ViewResolver interface ........................................... 461 Chaining ViewResolvers ............................................................................... 463 Redirecting to views ..................................................................................... 464 RedirectView ....................................................................................... 465 The redirect: prefix ............................................................................... 465 The forward: prefix ............................................................................... 466 ContentNegotiatingViewResolver .................................................................. 466 16.6. Using flash attributes .................................................................................... 468 16.7. Building URIs .............................................................................................. 469 16.8. Using locales ............................................................................................... 470 AcceptHeaderLocaleResolver ........................................................................ 471 CookieLocaleResolver .................................................................................. 471 SessionLocaleResolver ................................................................................. 471 LocaleChangeInterceptor .............................................................................. 472 16.9. Using themes ............................................................................................... 472 Overview of themes ...................................................................................... 472 Defining themes ........................................................................................... 472 Theme resolvers ........................................................................................... 473 16.10. Spring's multipart (file upload) support ........................................................ 474 Introduction ................................................................................................. 474 Using a MultipartResolver with Commons FileUpload .................................... 474 Using a MultipartResolver with Servlet 3.0 .................................................... 475 Handling a file upload in a form .................................................................... 475 Handling a file upload request from programmatic clients ............................... 476 3.1 Reference Documentation xv

Spring Framework

16.11. Handling exceptions ................................................................................... 477 HandlerExceptionResolver ............................................................................ 477 @ExceptionHandler ...................................................................................... 478 16.12. Convention over configuration support ........................................................ 478 The Controller ControllerClassNameHandlerMapping .................................... 479 The Model ModelMap (ModelAndView) ....................................................... 480 The View - RequestToViewNameTranslator .................................................. 481 16.13. ETag support .............................................................................................. 483 16.14. Configuring Spring MVC ............................................................................ 483 Enabling MVC Java Config or the MVC XML Namespace ............................. 484 Customizing the Provided Configuration ........................................................ 485 Configuring Interceptors ............................................................................... 486 Configuring View Controllers ....................................................................... 486 Configuring Serving of Resources ................................................................. 487 mvc:default-servlet-handler ........................................................................... 489 More Spring Web MVC Resources ................................................................ 490 Advanced Customizations with MVC Java Config .......................................... 490 Advanced Customizations with the MVC Namespace ..................................... 491 17. View technologies ................................................................................................... 493 17.1. Introduction ................................................................................................. 493 17.2. JSP & JSTL ................................................................................................. 493 View resolvers ............................................................................................. 493 'Plain-old' JSPs versus JSTL .......................................................................... 494 Additional tags facilitating development ........................................................ 494 Using Spring's form tag library ...................................................................... 494 Configuration ....................................................................................... 494 The form tag ........................................................................................ 495 The input tag ........................................................................................ 496 The checkbox tag .................................................................................. 496 The checkboxes tag .............................................................................. 498 The radiobutton tag ............................................................................... 498 The radiobuttons tag ............................................................................. 499 The password tag .................................................................................. 499 The select tag ....................................................................................... 499 The option tag ...................................................................................... 500 The options tag ..................................................................................... 500 The textarea tag .................................................................................... 501 The hidden tag ...................................................................................... 501 The errors tag ....................................................................................... 502 HTTP Method Conversion .................................................................... 504 HTML5 Tags ....................................................................................... 504 17.3. Tiles ............................................................................................................ 505 Dependencies ............................................................................................... 505 How to integrate Tiles ................................................................................... 505 UrlBasedViewResolver ......................................................................... 506 3.1 Reference Documentation xvi

Spring Framework

ResourceBundleViewResolver .............................................................. 506 SimpleSpringPreparerFactory and SpringBeanPreparerFactory ................ 506 17.4. Velocity & FreeMarker ................................................................................. 507 Dependencies ............................................................................................... 507 Context configuration ................................................................................... 507 Creating templates ........................................................................................ 508 Advanced configuration ................................................................................ 508 velocity.properties ................................................................................ 509 FreeMarker .......................................................................................... 509 Bind support and form handling ..................................................................... 509 The bind macros ................................................................................... 510 Simple binding ..................................................................................... 510 Form input generation macros ............................................................... 511 HTML escaping and XHTML compliance ............................................. 515 17.5. XSLT .......................................................................................................... 516 My First Words ............................................................................................ 516 Bean definitions ................................................................................... 516 Standard MVC controller code .............................................................. 516 Convert the model data to XML ............................................................ 517 Defining the view properties .................................................................. 518 Document transformation ...................................................................... 518 Summary ..................................................................................................... 518 17.6. Document views (PDF/Excel) ....................................................................... 519 Introduction ................................................................................................. 519 Configuration and setup ................................................................................ 519 Document view definitions .................................................................... 519 Controller code ..................................................................................... 520 Subclassing for Excel views .................................................................. 520 Subclassing for PDF views .................................................................... 521 17.7. JasperReports ............................................................................................... 522 Dependencies ............................................................................................... 522 Configuration ............................................................................................... 522 Configuring the ViewResolver .............................................................. 523 Configuring the Views .......................................................................... 523 About Report Files ............................................................................... 523 Using JasperReportsMultiFormatView ................................................... 524 Populating the ModelAndView ...................................................................... 525 Working with Sub-Reports ............................................................................ 525 Configuring Sub-Report Files ................................................................ 526 Configuring Sub-Report Data Sources ................................................... 526 Configuring Exporter Parameters ................................................................... 527 17.8. Feed Views .................................................................................................. 527 17.9. XML Marshalling View ................................................................................ 528 17.10. JSON Mapping View .................................................................................. 528 18. Integrating with other web frameworks ..................................................................... 530 3.1 Reference Documentation xvii

Spring Framework

18.1. Introduction ................................................................................................. 530 18.2. Common configuration ................................................................................. 531 18.3. JavaServer Faces 1.1 and 1.2 ......................................................................... 532 DelegatingVariableResolver (JSF 1.1/1.2) ...................................................... 532 SpringBeanVariableResolver (JSF 1.1/1.2) ..................................................... 533 SpringBeanFacesELResolver (JSF 1.2+) ........................................................ 533 FacesContextUtils ........................................................................................ 534 18.4. Apache Struts 1.x and 2.x ............................................................................. 534 ContextLoaderPlugin .................................................................................... 535 DelegatingRequestProcessor ................................................................. 536 DelegatingActionProxy ......................................................................... 536 ActionSupport Classes .................................................................................. 537 18.5. WebWork 2.x ............................................................................................... 537 18.6. Tapestry 3.x and 4.x ..................................................................................... 538 Injecting Spring-managed beans .................................................................... 539 Dependency Injecting Spring Beans into Tapestry pages ......................... 540 Component definition files .................................................................... 541 Adding abstract accessors ...................................................................... 542 Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style ............................................................................................................. 544 18.7. Further Resources ......................................................................................... 545 19. Portlet MVC Framework ......................................................................................... 546 19.1. Introduction ................................................................................................. 546 Controllers - The C in MVC .......................................................................... 547 Views - The V in MVC ................................................................................. 547 Web-scoped beans ........................................................................................ 548 19.2. The DispatcherPortlet ................................................................................... 548 19.3. The ViewRendererServlet ............................................................................. 550 19.4. Controllers ................................................................................................... 551 AbstractController and PortletContentGenerator ............................................. 551 Other simple controllers ................................................................................ 553 Command Controllers ................................................................................... 553 PortletWrappingController ............................................................................ 554 19.5. Handler mappings ........................................................................................ 554 PortletModeHandlerMapping ........................................................................ 555 ParameterHandlerMapping ............................................................................ 556 PortletModeParameterHandlerMapping ......................................................... 556 Adding HandlerInterceptors .......................................................................... 557 HandlerInterceptorAdapter ............................................................................ 557 ParameterMappingInterceptor ....................................................................... 557 19.6. Views and resolving them ............................................................................. 558 19.7. Multipart (file upload) support ...................................................................... 558 Using the PortletMultipartResolver ................................................................ 559 Handling a file upload in a form .................................................................... 559 19.8. Handling exceptions ..................................................................................... 562 3.1 Reference Documentation xviii

Spring Framework

19.9. Annotation-based controller configuration ..................................................... 563 Setting up the dispatcher for annotation support .............................................. 563 Defining a controller with @Controller .......................................................... 563 Mapping requests with @RequestMapping ..................................................... 564 Supported handler method arguments ............................................................ 565 Binding request parameters to method parameters with @RequestParam .......... 567 Providing a link to data from the model with @ModelAttribute ....................... 568 Specifying attributes to store in a Session with @SessionAttributes ................. 568 Customizing WebDataBinder initialization ..................................................... 569 Customizing data binding with @InitBinder ........................................... 569 Configuring a custom WebBindingInitializer .......................................... 569 19.10. Portlet application deployment .................................................................... 570 VI. Integration ...................................................................................................................... 571 20. Remoting and web services using Spring .................................................................. 572 20.1. Introduction ................................................................................................. 572 20.2. Exposing services using RMI ........................................................................ 573 Exporting the service using the RmiServiceExporter ....................................... 573 Linking in the service at the client ................................................................. 574 20.3. Using Hessian or Burlap to remotely call services via HTTP ........................... 575 Wiring up the DispatcherServlet for Hessian and co. ....................................... 575 Exposing your beans by using the HessianServiceExporter .............................. 575 Linking in the service on the client ................................................................ 576 Using Burlap ................................................................................................ 576 Applying HTTP basic authentication to a service exposed through Hessian or Burlap .......................................................................................................... 577 20.4. Exposing services using HTTP invokers ........................................................ 577 Exposing the service object ........................................................................... 577 Linking in the service at the client ................................................................. 578 20.5. Web services ................................................................................................ 579 Exposing servlet-based web services using JAX-RPC ..................................... 580 Accessing web services using JAX-RPC ........................................................ 580 Registering JAX-RPC Bean Mappings ........................................................... 582 Registering your own JAX-RPC Handler ....................................................... 583 Exposing servlet-based web services using JAX-WS ...................................... 583 Exporting standalone web services using JAX-WS ......................................... 584 Exporting web services using the JAX-WS RI's Spring support ....................... 585 Accessing web services using JAX-WS .......................................................... 585 20.6. JMS ............................................................................................................. 586 Server-side configuration .............................................................................. 587 Client-side configuration ............................................................................... 588 20.7. Auto-detection is not implemented for remote interfaces ................................. 589 20.8. Considerations when choosing a technology ................................................... 589 20.9. Accessing RESTful services on the Client ...................................................... 590 RestTemplate ............................................................................................... 590 Working with the URI .......................................................................... 592 3.1 Reference Documentation xix

Spring Framework

Dealing with request and response headers ............................................. 593 HTTP Message Conversion ........................................................................... 593 StringHttpMessageConverter ................................................................. 594 FormHttpMessageConverter .................................................................. 594 ByteArrayHttpMessageConverter .......................................................... 594 MarshallingHttpMessageConverter ........................................................ 594 MappingJacksonHttpMessageConverter ................................................. 595 SourceHttpMessageConverter ............................................................... 595 BufferedImageHttpMessageConverter ................................................... 595 21. Enterprise JavaBeans (EJB) integration .................................................................... 596 21.1. Introduction ................................................................................................. 596 21.2. Accessing EJBs ............................................................................................ 596 Concepts ...................................................................................................... 596 Accessing local SLSBs ................................................................................. 597 Accessing remote SLSBs .............................................................................. 598 Accessing EJB 2.x SLSBs versus EJB 3 SLSBs .............................................. 599 21.3. Using Spring's EJB implementation support classes ........................................ 599 EJB 2.x base classes ..................................................................................... 599 EJB 3 injection interceptor ............................................................................ 601 22. JMS (Java Message Service) .................................................................................... 603 22.1. Introduction ................................................................................................. 603 22.2. Using Spring JMS ........................................................................................ 603 JmsTemplate ................................................................................................ 603 Connections ................................................................................................. 604 Caching Messaging Resources ............................................................... 605 SingleConnectionFactory ...................................................................... 605 CachingConnectionFactory ................................................................... 605 Destination Management ............................................................................... 605 Message Listener Containers ......................................................................... 606 SimpleMessageListenerContainer .......................................................... 607 DefaultMessageListenerContainer ......................................................... 607 Transaction management ............................................................................... 607 22.3. Sending a Message ....................................................................................... 608 Using Message Converters ............................................................................ 609 SessionCallback and ProducerCallback .......................................................... 610 22.4. Receiving a message ..................................................................................... 610 Synchronous Reception ................................................................................. 610 Asynchronous Reception - Message-Driv


Recommended