spring-framework-reference

804
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.

Upload: vivek-pandey

Post on 24-Nov-2014

285 views

Category:

Documents


0 download

TRANSCRIPT

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

3.0

Reference Documentation

ii

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

Context management and caching .......................................................... 273 Dependency Injection of test fixtures ..................................................... 274 Transaction management ....................................................................... 274 Support classes for integration testing .................................................... 275 JDBC testing support .................................................................................... 275 Annotations .................................................................................................. 275 Spring TestContext Framework ..................................................................... 281 Key abstractions ................................................................................... 281 Context management and caching .......................................................... 282 Dependency Injection of test fixtures ..................................................... 284 Transaction management ....................................................................... 287 TestContext support classes ................................................................... 289 PetClinic example ......................................................................................... 292 9.4. Further Resources .......................................................................................... 294 IV. Data Access .................................................................................................................... 295 10. Transaction Management ......................................................................................... 296 10.1. Introduction to Spring Framework transaction management ............................ 296 10.2. Advantages of the Spring Framework's transaction support model ................... 296 Global transactions ....................................................................................... 297 Local transactions ......................................................................................... 297 Spring Framework's consistent programming model ....................................... 297 10.3. Understanding the Spring Framework transaction abstraction .......................... 298 10.4. Synchronizing resources with transactions ..................................................... 302 High-level synchronization approach ............................................................. 302 Low-level synchronization approach .............................................................. 302 TransactionAwareDataSourceProxy ............................................................... 303 10.5. Declarative transaction management .............................................................. 303 Understanding the Spring Framework's declarative transaction implementation 305 Example of declarative transaction implementation ......................................... 306 Rolling back a declarative transaction ............................................................ 310 Configuring different transactional semantics for different beans ..................... 311 settings ..................................................................................... 313 Using @Transactional ................................................................................... 314 @Transactional settings ........................................................................ 318 Multiple Transaction Managers with @Transactional .............................. 319 Custom shortcut annotations .................................................................. 320 Transaction propagation ................................................................................ 320 Required .............................................................................................. 321 RequiresNew ........................................................................................ 321 Nested ................................................................................................. 322 Advising transactional operations .................................................................. 322 Using @Transactional with AspectJ ............................................................... 325 10.6. Programmatic transaction management .......................................................... 326 Using the TransactionTemplate ..................................................................... 326 Specifying transaction settings ............................................................... 327 3.0 Reference Documentation x

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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

Spring Framework

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