Prévia do material em texto
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. Table of Contents I. Overview of Spring Framework ..............................................................................................1 1. Introduction to Spring Framework ..................................................................................2 1.1. Dependency Injection and Inversion of Control ....................................................2 1.2. Modules ............................................................................................................3 Core Container .................................................................................................3 Data Access/Integration ....................................................................................4 Web .................................................................................................................4 AOP and Instrumentation ..................................................................................5 Test .................................................................................................................5 1.3. Usage scenarios .................................................................................................5 Dependency Management and Naming Conventions ...........................................9 Spring Dependencies and Depending on Spring ........................................11 Maven Dependency Management ............................................................12 Ivy Dependency Management .................................................................13 Logging .........................................................................................................14 Not Using Commons Logging .................................................................14 Using SLF4J ..........................................................................................15 Using Log4J ...........................................................................................16 II. What's New in Spring 3 ......................................................................................................18 2. New Features and Enhancements in Spring 3.0 .............................................................19 2.1. Java 5 ..............................................................................................................19 2.2. Improved documentation ..................................................................................19 2.3. New articles and tutorials ..................................................................................19 2.4. New module organization and build system .......................................................20 2.5. Overview of new features .................................................................................21 Core APIs updated for Java 5 ..........................................................................22 Spring Expression Language ...........................................................................22 The Inversion of Control (IoC) container ..........................................................23 Java based bean metadata ........................................................................23 Defining bean metadata within components ..............................................24 General purpose type conversion system and field formatting system .................24 The Data Tier .................................................................................................24 The Web Tier .................................................................................................25 Comprehensive REST support .................................................................25 @MVC additions ...................................................................................25 Declarative model validation ...........................................................................25 Early support for Java EE 6 .............................................................................25 Support for embedded databases ......................................................................25 3. New Features and Enhancements in Spring 3.1 .............................................................26 3.1. Overview of new features .................................................................................26 Spring Framework 3.1 Reference Documentation ii Cache Abstraction ..........................................................................................26 Bean Definition Profiles ..................................................................................26 Environment Abstraction ................................................................................26 PropertySource Abstraction .............................................................................26 Code equivalents for Spring's XML namespaces ...............................................27 Support for Hibernate 4.x ................................................................................27 TestContext framework support for @Configuration classes and bean definition profiles ..........................................................................................................27 c: namespace for more concise constructor injection .........................................28 Support for injection against non-standard JavaBeans setters .............................28 Support for Servlet 3 code-based configuration of Servlet Container ..................28 Support for Servlet 3 MultipartResolver ...........................................................28 JPA EntityManagerFactory bootstrapping without persistence.xml ....................28 New HandlerMethod-based Support Classes For Annotated Controller Processing .......................................................................................................................29 "consumes" and "produces" conditions in @RequestMapping ...........................30 Flash Attributes and RedirectAttributes ............................................................30 URI Template Variable Enhancements .............................................................30 @Valid On @RequestBody Controller Method Arguments ...............................30 @RequestPart Annotation On Controller Method Arguments ............................31 UriComponentsBuilder and UriComponents .....................................................31 III. Core Technologies ............................................................................................................32 4. The IoC container .......................................................................................................33 4.1. Introduction to the Spring IoC container and beans .............................................33 4.2. Container overview ..........................................................................................33 Configuration metadata ...................................................................................34 Instantiating a container ..................................................................................36 Composing XML-based configuration metadata .......................................37 Using the container .........................................................................................384.3. Bean overview .................................................................................................38 Naming beans .................................................................................................40 Aliasing a bean outside the bean definition ...............................................40 Instantiating beans ..........................................................................................41 Instantiation with a constructor ................................................................42 Instantiation with a static factory method .................................................42 Instantiation using an instance factory method ..........................................43 4.4. Dependencies ...................................................................................................44 Dependency injection ......................................................................................44 Constructor-based dependency injection ...................................................44 Setter-based dependency injection ...........................................................47 Dependency resolution process ................................................................48 Examples of dependency injection ...........................................................49 Dependencies and configuration in detail .........................................................51 Straight values (primitives, Strings, and so on) .........................................51 References to other beans (collaborators) .................................................53 Spring Framework 3.1 Reference Documentation iii Inner beans .............................................................................................54 Collections .............................................................................................54 Null and empty string values ...................................................................57 XML shortcut with the p-namespace ........................................................57 XML shortcut with the c-namespace ........................................................58 Compound property names ......................................................................59 Using depends-on ...........................................................................................59 Lazy-initialized beans .....................................................................................60 Autowiring collaborators .................................................................................61 Limitations and disadvantages of autowiring ............................................62 Excluding a bean from autowiring ...........................................................63 Method injection ............................................................................................63 Lookup method injection .........................................................................64 Arbitrary method replacement .................................................................66 4.5. Bean scopes .....................................................................................................67 The singleton scope ........................................................................................68 The prototype scope ........................................................................................69 Singleton beans with prototype-bean dependencies ...........................................70 Request, session, and global session scopes ......................................................70 Initial web configuration .........................................................................70 Request scope .........................................................................................71 Session scope .........................................................................................72 Global session scope ...............................................................................72 Scoped beans as dependencies .................................................................72 Custom scopes ...............................................................................................74 Creating a custom scope ..........................................................................75 Using a custom scope ..............................................................................75 4.6. Customizing the nature of a bean .......................................................................77 Lifecycle callbacks .........................................................................................77 Initialization callbacks ............................................................................77 Destruction callbacks ..............................................................................78 Default initialization and destroy methods ................................................79 Combining lifecycle mechanisms ............................................................80 Startup and shutdown callbacks ...............................................................80 Shutting down the Spring IoC container gracefully in non-web applications 82 ApplicationContextAware and BeanNameAware ..............................................83 Other Aware interfaces ...................................................................................84 4.7. Bean definition inheritance ...............................................................................86 4.8. Container Extension Points ...............................................................................87 Customizing beans using a BeanPostProcessor .................................................87 Example: Hello World, BeanPostProcessor-style ......................................89 Example: The RequiredAnnotationBeanPostProcessor ..............................90 Customizing configuration metadata with a BeanFactoryPostProcessor ..............90 Example: the PropertyPlaceholderConfigurer ...........................................91 Example: the PropertyOverrideConfigurer ...............................................93 Spring Framework 3.1 Reference Documentation iv Customizing instantiation logic with a FactoryBean ..........................................94 4.9. Annotation-based container configuration ..........................................................95 @Required .....................................................................................................96 @Autowired ...................................................................................................97 Fine-tuning annotation-based autowiring with qualifiers ...................................99 CustomAutowireConfigurer .......................................................................... 104 @Resource ................................................................................................... 105 @PostConstruct and @PreDestroy ................................................................. 106 4.10. Classpath scanning and managed components ................................................ 107 @Component and further stereotype annotations ............................................ 107 Automatically detecting classes and registering bean definitions ...................... 107 Using filters to customize scanning ................................................................ 109 Defining bean metadata within components .................................................... 110 Naming autodetected components .................................................................. 111 Providing a scope for autodetected components .............................................. 112 Providing qualifier metadata with annotations ................................................ 112 4.11. Using JSR 330 Standard Annotations ............................................................. 113 Dependency Injectionwith @Inject and @Named .......................................... 114 @Named: a standard equivalent to the @Component annotation ...................... 114 Limitations of the standard approach .............................................................. 115 4.12. Java-based container configuration ................................................................ 116 Basic concepts: @Configuration and @Bean .................................................. 116 Instantiating the Spring container using AnnotationConfigApplicationContext . 116 Simple construction .............................................................................. 117 Building the container programmatically using register(Class<?>...) ........ 117 Enabling component scanning with scan(String...) .................................. 117 Support for web applications with AnnotationConfigWebApplicationContext ............................................................................................................. 118 Composing Java-based configurations ............................................................ 119 Using the @Import annotation ............................................................... 119 Combining Java and XML configuration ................................................ 122 Using the @Bean annotation ......................................................................... 124 Declaring a bean ................................................................................... 124 Injecting dependencies .......................................................................... 125 Receiving lifecycle callbacks ................................................................. 125 Specifying bean scope ........................................................................... 126 Customizing bean naming ..................................................................... 128 Bean aliasing ........................................................................................ 128 Further information about how Java-based configuration works internally ........ 128 4.13. Registering a LoadTimeWeaver .................................................................... 129 4.14. Additional Capabilities of the ApplicationContext .......................................... 130 Internationalization using MessageSource ...................................................... 130 Standard and Custom Events ......................................................................... 133 Convenient access to low-level resources ....................................................... 136 Convenient ApplicationContext instantiation for web applications ................... 137 Spring Framework 3.1 Reference Documentation v Deploying a Spring ApplicationContext as a J2EE RAR file ............................ 138 4.15. The BeanFactory .......................................................................................... 138 BeanFactory or ApplicationContext? ............................................................. 139 Glue code and the evil singleton .................................................................... 140 5. Resources ................................................................................................................. 142 5.1. Introduction ................................................................................................... 142 5.2. The Resource interface ................................................................................... 142 5.3. Built-in Resource implementations .................................................................. 143 UrlResource ................................................................................................. 143 ClassPathResource ....................................................................................... 144 FileSystemResource ..................................................................................... 144 ServletContextResource ................................................................................ 144 InputStreamResource .................................................................................... 144 ByteArrayResource ...................................................................................... 145 5.4. The ResourceLoader ....................................................................................... 145 5.5. The ResourceLoaderAware interface ............................................................... 146 5.6. Resources as dependencies ............................................................................. 147 5.7. Application contexts and Resource paths ......................................................... 147 Constructing application contexts .................................................................. 147 Constructing ClassPathXmlApplicationContext instances - shortcuts ....... 148 Wildcards in application context constructor resource paths ............................ 149 Ant-style Patterns ................................................................................. 149 The classpath*: prefix ........................................................................... 150 Other notes relating to wildcards ............................................................ 150 FileSystemResource caveats .......................................................................... 151 6. Validation, Data Binding, and Type Conversion .......................................................... 153 6.1. Introduction ................................................................................................... 153 6.2. Validation using Spring's Validator interface .................................................... 153 6.3. Resolving codes to error messages .................................................................. 155 6.4. Bean manipulation and the BeanWrapper ........................................................ 155 Setting and getting basic and nested properties ............................................... 156 Built-in PropertyEditor implementations ........................................................ 157 Registering additional custom PropertyEditors ....................................... 160 6.5. Spring 3 Type Conversion .............................................................................. 163 Converter SPI ............................................................................................... 163 ConverterFactory .......................................................................................... 164 GenericConverter ......................................................................................... 165 ConditionalGenericConverter ................................................................ 165 ConversionService API ................................................................................. 166 Configuring a ConversionService .................................................................. 166 Using a ConversionService programatically ................................................... 167 6.6. Spring 3 Field Formatting ............................................................................... 167 Formatter SPI ............................................................................................... 168 Annotation-driven Formatting ....................................................................... 169 Format Annotation API ......................................................................... 170 Spring Framework 3.1 Reference Documentation vi FormatterRegistry SPI .................................................................................. 171 FormatterRegistrar SPI ................................................................................. 171 Configuring Formatting in Spring MVC ......................................................... 172 6.7. Spring 3 Validation ........................................................................................173 Overview of the JSR-303 Bean Validation API ............................................... 173 Configuring a Bean Validation Implementation .............................................. 174 Injecting a Validator ............................................................................. 174 Configuring Custom Constraints ............................................................ 175 Additional Configuration Options .......................................................... 175 Configuring a DataBinder ............................................................................. 175 Spring MVC 3 Validation ............................................................................. 176 Triggering @Controller Input Validation ............................................... 176 Configuring a Validator for use by Spring MVC ..................................... 176 Configuring a JSR-303 Validator for use by Spring MVC ....................... 177 7. Spring Expression Language (SpEL) .......................................................................... 178 7.1. Introduction ................................................................................................... 178 7.2. Feature Overview ........................................................................................... 178 7.3. Expression Evaluation using Spring's Expression Interface ............................... 179 The EvaluationContext interface .................................................................... 182 Type Conversion .................................................................................. 182 7.4. Expression support for defining bean definitions .............................................. 183 XML based configuration ............................................................................. 183 Annotation-based configuration ..................................................................... 183 7.5. Language Reference ....................................................................................... 185 Literal expressions ........................................................................................ 185 Properties, Arrays, Lists, Maps, Indexers ........................................................ 185 Inline lists .................................................................................................... 186 Array construction ........................................................................................ 186 Methods ....................................................................................................... 187 Operators ..................................................................................................... 187 Relational operators .............................................................................. 187 Logical operators .................................................................................. 188 Mathematical operators ......................................................................... 188 Assignment .................................................................................................. 189 Types ........................................................................................................... 189 Constructors ................................................................................................. 189 Variables ...................................................................................................... 190 The #this and #root variables ................................................................. 190 Functions ..................................................................................................... 190 Bean references ............................................................................................ 191 Ternary Operator (If-Then-Else) .................................................................... 191 The Elvis Operator ....................................................................................... 192 Safe Navigation operator ............................................................................... 192 Collection Selection ...................................................................................... 193 Collection Projection .................................................................................... 193 Spring Framework 3.1 Reference Documentation vii Expression templating ................................................................................... 194 7.6. Classes used in the examples ........................................................................... 194 8. Aspect Oriented Programming with Spring ................................................................. 198 8.1. Introduction ................................................................................................... 198 AOP concepts ............................................................................................... 198 Spring AOP capabilities and goals ................................................................. 200 AOP Proxies ................................................................................................ 201 8.2. @AspectJ support .......................................................................................... 202 Enabling @AspectJ Support .......................................................................... 202 Declaring an aspect ....................................................................................... 202 Declaring a pointcut ...................................................................................... 203 Supported Pointcut Designators ............................................................. 204 Combining pointcut expressions ............................................................ 206 Sharing common pointcut definitions ..................................................... 206 Examples ............................................................................................. 207 Writing good pointcuts .......................................................................... 210 Declaring advice ........................................................................................... 211 Before advice ....................................................................................... 211 After returning advice ........................................................................... 211 After throwing advice ........................................................................... 212 After (finally) advice ............................................................................ 213 Around advice ...................................................................................... 213 Advice parameters ................................................................................ 214 Advice ordering .................................................................................... 218 Introductions ................................................................................................ 218 Aspect instantiation models ........................................................................... 219 Example ....................................................................................................... 220 8.3. Schema-based AOP support ............................................................................ 221 Declaring an aspect ....................................................................................... 222 Declaring a pointcut ...................................................................................... 222 Declaring advice ........................................................................................... 224 Before advice ....................................................................................... 224 After returning advice ........................................................................... 225 After throwing advice........................................................................... 225 After (finally) advice ............................................................................ 226 Around advice ...................................................................................... 226 Advice parameters ................................................................................ 227 Advice ordering .................................................................................... 229 Introductions ................................................................................................ 229 Aspect instantiation models ........................................................................... 230 Advisors ...................................................................................................... 230 Example ....................................................................................................... 230 8.4. Choosing which AOP declaration style to use .................................................. 232 Spring AOP or full AspectJ? ......................................................................... 232 @AspectJ or XML for Spring AOP? .............................................................. 233 Spring Framework 3.1 Reference Documentation viii 8.5. Mixing aspect types ........................................................................................ 234 8.6. Proxying mechanisms ..................................................................................... 234 Understanding AOP proxies .......................................................................... 235 8.7. Programmatic creation of @AspectJ Proxies .................................................... 238 8.8. Using AspectJ with Spring applications ........................................................... 238 Using AspectJ to dependency inject domain objects with Spring ...................... 238 Unit testing @Configurable objects ....................................................... 241 Working with multiple application contexts ............................................ 241 Other Spring aspects for AspectJ ................................................................... 242 Configuring AspectJ aspects using Spring IoC ................................................ 242 Load-time weaving with AspectJ in the Spring Framework ............................. 243 A first example ..................................................................................... 244 Aspects ................................................................................................ 247 'META-INF/aop.xml' ............................................................................ 247 Required libraries (JARS) ..................................................................... 247 Spring configuration ............................................................................. 248 Environment-specific configuration ....................................................... 250 8.9. Further Resources .......................................................................................... 253 9. Spring AOP APIs ...................................................................................................... 254 9.1. Introduction ................................................................................................... 254 9.2. Pointcut API in Spring .................................................................................... 254 Concepts ...................................................................................................... 254 Operations on pointcuts ................................................................................. 255 AspectJ expression pointcuts ......................................................................... 255 Convenience pointcut implementations .......................................................... 255 Static pointcuts ..................................................................................... 256 Dynamic pointcuts ................................................................................ 257 Pointcut superclasses .................................................................................... 257 Custom pointcuts .......................................................................................... 258 9.3. Advice API in Spring ..................................................................................... 258 Advice lifecycles .......................................................................................... 258 Advice types in Spring .................................................................................. 258 Interception around advice .................................................................... 258 Before advice ....................................................................................... 259 Throws advice ...................................................................................... 260 After Returning advice .......................................................................... 261 Introduction advice ............................................................................... 262 9.4. Advisor API in Spring .................................................................................... 265 9.5. Using the ProxyFactoryBean to create AOP proxies ......................................... 265 Basics .......................................................................................................... 265 JavaBean properties ...................................................................................... 266 JDK- and CGLIB-based proxies .................................................................... 267 Proxying interfaces ....................................................................................... 268 Proxying classes ........................................................................................... 270 Using 'global' advisors .................................................................................. 270 Spring Framework 3.1 Reference Documentation ix 9.6. Concise proxy definitions ............................................................................... 271 9.7. Creating AOP proxies programmatically with the ProxyFactory ........................ 272 9.8. Manipulating advised objects .......................................................................... 272 9.9. Using the "autoproxy" facility ......................................................................... 274 Autoproxy bean definitions ........................................................................... 274 BeanNameAutoProxyCreator ................................................................ 274 DefaultAdvisorAutoProxyCreator .......................................................... 275 AbstractAdvisorAutoProxyCreator ........................................................ 276 Using metadata-driven auto-proxying ............................................................ 276 9.10. Using TargetSources .................................................................................... 278 Hot swappable target sources ......................................................................... 279 Pooling target sources ................................................................................... 280 Prototype target sources ................................................................................ 281 ThreadLocal target sources ............................................................................ 281 9.11. Defining new Advice types ........................................................................... 282 9.12. Further resources .......................................................................................... 282 10. Testing ................................................................................................................... 28310.1. Introduction to Spring Testing ....................................................................... 283 10.2. Unit Testing ................................................................................................. 283 Mock Objects ............................................................................................... 283 JNDI .................................................................................................... 283 Servlet API .......................................................................................... 283 Portlet API ........................................................................................... 284 Unit Testing support Classes ......................................................................... 284 General utilities .................................................................................... 284 Spring MVC ......................................................................................... 284 10.3. Integration Testing ....................................................................................... 284 Overview ..................................................................................................... 284 Goals of Integration Testing .......................................................................... 285 Context management and caching .......................................................... 286 Dependency Injection of test fixtures ..................................................... 286 Transaction management ....................................................................... 287 Support classes for integration testing .................................................... 287 JDBC Testing Support .................................................................................. 288 Annotations .................................................................................................. 288 Spring Testing Annotations ................................................................... 288 Standard Annotation Support ................................................................. 292 Spring JUnit Testing Annotations .......................................................... 292 Spring TestContext Framework ..................................................................... 294 Key abstractions ................................................................................... 294 Context management ............................................................................ 295 Dependency injection of test fixtures ..................................................... 303 Transaction management ....................................................................... 306 TestContext support classes ................................................................... 308 PetClinic Example ........................................................................................ 310 Spring Framework 3.1 Reference Documentation x 10.4. Further Resources ......................................................................................... 312 IV. Data Access .................................................................................................................... 313 11. Transaction Management ......................................................................................... 314 11.1. Introduction to Spring Framework transaction management ............................ 314 11.2. Advantages of the Spring Framework's transaction support model ................... 314 Global transactions ....................................................................................... 315 Local transactions ......................................................................................... 315 Spring Framework's consistent programming model ....................................... 315 11.3. Understanding the Spring Framework transaction abstraction .......................... 316 11.4. Synchronizing resources with transactions ..................................................... 320 High-level synchronization approach ............................................................. 320 Low-level synchronization approach .............................................................. 320 TransactionAwareDataSourceProxy ............................................................... 321 11.5. Declarative transaction management .............................................................. 321 Understanding the Spring Framework's declarative transaction implementation 323 Example of declarative transaction implementation ......................................... 324 Rolling back a declarative transaction ............................................................ 328 Configuring different transactional semantics for different beans ..................... 329 <tx:advice/> settings ..................................................................................... 331 Using @Transactional ................................................................................... 332 @Transactional settings ........................................................................ 336 Multiple Transaction Managers with @Transactional .............................. 337 Custom shortcut annotations .................................................................. 338 Transaction propagation ................................................................................ 338 Required .............................................................................................. 339 RequiresNew ........................................................................................ 339 Nested ................................................................................................. 340 Advising transactional operations .................................................................. 340 Using @Transactional with AspectJ ............................................................... 343 11.6. Programmatic transaction management .......................................................... 344 Using the TransactionTemplate ..................................................................... 344 Specifying transaction settings ............................................................... 345 Using the PlatformTransactionManager ......................................................... 346 11.7. Choosing between programmatic and declarative transaction management ....... 347 11.8. Application server-specific integration ........................................................... 347 IBM WebSphere ........................................................................................... 348 BEA WebLogic Server ................................................................................. 348 Oracle OC4J ................................................................................................. 348 11.9. Solutions to common problems ..................................................................... 348 Use of the wrong transaction manager for a specific DataSource ...................... 348 11.10. Further Resources ....................................................................................... 348 12. DAO support .......................................................................................................... 350 12.1. Introduction ................................................................................................. 350 12.2. Consistent exception hierarchy ...................................................................... 350 12.3. Annotations used for configuring DAO or Repository classes .......................... 351 Spring Framework 3.1 Reference Documentation xi 13. Data access with JDBC ............................................................................................ 353 13.1. Introduction to Spring Framework JDBC ....................................................... 353 Choosing an approach forJDBC database access ............................................ 353 Package hierarchy ......................................................................................... 354 13.2. Using the JDBC core classes to control basic JDBC processing and error handling ............................................................................................................................. 355 JdbcTemplate ............................................................................................... 355 Examples of JdbcTemplate class usage .................................................. 356 JdbcTemplate best practices .................................................................. 358 NamedParameterJdbcTemplate ...................................................................... 359 SimpleJdbcTemplate ..................................................................................... 361 SQLExceptionTranslator ............................................................................... 363 Executing statements .................................................................................... 364 Running queries ........................................................................................... 365 Updating the database ................................................................................... 366 Retrieving auto-generated keys ...................................................................... 366 13.3. Controlling database connections .................................................................. 367 DataSource .................................................................................................. 367 DataSourceUtils ........................................................................................... 368 SmartDataSource .......................................................................................... 368 AbstractDataSource ...................................................................................... 369 SingleConnectionDataSource ........................................................................ 369 DriverManagerDataSource ............................................................................ 369 TransactionAwareDataSourceProxy ............................................................... 369 DataSourceTransactionManager .................................................................... 370 NativeJdbcExtractor ..................................................................................... 370 13.4. JDBC batch operations ................................................................................. 371 Basic batch operations with the JdbcTemplate ................................................ 371 Batch operations with a List of objects ........................................................... 372 Batch operations with multiple batches .......................................................... 373 13.5. Simplifying JDBC operations with the SimpleJdbc classes .............................. 374 Inserting data using SimpleJdbcInsert ............................................................ 374 Retrieving auto-generated keys using SimpleJdbcInsert ................................... 375 Specifying columns for a SimpleJdbcInsert .................................................... 375 Using SqlParameterSource to provide parameter values .................................. 376 Calling a stored procedure with SimpleJdbcCall ............................................. 377 Explicitly declaring parameters to use for a SimpleJdbcCall ............................ 379 How to define SqlParameters ......................................................................... 380 Calling a stored function using SimpleJdbcCall .............................................. 380 Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................. 381 13.6. Modeling JDBC operations as Java objects .................................................... 382 SqlQuery ...................................................................................................... 383 MappingSqlQuery ........................................................................................ 383 SqlUpdate .................................................................................................... 384 StoredProcedure ........................................................................................... 385 Spring Framework 3.1 Reference Documentation xii 13.7. Common problems with parameter and data value handling ............................ 388 Providing SQL type information for parameters .............................................. 388 Handling BLOB and CLOB objects ............................................................... 388 Passing in lists of values for IN clause ........................................................... 390 Handling complex types for stored procedure calls ......................................... 390 13.8. Embedded database support .......................................................................... 392 Why use an embedded database? ................................................................... 392 Creating an embedded database instance using Spring XML ........................... 392 Creating an embedded database instance programmatically ............................. 392 Extending the embedded database support ...................................................... 392 Using HSQL ................................................................................................ 393 Using H2 ..................................................................................................... 393 Using Derby ................................................................................................. 393 Testing data access logic with an embedded database ...................................... 393 13.9. Initializing a DataSource ............................................................................... 394 Initializing a database instance using Spring XML .......................................... 394 Initialization of Other Components that Depend on the Database ............. 395 14. Object Relational Mapping (ORM) Data Access ....................................................... 397 14.1. Introduction to ORM with Spring .................................................................. 397 14.2. General ORM integration considerations ........................................................ 398 Resource and transaction management ........................................................... 398 Exception translation .................................................................................... 399 14.3. Hibernate ..................................................................................................... 400 SessionFactory setup in a Spring container ..................................................... 400 Implementing DAOs based on plain Hibernate 3 API ...................................... 401 Declarative transaction demarcation ............................................................... 402 Programmatic transaction demarcation ........................................................... 404 Transaction management strategies ................................................................ 405 Comparing container-managed and locally defined resources .......................... 407 Spurious application server warnings with Hibernate ...................................... 408 14.4. JDO ............................................................................................................. 409 PersistenceManagerFactory setup .................................................................. 409 Implementing DAOs based on the plain JDO API ........................................... 410 Transaction management ............................................................................... 412 JdoDialect ....................................................................................................413 14.5. JPA ............................................................................................................. 414 Three options for JPA setup in a Spring environment ...................................... 414 LocalEntityManagerFactoryBean ........................................................... 414 Obtaining an EntityManagerFactory from JNDI ...................................... 415 LocalContainerEntityManagerFactoryBean ............................................ 415 Dealing with multiple persistence units .................................................. 418 Implementing DAOs based on plain JPA ........................................................ 418 Transaction Management .............................................................................. 421 JpaDialect .................................................................................................... 422 14.6. iBATIS SQL Maps ....................................................................................... 422 Spring Framework 3.1 Reference Documentation xiii Setting up the SqlMapClient .......................................................................... 422 Using SqlMapClientTemplate and SqlMapClientDaoSupport .......................... 424 Implementing DAOs based on plain iBATIS API ........................................... 425 15. Marshalling XML using O/X Mappers ..................................................................... 426 15.1. Introduction ................................................................................................. 426 15.2. Marshaller and Unmarshaller ........................................................................ 426 Marshaller .................................................................................................... 426 Unmarshaller ................................................................................................ 427 XmlMappingException ................................................................................. 428 15.3. Using Marshaller and Unmarshaller ............................................................... 428 15.4. XML Schema-based Configuration ................................................................ 430 15.5. JAXB .......................................................................................................... 431 Jaxb2Marshaller ........................................................................................... 431 XML Schema-based Configuration ........................................................ 431 15.6. Castor .......................................................................................................... 432 CastorMarshaller .......................................................................................... 432 Mapping ...................................................................................................... 432 15.7. XMLBeans .................................................................................................. 433 XmlBeansMarshaller .................................................................................... 433 XML Schema-based Configuration ........................................................ 433 15.8. JiBX ............................................................................................................ 434 JibxMarshaller .............................................................................................. 434 XML Schema-based Configuration ........................................................ 434 15.9. XStream ...................................................................................................... 435 XStreamMarshaller ....................................................................................... 435 V. The Web .......................................................................................................................... 437 16. Web MVC framework ............................................................................................. 438 16.1. Introduction to Spring Web MVC framework ................................................. 438 Features of Spring Web MVC ....................................................................... 439 Pluggability of other MVC implementations ................................................... 440 16.2. The DispatcherServlet .................................................................................. 440 Special Bean Types In the WebApplicationContext ........................................ 443 Default DispatcherServlet Configuration ........................................................ 444 DispatcherServlet Processing Sequence .......................................................... 444 16.3. Implementing Controllers ............................................................................. 446 Defining a controller with @Controller .......................................................... 447 Mapping Requests With @RequestMapping ................................................... 447 New Support Classes for @RequestMapping methods in Spring MVC 3.1 449 URI Template Patterns .......................................................................... 450 URI Template Patterns with Regular Expressions ................................... 451 Path Patterns ........................................................................................ 452 Consumable Media Types ..................................................................... 452 Producible Media Types ........................................................................ 452 Request Parameters and Header Values .................................................. 453 Defining @RequestMapping handler methods ................................................ 453 Spring Framework 3.1 Reference Documentation xiv Supported method argument types ......................................................... 454 Supported method return types .............................................................. 456 Binding request parameters to method parameters with @RequestParam .. 457 Mapping the request body with the @RequestBody annotation ................ 457 Mapping the response body with the @ResponseBody annotation ........... 458 Using HttpEntity<?> ............................................................................. 459 Using @ModelAttribute on a method ..................................................... 459 Using @ModelAttribute on a method argument ...................................... 460 Using @SessionAttributes to store model attributes in the HTTP session between requests .................................................................................. 462 Specifying redirect and flash attributes ................................................... 463 Working with "application/x-www-form-urlencoded" data ...................... 463 Mapping cookie values with the @CookieValue annotation .................... 464 Mapping request header attributes with the @RequestHeader annotation .. 465 Method Parameters And Type Conversion ............................................. 465 Customizing WebDataBinder initialization ............................................. 465 Support for the 'Last-Modified' Response Header To Facilitate Content Caching ............................................................................................... 467 16.4. Handler mappings ........................................................................................ 467 Intercepting requests with a HandlerInterceptor .............................................. 468 16.5. Resolving views ........................................................................................... 470 Resolving views with the ViewResolver interface ........................................... 470 Chaining ViewResolvers ............................................................................... 472 Redirecting to views .....................................................................................473 RedirectView ....................................................................................... 473 The redirect: prefix ............................................................................... 474 The forward: prefix ............................................................................... 474 ContentNegotiatingViewResolver .................................................................. 474 16.6. Using flash attributes .................................................................................... 477 16.7. Building URIs .............................................................................................. 478 16.8. Using locales ............................................................................................... 479 AcceptHeaderLocaleResolver ........................................................................ 479 CookieLocaleResolver .................................................................................. 479 SessionLocaleResolver ................................................................................. 480 LocaleChangeInterceptor .............................................................................. 480 16.9. Using themes ............................................................................................... 481 Overview of themes ...................................................................................... 481 Defining themes ........................................................................................... 481 Theme resolvers ........................................................................................... 482 16.10. Spring's multipart (file upload) support ........................................................ 482 Introduction ................................................................................................. 482 Using a MultipartResolver with Commons FileUpload .................................... 482 Using a MultipartResolver with Servlet 3.0 .................................................... 483 Handling a file upload in a form .................................................................... 483 Handling a file upload request from programmatic clients ............................... 484 Spring Framework 3.1 Reference Documentation xv 16.11. Handling exceptions ................................................................................... 485 HandlerExceptionResolver ............................................................................ 485 @ExceptionHandler ...................................................................................... 486 16.12. Convention over configuration support ........................................................ 487 The Controller ControllerClassNameHandlerMapping .................................... 487 The Model ModelMap (ModelAndView) ....................................................... 488 The View - RequestToViewNameTranslator .................................................. 490 16.13. ETag support .............................................................................................. 491 16.14. Configuring Spring MVC ............................................................................ 492 Enabling MVC Java Config or the MVC XML Namespace ............................. 492 Customizing the Provided Configuration ........................................................ 493 Configuring Interceptors ............................................................................... 494 Configuring View Controllers ....................................................................... 495 Configuring Serving of Resources ................................................................. 495 mvc:default-servlet-handler ........................................................................... 497 More Spring Web MVC Resources ................................................................ 498 Advanced Customizations with MVC Java Config .......................................... 499 Advanced Customizations with the MVC Namespace ..................................... 499 17. View technologies ................................................................................................... 501 17.1. Introduction ................................................................................................. 501 17.2. JSP & JSTL ................................................................................................. 501 View resolvers ............................................................................................. 501 'Plain-old' JSPs versus JSTL .......................................................................... 502 Additional tags facilitating development ........................................................ 502 Using Spring's form tag library ...................................................................... 502 Configuration ....................................................................................... 502 The form tag ........................................................................................ 503 The input tag ........................................................................................ 504 The checkbox tag .................................................................................. 504 The checkboxes tag .............................................................................. 506 The radiobutton tag ............................................................................... 506 The radiobuttons tag ............................................................................. 507 The password tag .................................................................................. 507 The select tag ....................................................................................... 507 The option tag ...................................................................................... 508 The options tag ..................................................................................... 508 The textarea tag .................................................................................... 509 The hidden tag ...................................................................................... 509 The errors tag ....................................................................................... 510 HTTP Method Conversion .................................................................... 512 HTML5 Tags ....................................................................................... 512 17.3. Tiles ............................................................................................................ 513 Dependencies ............................................................................................... 513 How to integrate Tiles ................................................................................... 513 UrlBasedViewResolver ......................................................................... 514 Spring Framework 3.1 Reference Documentation xvi ResourceBundleViewResolver .............................................................. 514 SimpleSpringPreparerFactory and SpringBeanPreparerFactory ................ 514 17.4. Velocity & FreeMarker ................................................................................. 515 Dependencies ............................................................................................... 515 Context configuration ................................................................................... 515 Creating templates ........................................................................................ 516 Advanced configuration ................................................................................ 516 velocity.properties ................................................................................ 517 FreeMarker ..........................................................................................517 Bind support and form handling ..................................................................... 517 The bind macros ................................................................................... 518 Simple binding ..................................................................................... 518 Form input generation macros ............................................................... 519 HTML escaping and XHTML compliance ............................................. 523 17.5. XSLT .......................................................................................................... 524 My First Words ............................................................................................ 524 Bean definitions ................................................................................... 524 Standard MVC controller code .............................................................. 524 Convert the model data to XML ............................................................ 525 Defining the view properties .................................................................. 526 Document transformation ...................................................................... 526 Summary ..................................................................................................... 526 17.6. Document views (PDF/Excel) ....................................................................... 527 Introduction ................................................................................................. 527 Configuration and setup ................................................................................ 527 Document view definitions .................................................................... 527 Controller code ..................................................................................... 528 Subclassing for Excel views .................................................................. 528 Subclassing for PDF views .................................................................... 529 17.7. JasperReports ............................................................................................... 530 Dependencies ............................................................................................... 530 Configuration ............................................................................................... 530 Configuring the ViewResolver .............................................................. 531 Configuring the Views .......................................................................... 531 About Report Files ............................................................................... 531 Using JasperReportsMultiFormatView ................................................... 532 Populating the ModelAndView ...................................................................... 533 Working with Sub-Reports ............................................................................ 533 Configuring Sub-Report Files ................................................................ 534 Configuring Sub-Report Data Sources ................................................... 534 Configuring Exporter Parameters ................................................................... 535 17.8. Feed Views .................................................................................................. 535 17.9. XML Marshalling View ................................................................................ 536 17.10. JSON Mapping View .................................................................................. 536 18. Integrating with other web frameworks ..................................................................... 538 Spring Framework 3.1 Reference Documentation xvii 18.1. Introduction ................................................................................................. 538 18.2. Common configuration ................................................................................. 539 18.3. JavaServer Faces 1.1 and 1.2 ......................................................................... 540 DelegatingVariableResolver (JSF 1.1/1.2) ...................................................... 540 SpringBeanVariableResolver (JSF 1.1/1.2) ..................................................... 541 SpringBeanFacesELResolver (JSF 1.2+) ........................................................ 541 FacesContextUtils ........................................................................................ 542 18.4. Apache Struts 1.x and 2.x ............................................................................. 542 ContextLoaderPlugin .................................................................................... 543 DelegatingRequestProcessor ................................................................. 544 DelegatingActionProxy ......................................................................... 544 ActionSupport Classes .................................................................................. 545 18.5. WebWork 2.x ............................................................................................... 545 18.6. Tapestry 3.x and 4.x ..................................................................................... 546 Injecting Spring-managed beans .................................................................... 547 Dependency Injecting Spring Beans into Tapestry pages ......................... 548 Component definition files .................................................................... 549 Adding abstract accessors ...................................................................... 550 Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style ............................................................................................................. 552 18.7. Further Resources ......................................................................................... 553 19. Portlet MVC Framework ......................................................................................... 554 19.1. Introduction ................................................................................................. 554 Controllers - The C in MVC .......................................................................... 555 Views - The V in MVC ................................................................................. 555 Web-scoped beans ........................................................................................ 556 19.2. The DispatcherPortlet ................................................................................... 556 19.3. The ViewRendererServlet ............................................................................. 558 19.4. Controllers ................................................................................................... 559 AbstractController and PortletContentGenerator ............................................. 559 Other simple controllers ................................................................................ 561 Command Controllers ................................................................................... 561 PortletWrappingController ............................................................................ 562 19.5. Handler mappings ........................................................................................ 562 PortletModeHandlerMapping ........................................................................ 563 ParameterHandlerMapping ............................................................................ 564 PortletModeParameterHandlerMapping ......................................................... 564 Adding HandlerInterceptors .......................................................................... 565 HandlerInterceptorAdapter ............................................................................ 565 ParameterMappingInterceptor