791
Reference Documentation 3.0 Copyright © 2004-2010 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 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 Reference

Embed Size (px)

Citation preview

Reference Documentation

3.0Copyright 2004-2010 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

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.0 ...................................................................................................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 III. Core Technologies ............................................................................................................23 3. The IoC container .......................................................................................................24

3.0

Reference Documentation

ii

Spring Framework

3.1. Introduction to the Spring IoC container and beans .............................................24 3.2. Container overview ..........................................................................................24 Configuration metadata ...................................................................................25 Instantiating a container ..................................................................................26 Composing XML-based configuration metadata .......................................28 Using the container .........................................................................................28 3.3. Bean overview .................................................................................................29 Naming beans .................................................................................................30 Aliasing a bean outside the bean definition ...............................................31 Instantiating beans ..........................................................................................32 Instantiation with a constructor ................................................................32 Instantiation with a static factory method .................................................33 Instantiation using an instance factory method ..........................................33 3.4. Dependencies ...................................................................................................35 Dependency injection ......................................................................................35 Constructor-based dependency injection ...................................................35 Setter-based dependency injection ...........................................................37 Dependency resolution process ................................................................38 Examples of dependency injection ...........................................................40 Dependencies and configuration in detail .........................................................42 Straight values (primitives, Strings, and so on) .........................................42 References to other beans (collaborators) .................................................43 Inner beans .............................................................................................44 Collections .............................................................................................45 Null and empty string values ...................................................................47 XML shortcut with the p-namespace ........................................................48 Compound property names ......................................................................49 Using depends-on ...........................................................................................49 Lazy-initialized beans .....................................................................................50 Autowiring collaborators .................................................................................50 Limitations and disadvantages of autowiring ............................................52 Excluding a bean from autowiring ...........................................................52 Method injection ............................................................................................53 Lookup method injection .........................................................................54 Arbitrary method replacement .................................................................55 3.5. Bean scopes .....................................................................................................56 The singleton scope ........................................................................................57 The prototype scope ........................................................................................58 Singleton beans with prototype-bean dependencies ...........................................59 Request, session, and global session scopes ......................................................59 Initial web configuration .........................................................................59 Request scope .........................................................................................60 Session scope .........................................................................................60 Global session scope ...............................................................................61 Scoped beans as dependencies .................................................................61 3.0 Reference Documentation iii

Spring Framework

Custom scopes ...............................................................................................63 Creating a custom scope ..........................................................................63 Using a custom scope ..............................................................................64 3.6. Customizing the nature of a bean .......................................................................65 Lifecycle callbacks .........................................................................................66 Initialization callbacks ............................................................................66 Destruction callbacks ..............................................................................67 Default initialization and destroy methods ................................................67 Combining lifecycle mechanisms ............................................................69 Startup and shutdown callbacks ...............................................................69 Shutting down the Spring IoC container gracefully in non-web applications 71 ApplicationContextAware and BeanNameAware ..............................................72 Other Aware interfaces ...................................................................................72 3.7. Bean definition inheritance ...............................................................................74 3.8. Container extension points ................................................................................76 Customizing beans using the BeanPostProcessor Interface ................................76 Example: Hello World, BeanPostProcessor-style ......................................77 Example: The RequiredAnnotationBeanPostProcessor ..............................78 Customizing configuration metadata with BeanFactoryPostProcessor interface ...79 Example: the PropertyPlaceholderConfigurer ...........................................80 Example: the PropertyOverrideConfigurer ...............................................81 Customizing instantiation logic with the FactoryBean Interface .........................82 3.9. Annotation-based container configuration ..........................................................83 @Required .....................................................................................................84 @Autowired and @Inject ................................................................................85 Fine-tuning annotation-based autowiring with qualifiers ...................................87 CustomAutowireConfigurer ............................................................................93 @Resource .....................................................................................................93 @PostConstruct and @PreDestroy ...................................................................94 3.10. Classpath scanning and managed components ..................................................95 @Component and further stereotype annotations ..............................................95 Automatically detecting classes and registering bean definitions ........................96 Using filters to customize scanning ..................................................................97 Defining bean metadata within components ......................................................98 Naming autodetected components ....................................................................99 Providing a scope for autodetected components .............................................. 100 Providing qualifier metadata with annotations ................................................ 101 3.11. Java-based container configuration ................................................................ 102 Basic concepts: @Configuration and @Bean .................................................. 102 Instantiating the Spring container using AnnotationConfigApplicationContext . 102 Simple construction .............................................................................. 103 Building the container programmatically using register(Class...) ........ 103 Enabling component scanning with scan(String...) .................................. 104 Support for web applications with AnnotationConfigWebApplicationContext ............................................................................................................. 104 3.0 Reference Documentation iv

Spring Framework

Composing Java-based configurations ............................................................ 105 Using the @Import annotation ............................................................... 105 Combining Java and XML configuration ................................................ 108 Using the @Bean annotation ......................................................................... 110 Declaring a bean ................................................................................... 110 Injecting dependencies .......................................................................... 111 Receiving lifecycle callbacks ................................................................. 111 Specifying bean scope ........................................................................... 112 Customizing bean naming ..................................................................... 114 Bean aliasing ........................................................................................ 114 Further information about how Java-based configuration works internally ........ 114 3.12. Registering a LoadTimeWeaver .................................................................... 115 3.13. Additional Capabilities of the ApplicationContext .......................................... 116 Internationalization using MessageSource ...................................................... 116 Standard and Custom Events ......................................................................... 119 Convenient access to low-level resources ....................................................... 122 Convenient ApplicationContext instantiation for web applications ................... 123 Deploying a Spring ApplicationContext as a J2EE RAR file ............................ 124 3.14. The BeanFactory .......................................................................................... 125 BeanFactory or ApplicationContext? ............................................................. 125 Glue code and the evil singleton .................................................................... 126 4. Resources ................................................................................................................. 128 4.1. Introduction ................................................................................................... 128 4.2. The Resource interface ................................................................................... 128 4.3. Built-in Resource implementations .................................................................. 129 UrlResource ................................................................................................. 129 ClassPathResource ....................................................................................... 130 FileSystemResource ..................................................................................... 130 ServletContextResource ................................................................................ 130 InputStreamResource .................................................................................... 130 ByteArrayResource ...................................................................................... 131 4.4. The ResourceLoader ....................................................................................... 131 4.5. The ResourceLoaderAware interface ............................................................... 132 4.6. Resources as dependencies ............................................................................. 133 4.7. Application contexts and Resource paths ......................................................... 133 Constructing application contexts .................................................................. 133 Constructing ClassPathXmlApplicationContext instances - shortcuts ....... 134 Wildcards in application context constructor resource paths ............................ 135 Ant-style Patterns ................................................................................. 135 The classpath*: prefix ........................................................................... 136 Other notes relating to wildcards ............................................................ 136 FileSystemResource caveats .......................................................................... 137 5. Validation, Data Binding, and Type Conversion .......................................................... 139 5.1. Introduction ................................................................................................... 139 5.2. Validation using Spring's Validator interface .................................................... 139 3.0 Reference Documentation v

Spring Framework

5.3. Resolving codes to error messages .................................................................. 141 5.4. Bean manipulation and the BeanWrapper ........................................................ 141 Setting and getting basic and nested properties ............................................... 142 Built-in PropertyEditor implementations ........................................................ 143 Registering additional custom PropertyEditors ....................................... 146 5.5. Spring 3 Type Conversion .............................................................................. 149 Converter SPI ............................................................................................... 149 ConverterFactory .......................................................................................... 150 GenericConverter ......................................................................................... 151 ConditionalGenericConverter ................................................................ 151 ConversionService API ................................................................................. 152 Configuring a ConversionService .................................................................. 152 Using a ConversionService programatically ................................................... 153 5.6. Spring 3 Field Formatting ............................................................................... 153 Formatter SPI ............................................................................................... 154 Annotation-driven Formatting ....................................................................... 155 Format Annotation API ......................................................................... 156 FormatterRegistry SPI .................................................................................. 157 Configuring Formatting in Spring MVC ......................................................... 157 5.7. Spring 3 Validation ........................................................................................ 158 Overview of the JSR-303 Bean Validation API ............................................... 158 Configuring a Bean Validation Implementation .............................................. 159 Injecting a Validator ............................................................................. 159 Configuring Custom Constraints ............................................................ 160 Additional Configuration Options .......................................................... 161 Configuring a DataBinder ............................................................................. 161 Spring MVC 3 Validation ............................................................................. 161 Triggering @Controller Input Validation ............................................... 161 Configuring a Validator for use by Spring MVC ..................................... 162 Configuring a JSR-303 Validator for use by Spring MVC ....................... 162 6. Spring Expression Language (SpEL) .......................................................................... 164 6.1. Introduction ................................................................................................... 164 6.2. Feature Overview ........................................................................................... 164 6.3. Expression Evaluation using Spring's Expression Interface ............................... 165 The EvaluationContext interface .................................................................... 168 Type Conversion .................................................................................. 168 6.4. Expression support for defining bean definitions .............................................. 169 XML based configuration ............................................................................. 169 Annotation-based configuration ..................................................................... 169 6.5. Language Reference ....................................................................................... 171 Literal expressions ........................................................................................ 171 Properties, Arrays, Lists, Maps, Indexers ........................................................ 171 Inline lists .................................................................................................... 172 Array construction ........................................................................................ 172 Methods ....................................................................................................... 173 3.0 Reference Documentation vi

Spring Framework

Operators ..................................................................................................... 173 Relational operators .............................................................................. 173 Logical operators .................................................................................. 174 Mathematical operators ......................................................................... 174 Assignment .................................................................................................. 175 Types ........................................................................................................... 175 Constructors ................................................................................................. 175 Variables ...................................................................................................... 176 The #this and #root variables ................................................................. 176 Functions ..................................................................................................... 176 Bean references ............................................................................................ 177 Ternary Operator (If-Then-Else) .................................................................... 177 The Elvis Operator ....................................................................................... 178 Safe Navigation operator ............................................................................... 178 Collection Selection ...................................................................................... 179 Collection Projection .................................................................................... 179 Expression templating ................................................................................... 179 6.6. Classes used in the examples ........................................................................... 180 7. Aspect Oriented Programming with Spring ................................................................. 183 7.1. Introduction ................................................................................................... 183 AOP concepts ............................................................................................... 183 Spring AOP capabilities and goals ................................................................. 185 AOP Proxies ................................................................................................ 186 7.2. @AspectJ support .......................................................................................... 187 Enabling @AspectJ Support .......................................................................... 187 Declaring an aspect ....................................................................................... 187 Declaring a pointcut ...................................................................................... 188 Supported Pointcut Designators ............................................................. 189 Combining pointcut expressions ............................................................ 191 Sharing common pointcut definitions ..................................................... 191 Examples ............................................................................................. 192 Writing good pointcuts .......................................................................... 195 Declaring advice ........................................................................................... 196 Before advice ....................................................................................... 196 After returning advice ........................................................................... 196 After throwing advice ........................................................................... 197 After (finally) advice ............................................................................ 198 Around advice ...................................................................................... 198 Advice parameters ................................................................................ 199 Advice ordering .................................................................................... 203 Introductions ................................................................................................ 203 Aspect instantiation models ........................................................................... 204 Example ....................................................................................................... 205 7.3. Schema-based AOP support ............................................................................ 206 Declaring an aspect ....................................................................................... 207 3.0 Reference Documentation vii

Spring Framework

Declaring a pointcut ...................................................................................... 207 Declaring advice ........................................................................................... 209 Before advice ....................................................................................... 209 After returning advice ........................................................................... 210 After throwing advice ........................................................................... 210 After (finally) advice ............................................................................ 211 Around advice ...................................................................................... 211 Advice parameters ................................................................................ 212 Advice ordering .................................................................................... 214 Introductions ................................................................................................ 214 Aspect instantiation models ........................................................................... 215 Advisors ...................................................................................................... 215 Example ....................................................................................................... 215 7.4. Choosing which AOP declaration style to use .................................................. 217 Spring AOP or full AspectJ? ......................................................................... 217 @AspectJ or XML for Spring AOP? .............................................................. 218 7.5. Mixing aspect types ........................................................................................ 219 7.6. Proxying mechanisms ..................................................................................... 219 Understanding AOP proxies .......................................................................... 220 7.7. Programmatic creation of @AspectJ Proxies .................................................... 222 7.8. Using AspectJ with Spring applications ........................................................... 222 Using AspectJ to dependency inject domain objects with Spring ...................... 223 Unit testing @Configurable objects ....................................................... 225 Working with multiple application contexts ............................................ 226 Other Spring aspects for AspectJ ................................................................... 226 Configuring AspectJ aspects using Spring IoC ................................................ 227 Load-time weaving with AspectJ in the Spring Framework ............................. 228 A first example ..................................................................................... 228 Aspects ................................................................................................ 231 'META-INF/aop.xml' ............................................................................ 232 Required libraries (JARS) ..................................................................... 232 Spring configuration ............................................................................. 232 Environment-specific configuration ....................................................... 235 7.9. Further Resources .......................................................................................... 237 8. Spring AOP APIs ...................................................................................................... 239 8.1. Introduction ................................................................................................... 239 8.2. Pointcut API in Spring .................................................................................... 239 Concepts ...................................................................................................... 239 Operations on pointcuts ................................................................................. 240 AspectJ expression pointcuts ......................................................................... 240 Convenience pointcut implementations .......................................................... 240 Static pointcuts ..................................................................................... 241 Dynamic pointcuts ................................................................................ 242 Pointcut superclasses .................................................................................... 242 Custom pointcuts .......................................................................................... 243 3.0 Reference Documentation viii

Spring Framework

8.3. Advice API in Spring ..................................................................................... 243 Advice lifecycles .......................................................................................... 243 Advice types in Spring .................................................................................. 243 Interception around advice .................................................................... 243 Before advice ....................................................................................... 244 Throws advice ...................................................................................... 245 After Returning advice .......................................................................... 246 Introduction advice ............................................................................... 247 8.4. Advisor API in Spring .................................................................................... 250 8.5. Using the ProxyFactoryBean to create AOP proxies ......................................... 250 Basics .......................................................................................................... 250 JavaBean properties ...................................................................................... 251 JDK- and CGLIB-based proxies .................................................................... 252 Proxying interfaces ....................................................................................... 253 Proxying classes ........................................................................................... 255 Using 'global' advisors .................................................................................. 255 8.6. Concise proxy definitions ............................................................................... 256 8.7. Creating AOP proxies programmatically with the ProxyFactory ........................ 257 8.8. Manipulating advised objects .......................................................................... 257 8.9. Using the "autoproxy" facility ......................................................................... 259 Autoproxy bean definitions ........................................................................... 259 BeanNameAutoProxyCreator ................................................................ 259 DefaultAdvisorAutoProxyCreator .......................................................... 260 AbstractAdvisorAutoProxyCreator ........................................................ 261 Using metadata-driven auto-proxying ............................................................ 261 8.10. Using TargetSources .................................................................................... 263 Hot swappable target sources ......................................................................... 264 Pooling target sources ................................................................................... 265 Prototype target sources ................................................................................ 266 ThreadLocal target sources ............................................................................ 266 8.11. Defining new Advice types ........................................................................... 267 8.12. Further resources .......................................................................................... 267 9. Testing ..................................................................................................................... 268 9.1. Introduction to testing ..................................................................................... 268 9.2. Unit testing .................................................................................................... 268 Mock objects ................................................................................................ 268 JNDI .................................................................................................... 268 Servlet API .......................................................................................... 268 Portlet API ........................................................................................... 269 Unit testing support classes ........................................................................... 269 General utilities .................................................................................... 269 Spring MVC ......................................................................................... 269 9.3. Integration testing .......................................................................................... 269 Overview ..................................................................................................... 269 Goals of integration testing ............................................................................ 270 3.0 Reference Documentation ix

Spring Framework

Context management and caching .......................................................... 270 Dependency Injection of test fixtures ..................................................... 271 Transaction management ....................................................................... 271 Support classes for integration testing .................................................... 272 JDBC testing support .................................................................................... 272 Annotations .................................................................................................. 272 Spring TestContext Framework ..................................................................... 278 Key abstractions ................................................................................... 278 Context management and caching .......................................................... 279 Dependency Injection of test fixtures ..................................................... 281 Transaction management ....................................................................... 284 TestContext support classes ................................................................... 286 PetClinic example ......................................................................................... 289 9.4. Further Resources .......................................................................................... 291 IV. Data Access .................................................................................................................... 292 10. Transaction Management ......................................................................................... 293 10.1. Introduction to Spring Framework transaction management ............................ 293 10.2. Advantages of the Spring Framework's transaction support model ................... 293 Global transactions ....................................................................................... 294 Local transactions ......................................................................................... 294 Spring Framework's consistent programming model ....................................... 294 10.3. Understanding the Spring Framework transaction abstraction .......................... 295 10.4. Synchronizing resources with transactions ..................................................... 299 High-level synchronization approach ............................................................. 299 Low-level synchronization approach .............................................................. 299 TransactionAwareDataSourceProxy ............................................................... 300 10.5. Declarative transaction management .............................................................. 300 Understanding the Spring Framework's declarative transaction implementation 302 Example of declarative transaction implementation ......................................... 302 Rolling back a declarative transaction ............................................................ 306 Configuring different transactional semantics for different beans ..................... 307 settings ..................................................................................... 309 Using @Transactional ................................................................................... 310 @Transactional settings ........................................................................ 314 Multiple Transaction Managers with @Transactional .............................. 315 Custom shortcut annotations .................................................................. 316 Transaction propagation ................................................................................ 317 Required .............................................................................................. 317 RequiresNew ........................................................................................ 317 Nested ................................................................................................. 317 Advising transactional operations .................................................................. 318 Using @Transactional with AspectJ ............................................................... 320 10.6. Programmatic transaction management .......................................................... 321 Using the TransactionTemplate ..................................................................... 322 Specifying transaction settings ............................................................... 323 3.0 Reference Documentation x

Spring Framework

Using the PlatformTransactionManager ......................................................... 324 10.7. Choosing between programmatic and declarative transaction management ....... 324 10.8. Application server-specific integration ........................................................... 324 IBM WebSphere ........................................................................................... 325 BEA WebLogic Server ................................................................................. 325 Oracle OC4J ................................................................................................. 325 10.9. Solutions to common problems ..................................................................... 326 Use of the wrong transaction manager for a specific DataSource ...................... 326 10.10. Further Resources ....................................................................................... 326 11. DAO support .......................................................................................................... 327 11.1. Introduction ................................................................................................. 327 11.2. Consistent exception hierarchy ...................................................................... 327 11.3. Annotations used for configuring DAO or Repository classes .......................... 328 12. Data access with JDBC ............................................................................................ 330 12.1. Introduction to Spring Framework JDBC ....................................................... 330 Choosing an approach for JDBC database access ............................................ 330 Package hierarchy ......................................................................................... 331 12.2. Using the JDBC core classes to control basic JDBC processing and error handling ............................................................................................................................. 332 JdbcTemplate ............................................................................................... 332 Examples of JdbcTemplate class usage .................................................. 333 JdbcTemplate best practices .................................................................. 335 NamedParameterJdbcTemplate ...................................................................... 336 SimpleJdbcTemplate ..................................................................................... 338 SQLExceptionTranslator ............................................................................... 340 Executing statements .................................................................................... 341 Running queries ........................................................................................... 342 Updating the database ................................................................................... 343 Retrieving auto-generated keys ...................................................................... 343 12.3. Controlling database connections .................................................................. 344 DataSource .................................................................................................. 344 DataSourceUtils ........................................................................................... 345 SmartDataSource .......................................................................................... 345 AbstractDataSource ...................................................................................... 346 SingleConnectionDataSource ........................................................................ 346 DriverManagerDataSource ............................................................................ 346 TransactionAwareDataSourceProxy ............................................................... 346 DataSourceTransactionManager .................................................................... 347 NativeJdbcExtractor ..................................................................................... 347 12.4. JDBC batch operations ................................................................................. 348 Batch operations with the JdbcTemplate ......................................................... 348 Batch operations with the SimpleJdbcTemplate .............................................. 349 12.5. Simplifying JDBC operations with the SimpleJdbc classes .............................. 350 Inserting data using SimpleJdbcInsert ............................................................ 350 Retrieving auto-generated keys using SimpleJdbcInsert ................................... 351 3.0 Reference Documentation xi

Spring Framework

Specifying columns for a SimpleJdbcInsert .................................................... 351 Using SqlParameterSource to provide parameter values .................................. 352 Calling a stored procedure with SimpleJdbcCall ............................................. 353 Explicitly declaring parameters to use for a SimpleJdbcCall ............................ 355 How to define SqlParameters ......................................................................... 356 Calling a stored function using SimpleJdbcCall .............................................. 356 Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................. 357 12.6. Modeling JDBC operations as Java objects .................................................... 358 SqlQuery ...................................................................................................... 359 MappingSqlQuery ........................................................................................ 359 SqlUpdate .................................................................................................... 360 StoredProcedure ........................................................................................... 361 12.7. Common problems with parameter and data value handling ............................ 364 Providing SQL type information for parameters .............................................. 364 Handling BLOB and CLOB objects ............................................................... 364 Passing in lists of values for IN clause ........................................................... 366 Handling complex types for stored procedure calls ......................................... 366 12.8. Embedded database support .......................................................................... 368 Why use an embedded database? ................................................................... 368 Creating an embedded database instance using Spring XML ........................... 368 Creating an embedded database instance programmatically ............................. 368 Extending the embedded database support ...................................................... 368 Using HSQL ................................................................................................ 369 Using H2 ..................................................................................................... 369 Using Derby ................................................................................................. 369 Testing data access logic with an embedded database ...................................... 369 12.9. Initializing a DataSource ............................................................................... 370 Initializing a database instance using Spring XML .......................................... 370 Initialization of Other Components that Depend on the Database ............. 371 13. Object Relational Mapping (ORM) Data Access ....................................................... 373 13.1. Introduction to ORM with Spring .................................................................. 373 13.2. General ORM integration considerations ........................................................ 374 Resource and transaction management ........................................................... 374 Exception translation .................................................................................... 375 13.3. Hibernate ..................................................................................................... 376 SessionFactory setup in a Spring container ..................................................... 376 Implementing DAOs based on plain Hibernate 3 API ...................................... 377 Declarative transaction demarcation ............................................................... 378 Programmatic transaction demarcation ........................................................... 380 Transaction management strategies ................................................................ 381 Comparing container-managed and locally defined resources .......................... 383 Spurious application server warnings with Hibernate ...................................... 384 13.4. JDO ............................................................................................................. 385 PersistenceManagerFactory setup .................................................................. 385 Implementing DAOs based on the plain JDO API ........................................... 386 3.0 Reference Documentation xii

Spring Framework

Transaction management ............................................................................... 388 JdoDialect .................................................................................................... 389 13.5. JPA ............................................................................................................. 390 Three options for JPA setup in a Spring environment ...................................... 390 LocalEntityManagerFactoryBean ........................................................... 390 Obtaining an EntityManagerFactory from JNDI ...................................... 391 LocalContainerEntityManagerFactoryBean ............................................ 391 Dealing with multiple persistence units .................................................. 394 Implementing DAOs based on plain JPA ........................................................ 394 Transaction Management .............................................................................. 397 JpaDialect .................................................................................................... 398 13.6. iBATIS SQL Maps ....................................................................................... 398 Setting up the SqlMapClient .......................................................................... 398 Using SqlMapClientTemplate and SqlMapClientDaoSupport .......................... 400 Implementing DAOs based on plain iBATIS API ........................................... 401 14. Marshalling XML using O/X Mappers ..................................................................... 402 14.1. Introduction ................................................................................................. 402 14.2. Marshaller and Unmarshaller ........................................................................ 402 Marshaller .................................................................................................... 402 Unmarshaller ................................................................................................ 403 XmlMappingException ................................................................................. 404 14.3. Using Marshaller and Unmarshaller ............................................................... 404 14.4. XML Schema-based Configuration ................................................................ 406 14.5. JAXB .......................................................................................................... 407 Jaxb2Marshaller ........................................................................................... 407 XML Schema-based Configuration ........................................................ 407 14.6. Castor .......................................................................................................... 408 CastorMarshaller .......................................................................................... 408 Mapping ...................................................................................................... 408 14.7. XMLBeans .................................................................................................. 409 XmlBeansMarshaller .................................................................................... 409 XML Schema-based Configuration ........................................................ 409 14.8. JiBX ............................................................................................................ 410 JibxMarshaller .............................................................................................. 410 XML Schema-based Configuration ........................................................ 410 14.9. XStream ...................................................................................................... 411 XStreamMarshaller ....................................................................................... 411 V. The Web .......................................................................................................................... 412 15. Web MVC framework ............................................................................................. 413 15.1. Introduction to Spring Web MVC framework ................................................. 413 Features of Spring Web MVC ....................................................................... 414 Pluggability of other MVC implementations ................................................... 415 15.2. The DispatcherServlet .................................................................................. 415 15.3. Implementing Controllers ............................................................................. 420 Defining a controller with @Controller .......................................................... 420 3.0 Reference Documentation xiii

Spring Framework

Mapping requests with @RequestMapping ..................................................... 421 URI Templates ..................................................................................... 423 Advanced @RequestMapping options .................................................... 424 Supported handler method arguments and return types ............................ 425 Binding request parameters to method parameters with @RequestParam .. 428 Mapping the request body with the @RequestBody annotation ................ 429 Mapping the response body with the @ResponseBody annotation ........... 430 Using HttpEntity ............................................................................. 430 Providing a link to data from the model with @ModelAttribute ............... 430 Specifying attributes to store in a session with @SessionAttributes .......... 431 Mapping cookie values with the @CookieValue annotation .................... 432 Mapping request header attributes with the @RequestHeader annotation .. 432 Customizing WebDataBinder initialization ............................................. 433 15.4. Handler mappings ........................................................................................ 434 Intercepting requests - the HandlerInterceptor interface ................................... 435 15.5. Resolving views ........................................................................................... 436 Resolving views with the ViewResolver interface ........................................... 437 Chaining ViewResolvers ............................................................................... 438 Redirecting to views ..................................................................................... 439 RedirectView ....................................................................................... 440 The redirect: prefix ............................................................................... 440 The forward: prefix ............................................................................... 441 ContentNegotiatingViewResolver .................................................................. 441 15.6. Using locales ............................................................................................... 443 AcceptHeaderLocaleResolver ........................................................................ 444 CookieLocaleResolver .................................................................................. 444 SessionLocaleResolver ................................................................................. 444 LocaleChangeInterceptor .............................................................................. 445 15.7. Using themes ............................................................................................... 445 Overview of themes ...................................................................................... 445 Defining themes ........................................................................................... 445 Theme resolvers ........................................................................................... 446 15.8. Spring's multipart (fileupload) support ........................................................... 447 Introduction ................................................................................................. 447 Using the MultipartResolver .......................................................................... 447 Handling a file upload in a form .................................................................... 447 15.9. Handling exceptions ..................................................................................... 448 HandlerExceptionResolver ............................................................................ 448 @ExceptionHandler ...................................................................................... 449 15.10. Convention over configuration support ........................................................ 450 The Controller ControllerClassNameHandlerMapping .................................... 450 The Model ModelMap (ModelAndView) ....................................................... 451 The View - RequestToViewNameTranslator .................................................. 453 15.11. ETag support .............................................................................................. 454 15.12. Configuring Spring MVC ............................................................................ 455 3.0 Reference Documentation xiv

Spring Framework

mvc:annotation-driven .................................................................................. 455 mvc:interceptors ........................................................................................... 456 mvc:view-controller ...................................................................................... 456 mvc:resources .............................................................................................. 456 mvc:default-servlet-handler ........................................................................... 458 15.13. More Spring Web MVC Resources .............................................................. 458 16. View technologies ................................................................................................... 460 16.1. Introduction ................................................................................................. 460 16.2. JSP & JSTL ................................................................................................. 460 View resolvers ............................................................................................. 460 'Plain-old' JSPs versus JSTL .......................................................................... 461 Additional tags facilitating development ........................................................ 461 Using Spring's form tag library ...................................................................... 461 Configuration ....................................................................................... 461 The form tag ........................................................................................ 462 The input tag ........................................................................................ 463 The checkbox tag .................................................................................. 463 The checkboxes tag .............................................................................. 465 The radiobutton tag ............................................................................... 465 The radiobuttons tag ............................................................................. 466 The password tag .................................................................................. 466 The select tag ....................................................................................... 466 The option tag ...................................................................................... 467 The options tag ..................................................................................... 467 The textarea tag .................................................................................... 468 The hidden tag ...................................................................................... 468 The errors tag ....................................................................................... 469 HTTP Method Conversion .................................................................... 471 16.3. Tiles ............................................................................................................ 471 Dependencies ............................................................................................... 472 How to integrate Tiles ................................................................................... 472 UrlBasedViewResolver ......................................................................... 472 ResourceBundleViewResolver .............................................................. 473 SimpleSpringPreparerFactory and SpringBeanPreparerFactory ................ 473 16.4. Velocity & FreeMarker ................................................................................. 474 Dependencies ............................................................................................... 474 Context configuration ................................................................................... 474 Creating templates ........................................................................................ 475 Advanced configuration ................................................................................ 475 velocity.properties ................................................................................ 475 FreeMarker .......................................................................................... 476 Bind support and form handling ..................................................................... 476 The bind macros ................................................................................... 476 Simple binding ..................................................................................... 477 Form input generation macros ............................................................... 478 3.0 Reference Documentation xv

Spring Framework

HTML escaping and XHTML compliance ............................................. 482 16.5. XSLT .......................................................................................................... 483 My First Words ............................................................................................ 483 Bean definitions ................................................................................... 483 Standard MVC controller code .............................................................. 483 Convert the model data to XML ............................................................ 484 Defining the view properties .................................................................. 484 Document transformation ...................................................................... 485 Summary ..................................................................................................... 485 16.6. Document views (PDF/Excel) ....................................................................... 486 Introduction ................................................................................................. 486 Configuration and setup ................................................................................ 486 Document view definitions .................................................................... 486 Controller code ..................................................................................... 486 Subclassing for Excel views .................................................................. 487 Subclassing for PDF views .................................................................... 488 16.7. JasperReports ............................................................................................... 489 Dependencies ............................................................................................... 489 Configuration ............................................................................................... 489 Configuring the ViewResolver .............................................................. 489 Configuring the Views .......................................................................... 490 About Report Files ............................................................................... 490 Using JasperReportsMultiFormatView ................................................... 490 Populating the ModelAndView ...................................................................... 491 Working with Sub-Reports ............................................................................ 492 Configuring Sub-Report Files ................................................................ 492 Configuring Sub-Report Data Sources ................................................... 493 Configuring Exporter Parameters ................................................................... 493 16.8. Feed Views .................................................................................................. 494 16.9. XML Marshalling View ................................................................................ 495 16.10. JSON Mapping View .................................................................................. 495 17. Integrating with other web frameworks ..................................................................... 496 17.1. Introduction ................................................................................................. 496 17.2. Common configuration ................................................................................. 497 17.3. JavaServer Faces 1.1 and 1.2 ......................................................................... 498 DelegatingVariableResolver (JSF 1.1/1.2) ...................................................... 498 SpringBeanVariableResolver (JSF 1.1/1.2) ..................................................... 499 SpringBeanFacesELResolver (JSF 1.2+) ........................................................ 499 FacesContextUtils ........................................................................................ 500 17.4. Apache Struts 1.x and 2.x ............................................................................. 500 ContextLoaderPlugin .................................................................................... 501 DelegatingRequestProcessor ................................................................. 502 DelegatingActionProxy ......................................................................... 502 ActionSupport Classes .................................................................................. 503 17.5. WebWork 2.x ............................................................................................... 503 3.0 Reference Documentation xvi

Spring Framework

17.6. Tapestry 3.x and 4.x ..................................................................................... 504 Injecting Spring-managed beans .................................................................... 505 Dependency Injecting Spring Beans into Tapestry pages ......................... 506 Component definition files .................................................................... 507 Adding abstract accessors ...................................................................... 508 Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style ............................................................................................................. 510 17.7. Further Resources ......................................................................................... 511 18. Portlet MVC Framework ......................................................................................... 512 18.1. Introduction ................................................................................................. 512 Controllers - The C in MVC .......................................................................... 513 Views - The V in MVC ................................................................................. 513 Web-scoped beans ........................................................................................ 514 18.2. The DispatcherPortlet ................................................................................... 514 18.3. The ViewRendererServlet ............................................................................. 516 18.4. Controllers ................................................................................................... 517 AbstractController and PortletContentGenerator ............................................. 517 Other simple controllers ................................................................................ 519 Command Controllers ................................................................................... 519 PortletWrappingController ............................................................................ 520 18.5. Handler mappings ........................................................................................ 520 PortletModeHandlerMapping ........................................................................ 521 ParameterHandlerMapping ............................................................................ 522 PortletModeParameterHandlerMapping ......................................................... 522 Adding HandlerInterceptors .......................................................................... 523 HandlerInterceptorAdapter ............................................................................ 523 ParameterMappingInterceptor ....................................................................... 523 18.6. Views and resolving them ............................................................................. 524 18.7. Multipart (file upload) support ...................................................................... 524 Using the PortletMultipartResolver ................................................................ 525 Handling a file upload in a form .................................................................... 525 18.8. Handling exceptions ..................................................................................... 528 18.9. Annotation-based controller configuration ..................................................... 529 Setting up the dispatcher for annotation support .............................................. 529 Defining a controller with @Controller .......................................................... 529 Mapping requests with @RequestMapping ..................................................... 530 Supported handler method arguments ............................................................ 531 Binding request parameters to method parameters with @RequestParam .......... 533 Providing a link to data from the model with @ModelAttribute ....................... 534 Specifying attributes to store in a Session with @SessionAttributes ................. 534 Customizing WebDataBinder initialization ..................................................... 535 Customizing data binding with @InitBinder ........................................... 535 Configuring a custom WebBindingInitializer .......................................... 535 18.10. Portlet application deployment .................................................................... 536 VI. Integration ...................................................................................................................... 537 3.0 Reference Documentation xvii

Spring Framework

19. Remoting and web services using Spring .................................................................. 538 19.1. Introduction ................................................................................................. 538 19.2. Exposing services using RMI ........................................................................ 539 Exporting the service using the RmiServiceExporter ....................................... 539 Linking in the service at the client ................................................................. 540 19.3. Using Hessian or Burlap to remotely call services via HTTP ........................... 541 Wiring up the DispatcherServlet for Hessian and co. ....................................... 541 Exposing your beans by using the HessianServiceExporter .............................. 541 Linking in the service on the client ................................................................ 542 Using Burlap ................................................................................................ 542 Applying HTTP basic authentication to a service exposed through Hessian or Burlap .......................................................................................................... 543 19.4. Exposing services using HTTP invokers ........................................................ 543 Exposing the service object ........................................................................... 543 Linking in the service at the client ................................................................. 544 19.5. Web services ................................................................................................ 545 Exposing servlet-based web services using JAX-RPC ..................................... 546 Accessing web services using JAX-RPC ........................................................ 546 Registering JAX-RPC Bean Mappings ........................................................... 548 Registering your own JAX-RPC Handler ....................................................... 549 Exposing servlet-based web services using JAX-WS ...................................... 549 Exporting standalone web services using JAX-WS ......................................... 550 Exporting web services using the JAX-WS RI's Spring support ....................... 551 Accessing web services using JAX-WS .......................................................... 551 19.6. JMS ............................................................................................................. 552 Server-side configuration .............................................................................. 553 Client-side configuration ............................................................................... 554 19.7. Auto-detection is not implemented for remote interfaces ................................. 555 19.8. Considerations when choosing a technology ................................................... 555 19.9. Accessing RESTful services on the Client ...................................................... 556 RestTemplate ............................................................................................... 556 Dealing with request and response headers ............................................. 558 HTTP Message Conversion ........................................................................... 559 StringHttpMessageConverter ................................................................. 559 FormHttpMessageConverter .................................................................. 559 ByteArrayMessageConverter ................................................................. 560 MarshallingHttpMessageConverter ........................................................ 560 MappingJacksonHttpMessageConverter ................................................. 560 SourceHttpMessageConverter ............................................................... 560 BufferedImageHttpMessageConverter ................................................... 560 20. Enterprise JavaBeans (EJB) integration .................................................................... 561 20.1. Introduction ................................................................................................. 561 20.2. Accessing EJBs ............................................................................................ 561 Concepts ...................................................................................................... 561 Accessing local SLSBs ................................................................................. 562 3.0 Reference Documentation xviii

Spring Framework

Accessing remote SLSBs .............................................................................. 563 Accessing EJB 2.x SLSBs versus EJB 3 SLSBs .............................................. 564 20.3. Using Spring's EJB implementation support classes ........................................ 564 EJB 2.x base classes ..................................................................................... 564 EJB 3 injection interceptor ............................................................................ 566 21. JMS (Java Message Service) .................................................................................... 568 21.1. Introduction ................................................................................................. 568 21.2. Using Spring JMS ........................................................................................ 568 JmsTemplate ................................................................................................ 568 Connections ................................................................................................. 569 Caching Messaging Resources ............................................................... 570 SingleConnectionFactory ...................................................................... 570 CachingConnectionFactory ................................................................... 570 Destination Management ............................................................................... 570 Message Listener Containers ......................................................................... 571 SimpleMessageListenerContainer .......................................................... 572 DefaultMessageListenerContainer ......................................................... 572 Transaction management ............................................................................... 572 21.3. Sending a Message ....................................................................................... 573 Using Message Converters ............................................................................ 574 SessionCallback and ProducerCallback .......................................................... 575 21.4. Receiving a message ..................................................................................... 575 Synchronous Reception ................................................................................. 575 Asynchronous Reception - Message-Driven POJOs ........................................ 575 The SessionAwareMessageListener interface ................................................. 576 The MessageListenerAdapter ........................................................................ 576 Processing messages within transactions ........................................................ 578 21.5. Support for JCA Message Endpoints .............................................................. 579 21.6. JMS Namespace Support .............................................................................. 581 22. JMX ....................................................................................................................... 586 22.1. Introduction ................................................................................................. 586 22.2. Exporting your beans to JMX ........................................................................ 586 Creating an MBeanServer ............................................................................. 587 Reusing an existing MBeanServer ................................................................. 588 Lazy-initialized MBeans ............................................................................... 589 Automatic registration of MBeans ................................................................. 589 Controlling the registration behavior .............................................................. 589 22.3. Controlling the management interface of your beans ....................................... 591 The MBeanInfoAssembler Interface .............................................................. 591 Using Source-Level Metadata (JDK 5.0 annotations) ...................................... 591 Source-Level Metadata Types ....................................................................... 593 The AutodetectCapableMBeanInfoAssembler interface ................................... 595 Defining management interfaces using Java interfaces .................................... 596 Using MethodNameBasedMBeanInfoAssembler ............................................ 597 22.4. Controlling the ObjectNames for your beans .................................................. 597 3.0 Reference Documentation xix

Spring Framework

Reading ObjectNames from Properties ........................................................... 598 Using the MetadataNamingStrategy ............................................................... 599 The element ........................................................... 599 22.5. JSR-160 Connectors ..................................................................................... 600 Server-side Connectors ................................................................................. 600 Client-side Connectors .................................................................................. 601 JMX over Burlap/Hessian/SOAP ................................................................... 601 22.6. Accessing MBeans via Proxies ...................................................................... 602 22.7. Notifications ................................................................................................ 602 Registering Listeners for Notifications ........................................................... 602 Publishing Notifications ................................................................................ 606 22.8. Further Resources ......................................................................................... 607 23. JCA CCI ................................................................................................................. 608 23.1. Introduction ................................................................................................. 608 23.2. Configuring CCI .......................................................................................... 608 Connector configuration ................................................................................ 608 ConnectionFactory configuration in Spring .................................................... 609 Configuring CCI connections ........................................................................ 610 Using a single CCI connection ....................................................................... 610 23.3. Using Spring's CCI access support ................................................................. 611 Record conversion ........................................................................................ 611 The CciTemplate .......................................................................................... 612 DAO support ................................................................................................ 613 Automatic output record generation ............................................................... 614 Summary ..................................................................................................... 614 Using a CCI Connection and Interaction directly ............................................ 615 Example for CciTemplate usage .................................................................... 616 23.4. Modeling CCI access as operation objects ...................................................... 618 MappingRecordOperation ............................................................................. 618 MappingCommAreaOperation ....................................................................... 619 Automatic output record generation ............................................................... 619 Summary ..................................................................................................... 619 Example for MappingRecordOperation