spring framework reference

737
Reference Documentation (Work in progress) 3.0.M3 Copyright © 2004-2009 Rod Johnson, Juergen Hoeller, Alef Arendsen, Colin Sampaleanu, Rob Harrop, 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 Abed Rabbo 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: rsacoman

Post on 15-Nov-2014

514 views

Category:

Documents


0 download

TRANSCRIPT

Reference Documentation(Work in progress)

3.0.M3Copyright 2004-2009 Rod Johnson, Juergen Hoeller, Alef Arendsen, Colin Sampaleanu, Rob Harrop, 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 Abed Rabbo

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 ContentsPreface ................................................................................................................................xxiii 1. Introduction ..........................................................................................................................1 1.1. Dependency Injection .................................................................................................1 1.2. Modules ....................................................................................................................2 Core Container .........................................................................................................3 Data Access/Integration ............................................................................................4 Web .........................................................................................................................4 AOP and Instrumentation ..........................................................................................5 Test .........................................................................................................................5 1.3. Usage scenarios .........................................................................................................5 2. What's new in Spring 3.0? ...................................................................................................10 2.1. Java 5 ......................................................................................................................10 2.2. Improved documentation ..........................................................................................10 2.3. New module organization and build system ...............................................................11 2.4. Overview of new features .........................................................................................12 Core APIs updated for Java 5 ..................................................................................12 Spring Expression Language ...................................................................................13 The Inversion of Control (IoC) container ..................................................................13 Java based bean metadata ................................................................................13 Defining bean metadata within components ......................................................14 The Data Tier .........................................................................................................14 The Web Tier .........................................................................................................14 Comprehensive REST support .........................................................................15 @MVC additions ...........................................................................................15 Declarative model validation ...................................................................................15 Early support for Java EE 6 .....................................................................................15 3. Getting started with Spring ..................................................................................................16 3.1. Creating an ApplicationContext ................................................................................16 3.2. The Data Access Object ............................................................................................16 3.3. The Business Layer ..................................................................................................16 3.4. The Web UI .............................................................................................................16 I. Core Technologies ...............................................................................................................17 4. The IoC container .......................................................................................................18 4.1. Introduction .....................................................................................................18 4.2. Basics - containers and beans ............................................................................18 The container .................................................................................................19 Configuration metadata ...........................................................................20 Instantiating a container ..................................................................................21 Composing XML-based configuration metadata .......................................22 The beans .......................................................................................................23

3.0.M3

Reference Documentation

ii

Spring Framework

Naming beans .........................................................................................24 Instantiating beans ..................................................................................25 Using the container .........................................................................................28 4.3. Dependencies ...................................................................................................28 Injecting dependencies ....................................................................................28 Constructor Injection ..............................................................................28 Setter Injection .......................................................................................30 Some examples ......................................................................................33 Dependencies and configuration in detail .........................................................34 Straight values (primitives, Strings, etc.) ..................................................35 References to other beans (collaborators) .................................................36 Inner beans .............................................................................................37 Collections .............................................................................................38 Nulls ......................................................................................................41 Shortcuts and other convenience options for XML-based configuration metadata ................................................................................................41 Compound property names ......................................................................44 Using depends-on ...........................................................................................44 Lazily-instantiated beans .................................................................................45 Autowiring collaborators .................................................................................46 Excluding a bean from being available for autowiring ...............................48 Checking for dependencies ..............................................................................48 Method Injection ............................................................................................49 Lookup method injection .........................................................................50 Arbitrary method replacement .................................................................51 4.4. Bean scopes .....................................................................................................52 The singleton scope ........................................................................................54 The prototype scope ........................................................................................54 Singleton beans with prototype-bean dependencies ...........................................56 The other scopes .............................................................................................56 Initial web configuration .........................................................................57 The request scope ...................................................................................58 The session scope ...................................................................................58 The global session scope .........................................................................58 Scoped beans as dependencies .................................................................59 Custom scopes ...............................................................................................61 Creating your own custom scope .............................................................61 Using a custom scope ..............................................................................62 4.5. Customizing the nature of a bean .......................................................................63 Lifecycle callbacks .........................................................................................63 Initialization callbacks ............................................................................64 Destruction callbacks ..............................................................................64 Default initialization & destroy methods ..................................................65 Combining lifecycle mechanisms ............................................................66 Shutting down the Spring IoC container gracefully in non-web applications 67 3.0.M3 Reference Documentation iii

Spring Framework

Knowing who you are .....................................................................................68 BeanFactoryAware .................................................................................68 BeanNameAware ....................................................................................70 4.6. Bean definition inheritance ...............................................................................70 4.7. Container extension points ................................................................................72 Customizing beans using BeanPostProcessors ..................................................72 Example: Hello World, BeanPostProcessor-style ......................................74 Example: The RequiredAnnotationBeanPostProcessor ..............................75 Customizing configuration metadata with BeanFactoryPostProcessors ...............75 Example: the PropertyPlaceholderConfigurer ...........................................77 Example: the PropertyOverrideConfigurer ...............................................78 Customizing instantiation logic using FactoryBeans ..........................................79 4.8. The ApplicationContext ....................................................................................80 BeanFactory or ApplicationContext? ...............................................................80 Internationalization using MessageSources .......................................................81 Events ............................................................................................................84 Convenient access to low-level resources .........................................................86 Convenient ApplicationContext instantiation for web applications .....................87 4.9. Glue code and the evil singleton ........................................................................88 4.10. Deploying a Spring ApplicationContext as a J2EE RAR file .............................89 4.11. Annotation-based configuration .......................................................................90 @Required .....................................................................................................90 @Autowired ...................................................................................................91 Fine-tuning annotation-based autowiring with qualifiers ...................................93 CustomAutowireConfigurer ............................................................................98 @Resource .....................................................................................................99 @PostConstruct and @PreDestroy ................................................................. 100 4.12. Classpath scanning, managed components and writing configurations using Java 101 @Component and further stereotype annotations ............................................ 101 Auto-detecting components ........................................................................... 101 Using filters to customize scanning ................................................................ 102 Using the @Configuration annotation ............................................................ 103 Using the @Bean annotation ......................................................................... 104 Declaring a bean ................................................................................... 104 Injecting dependencies .......................................................................... 105 Receiving lifecycle callbacks ................................................................. 105 Specifying bean scope ........................................................................... 106 Customizing bean naming ..................................................................... 108 Defining bean metadata within components .................................................... 108 Naming autodetected components .................................................................. 109 Providing a scope for autodetected components .............................................. 110 Providing qualifier metadata with annotations ................................................ 111 4.13. Registering a LoadTimeWeaver .................................................................... 112 5. Resources ................................................................................................................. 113 5.1. Introduction ................................................................................................... 113 3.0.M3 Reference Documentation iv

Spring Framework

5.2. The Resource interface ................................................................................... 113 5.3. Built-in Resource implementations .................................................................. 114 UrlResource ................................................................................................. 114 ClassPathResource ....................................................................................... 115 FileSystemResource ..................................................................................... 115 ServletContextResource ................................................................................ 115 InputStreamResource .................................................................................... 115 ByteArrayResource ...................................................................................... 116 5.4. The ResourceLoader ....................................................................................... 116 5.5. The ResourceLoaderAware interface ............................................................... 117 5.6. Resources as dependencies ............................................................................. 118 5.7. Application contexts and Resource paths ......................................................... 118 Constructing application contexts .................................................................. 118 Constructing ClassPathXmlApplicationContext instances - shortcuts ....... 119 Wildcards in application context constructor resource paths ............................ 120 Ant-style Patterns ................................................................................. 120 The classpath*: prefix ........................................................................... 121 Other notes relating to wildcards ............................................................ 121 FileSystemResource caveats .......................................................................... 122 6. Validation, Data-binding, the BeanWrapper, and PropertyEditors ................................ 124 6.1. Introduction ................................................................................................... 124 6.2. Validation using Spring's Validator interface .................................................... 124 6.3. Resolving codes to error messages .................................................................. 126 6.4. Bean manipulation and the BeanWrapper ........................................................ 126 Setting and getting basic and nested properties ............................................... 127 Built-in PropertyEditor implementations ........................................................ 128 Registering additional custom PropertyEditors ....................................... 131 7. Spring Expression Language (SpEL) .......................................................................... 135 7.1. Introduction ................................................................................................... 135 7.2. Feature Overview ........................................................................................... 135 7.3. Expression Evaluation using Spring's Expression Interface ............................... 136 The EvaluationContext interface .................................................................... 138 Type Conversion .................................................................................. 138 7.4. Expression support for defining bean definitions .............................................. 139 XML based configuration ............................................................................. 139 Annotation-based configuration ..................................................................... 140 7.5. Language Reference ....................................................................................... 141 Literal expressions ........................................................................................ 141 Properties, Arrays, Lists, Maps, Indexers ........................................................ 141 Methods ....................................................................................................... 142 Operators ..................................................................................................... 142 Relational operators .............................................................................. 143 Logical operators .................................................................................. 143 Mathematical operators ......................................................................... 144 Assignment .................................................................................................. 144 3.0.M3 Reference Documentation v

Spring Framework

Types ........................................................................................................... 144 Constructors ................................................................................................. 145 Variables ...................................................................................................... 145 The #this variable ................................................................................. 145 Functions ..................................................................................................... 146 Ternary Operator (If-Then-Else) .................................................................... 146 Collection Selection ...................................................................................... 147 Collection Projection .................................................................................... 147 Expression templating ................................................................................... 147 7.6. Classes used in the examples ........................................................................... 148 8. Aspect Oriented Programming with Spring ................................................................. 151 8.1. Introduction ................................................................................................... 151 AOP concepts ............................................................................................... 151 Spring AOP capabilities and goals ................................................................. 153 AOP Proxies ................................................................................................ 154 8.2. @AspectJ support .......................................................................................... 155 Enabling @AspectJ Support .......................................................................... 155 Declaring an aspect ....................................................................................... 155 Declaring a pointcut ...................................................................................... 156 Supported Pointcut Designators ............................................................. 157 Combining pointcut expressions ............................................................ 158 Sharing common pointcut definitions ..................................................... 159 Examples ............................................................................................. 160 Declaring advice ........................................................................................... 163 Before advice ....................................................................................... 163 After returning advice ........................................................................... 163 After throwing advice ........................................................................... 164 After (finally) advice ............................................................................ 165 Around advice ...................................................................................... 165 Advice parameters ................................................................................ 166 Advice ordering .................................................................................... 169 Introductions ................................................................................................ 170 Aspect instantiation models ........................................................................... 170 Example ....................................................................................................... 171 8.3. Schema-based AOP support ............................................................................ 173 Declaring an aspect ....................................................................................... 173 Declaring a pointcut ...................................................................................... 174 Declaring advice ........................................................................................... 175 Before advice ....................................................................................... 175 After returning advice ........................................................................... 176 After throwing advice ........................................................................... 177 After (finally) advice ............................................................................ 177 Around advice ...................................................................................... 178 Advice parameters ................................................................................ 178 Advice ordering .................................................................................... 180 3.0.M3 Reference Documentation vi

Spring Framework

Introductions ................................................................................................ 180 Aspect instantiation models ........................................................................... 181 Advisors ...................................................................................................... 181 Example ....................................................................................................... 182 8.4. Choosing which AOP declaration style to use .................................................. 184 Spring AOP or full AspectJ? ......................................................................... 184 @AspectJ or XML for Spring AOP? .............................................................. 184 8.5. Mixing aspect types ........................................................................................ 185 8.6. Proxying mechanisms ..................................................................................... 185 Understanding AOP proxies .......................................................................... 186 8.7. Programmatic creation of @AspectJ Proxies .................................................... 189 8.8. Using AspectJ with Spring applications ........................................................... 189 Using AspectJ to dependency inject domain objects with Spring ...................... 190 Unit testing @Configurable objects ....................................................... 192 Working with multiple application contexts ............................................ 192 Other Spring aspects for AspectJ ................................................................... 193 Configuring AspectJ aspects using Spring IoC ................................................ 194 Load-time weaving with AspectJ in the Spring Framework ............................. 195 A first example ..................................................................................... 195 Aspects ................................................................................................ 198 'META-INF/aop.xml' ............................................................................ 198 Required libraries (JARS) ..................................................................... 199 Spring configuration ............................................................................. 199 Environment-specific configuration ....................................................... 201 8.9. Further Resources .......................................................................................... 202 9. Spring AOP APIs ...................................................................................................... 204 9.1. Introduction ................................................................................................... 204 9.2. Pointcut API in Spring .................................................................................... 204 Concepts ...................................................................................................... 204 Operations on pointcuts ................................................................................. 205 AspectJ expression pointcuts ......................................................................... 205 Convenience pointcut implementations .......................................................... 205 Static pointcuts ..................................................................................... 206 Dynamic pointcuts ................................................................................ 207 Pointcut superclasses .................................................................................... 207 Custom pointcuts .......................................................................................... 208 9.3. Advice API in Spring ..................................................................................... 208 Advice lifecycles .......................................................................................... 208 Advice types in Spring .................................................................................. 208 Interception around advice .................................................................... 209 Before advice ....................................................................................... 209 Throws advice ...................................................................................... 210 After Returning advice .......................................................................... 211 Introduction advice ............................................................................... 212 9.4. Advisor API in Spring .................................................................................... 215 3.0.M3 Reference Documentation vii

Spring Framework

9.5. Using the ProxyFactoryBean to create AOP proxies ......................................... 215 Basics .......................................................................................................... 215 JavaBean properties ...................................................................................... 216 JDK- and CGLIB-based proxies .................................................................... 217 Proxying interfaces ....................................................................................... 218 Proxying classes ........................................................................................... 220 Using 'global' advisors .................................................................................. 220 9.6. Concise proxy definitions ............................................................................... 221 9.7. Creating AOP proxies programmatically with the ProxyFactory ........................ 222 9.8. Manipulating advised objects .......................................................................... 222 9.9. Using the "autoproxy" facility ......................................................................... 224 Autoproxy bean definitions ........................................................................... 224 BeanNameAutoProxyCreator ................................................................ 224 DefaultAdvisorAutoProxyCreator .......................................................... 225 AbstractAdvisorAutoProxyCreator ........................................................ 226 Using metadata-driven auto-proxying ............................................................ 226 9.10. Using TargetSources .................................................................................... 229 Hot swappable target sources ......................................................................... 229 Pooling target sources ................................................................................... 230 Prototype target sources ................................................................................ 231 ThreadLocal target sources ............................................................................ 231 9.11. Defining new Advice types ........................................................................... 232 9.12. Further resources .......................................................................................... 232 10. Testing ................................................................................................................... 234 10.1. Introduction ................................................................................................. 234 10.2. Unit testing .................................................................................................. 234 Mock objects ................................................................................................ 234 JNDI .................................................................................................... 234 Servlet API .......................................................................................... 234 Portlet API ........................................................................................... 235 Unit testing support classes ........................................................................... 235 General utilities .................................................................................... 235 Spring MVC ......................................................................................... 235 10.3. Integration testing ......................................................................................... 235 Overview ..................................................................................................... 235 Goals ........................................................................................................... 236 Context management and caching .......................................................... 236 Dependency Injection of test fixtures ..................................................... 237 Transaction management ....................................................................... 237 Integration testing support classes .......................................................... 238 JDBC testing support .................................................................................... 238 Annotations .................................................................................................. 239 Spring TestContext Framework ..................................................................... 243 Key abstractions ................................................................................... 243 Context management and caching .......................................................... 244 3.0.M3 Reference Documentation viii

Spring Framework

Dependency Injection of test fixtures ..................................................... 246 Transaction management ....................................................................... 249 TestContext support classes ................................................................... 250 PetClinic example ......................................................................................... 253 10.4. Further Resources ......................................................................................... 255 II. Data Access ..................................................................................................................... 257 11. Transaction management ......................................................................................... 258 11.1. Introduction ................................................................................................. 258 11.2. Motivations .................................................................................................. 258 11.3. Key abstractions ........................................................................................... 260 11.4. Resource synchronization with transactions ................................................... 263 High-level approach ...................................................................................... 263 Low-level approach ...................................................................................... 264 TransactionAwareDataSourceProxy ............................................................... 264 11.5. Declarative transaction management .............................................................. 265 Understanding the Spring Framework's declarative transaction implementation 266 A first example ............................................................................................. 267 Rolling back ................................................................................................. 271 Configuring different transactional semantics for different beans ..................... 272 settings ..................................................................................... 273 Using @Transactional ................................................................................... 275 @Transactional settings ........................................................................ 279 Transaction propagation ................................................................................ 281 Required .............................................................................................. 281 RequiresNew ........................................................................................ 281 Nested ................................................................................................. 282 Advising transactional operations .................................................................. 282 Using @Transactional with AspectJ ............................................................... 285 11.6. Programmatic transaction management .......................................................... 286 Using the TransactionTemplate ..................................................................... 286 Specifying transaction settings ............................................................... 287 Using the PlatformTransactionManager ......................................................... 288 11.7. Choosing between programmatic and declarative transaction management ....... 289 11.8. Application server-specific integration ........................................................... 289 IBM WebSphere ........................................................................................... 290 BEA WebLogic ............................................................................................ 290 Oracle OC4J ................................................................................................. 290 11.9. Solutions to common problems ..................................................................... 290 Use of the wrong transaction manager for a specific DataSource ...................... 290 11.10. Further Resources ....................................................................................... 291 12. DAO support .......................................................................................................... 292 12.1. Introduction ................................................................................................. 292 12.2. Consistent exception hierarchy ...................................................................... 292 12.3. Consistent abstract classes for DAO support .................................................. 293 13. Data access using JDBC .......................................................................................... 294 3.0.M3 Reference Documentation ix

Spring Framework

13.1. Introduction ................................................................................................. 294 Choosing a style ........................................................................................... 294 The package hierarchy .................................................................................. 295 13.2. Using the JDBC Core classes to control basic JDBC processing and error handling ............................................................................................................................. 296 JdbcTemplate ............................................................................................... 296 Examples ............................................................................................. 296 JdbcTemplate idioms (best practices) ..................................................... 298 NamedParameterJdbcTemplate ...................................................................... 299 SimpleJdbcTemplate ..................................................................................... 301 DataSource .................................................................................................. 303 SQLExceptionTranslator ............................................................................... 303 Executing statements .................................................................................... 305 Running Queries ........................................................................................... 305 Updating the database ................................................................................... 306 Retrieving auto-generated keys ...................................................................... 306 13.3. Controlling database connections .................................................................. 307 DataSourceUtils ........................................................................................... 307 SmartDataSource .......................................................................................... 307 AbstractDataSource ...................................................................................... 307 SingleConnectionDataSource ........................................................................ 307 DriverManagerDataSource ............................................................................ 308 TransactionAwareDataSourceProxy ............................................................... 308 DataSourceTransactionManager .................................................................... 308 NativeJdbcExtractor ..................................................................................... 309 13.4. JDBC batch operations ................................................................................. 310 Batch operations with the JdbcTemplate ......................................................... 310 Batch operations with the SimpleJdbcTemplate .............................................. 310 13.5. Simplifying JDBC operations with the SimpleJdbc classes .............................. 312 Inserting data using SimpleJdbcInsert ............................................................ 312 Retrieving auto-generated keys using SimpleJdbcInsert ................................... 312 Specifying the columns to use for a SimpleJdbcInsert ..................................... 313 Using SqlParameterSource to provide parameter values .................................. 314 Calling a stored procedure using SimpleJdbcCall ............................................ 315 Declaring parameters to use for a SimpleJdbcCall ........................................... 317 How to define SqlParameters ......................................................................... 317 Calling a stored function using SimpleJdbcCall .............................................. 318 Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................. 319 13.6. Modeling JDBC operations as Java objects .................................................... 320 SqlQuery ...................................................................................................... 320 MappingSqlQuery ........................................................................................ 321 SqlUpdate .................................................................................................... 322 StoredProcedure ........................................................................................... 322 SqlFunction .................................................................................................. 326 13.7. Common issues with parameter and data value handling ................................. 326 3.0.M3 Reference Documentation x

Spring Framework

Providing SQL type information for parameters .............................................. 326 Handling BLOB and CLOB objects ............................................................... 327 Passing in lists of values for IN clause ........................................................... 328 Handling complex types for stored procedure calls ......................................... 329 14. Object Relational Mapping (ORM) data access ......................................................... 331 14.1. Introduction ................................................................................................. 331 14.2. Hibernate ..................................................................................................... 332 Resource management .................................................................................. 332 SessionFactory setup in a Spring container ..................................................... 333 The HibernateTemplate ................................................................................. 334 Implementing Spring-based DAOs without callbacks ...................................... 335 Implementing DAOs based on plain Hibernate 3 API ...................................... 336 Programmatic transaction demarcation ........................................................... 337 Declarative transaction demarcation ............................................................... 338 Transaction management strategies ................................................................ 340 Container resources versus local resources ..................................................... 341 Spurious application server warnings when using Hibernate ............................ 342 14.3. JDO ............................................................................................................. 344 PersistenceManagerFactory setup .................................................................. 344 JdoTemplate and JdoDaoSupport ................................................................... 345 Implementing DAOs based on the plain JDO API ........................................... 346 Transaction management ............................................................................... 348 JdoDialect .................................................................................................... 349 14.4. Oracle TopLink ............................................................................................ 349 SessionFactory abstraction ............................................................................ 350 TopLinkTemplate and TopLinkDaoSupport ................................................... 350 Implementing DAOs based on plain TopLink API .......................................... 352 Transaction management ............................................................................... 353 14.5. iBATIS SQL Maps ....................................................................................... 354 Setting up the SqlMapClient .......................................................................... 355 Using SqlMapClientTemplate and SqlMapClientDaoSupport .......................... 356 Implementing DAOs based on plain iBATIS API ........................................... 357 14.6. JPA ............................................................................................................. 358 JPA setup in a Spring environment ................................................................ 358 LocalEntityManagerFactoryBean ........................................................... 358 Obtaining an EntityManagerFactory from JNDI ...................................... 358 LocalContainerEntityManagerFactoryBean ............................................ 359 Dealing with multiple persistence units .................................................. 363 JpaTemplate and JpaDaoSupport ................................................................... 364 Implementing DAOs based on plain JPA ........................................................ 365 Exception Translation ................................................................................... 367 14.7. Transaction Management .............................................................................. 368 14.8. JpaDialect .................................................................................................... 369 15. Marshalling XML using O/X Mappers ..................................................................... 370 15.1. Introduction ................................................................................................. 370 3.0.M3 Reference Documentation xi

Spring Framework

15.2. Marshaller and Unmarshaller ........................................................................ 370 Marshaller .................................................................................................... 370 Unmarshaller ................................................................................................ 371 XmlMappingException ................................................................................. 372 15.3. Using Marshaller and Unmarshaller ............................................................... 372 15.4. XML Schema-based Configuration ................................................................ 374 15.5. JAXB .......................................................................................................... 375 Jaxb2Marshaller ........................................................................................... 375 XML Schema-based Configuration ........................................................ 376 15.6. Castor .......................................................................................................... 376 CastorMarshaller .......................................................................................... 376 Mapping ...................................................................................................... 377 15.7. XMLBeans .................................................................................................. 377 XmlBeansMarshaller .................................................................................... 377 XML Schema-based Configuration ........................................................ 377 15.8. JiBX ............................................................................................................ 378 JibxMarshaller .............................................................................................. 378 XML Schema-based Configuration ........................................................ 378 15.9. XStream ...................................................................................................... 379 XStreamMarshaller ....................................................................................... 379 III. The Web ......................................................................................................................... 380 16. Web MVC framework ............................................................................................. 381 16.1. Introduction ................................................................................................. 381 Pluggability of other MVC implementations ................................................... 382 Features of Spring Web MVC ....................................................................... 383 16.2. The DispatcherServlet .................................................................................. 384 16.3. Controllers ................................................................................................... 389 AbstractController and WebContentGenerator ................................................ 390 Other simple controllers ................................................................................ 391 The MultiActionController ............................................................................ 391 Command controllers .................................................................................... 394 16.4. Handler mappings ........................................................................................ 395 BeanNameUrlHandlerMapping ..................................................................... 396 SimpleUrlHandlerMapping ........................................................................... 397 Intercepting requests - the HandlerInterceptor interface ................................... 398 16.5. Views and resolving them ............................................................................. 400 Resolving views - the ViewResolver interface ................................................ 400 Chaining ViewResolvers ............................................................................... 402 Redirecting to views ..................................................................................... 402 RedirectView ....................................................................................... 403 The redirect: prefix ............................................................................... 403 The forward: prefix ............................................................................... 404 16.6. Using locales ............................................................................................... 404 AcceptHeaderLocaleResolver ........................................................................ 404 CookieLocaleResolver .................................................................................. 405 3.0.M3 Reference Documentation xii

Spring Framework

SessionLocaleResolver ................................................................................. 405 LocaleChangeInterceptor .............................................................................. 405 16.7. Using themes ............................................................................................... 406 Introduction ................................................................................................. 406 Defining themes ........................................................................................... 406 Theme resolvers ........................................................................................... 407 16.8. Spring's multipart (fileupload) support ........................................................... 407 Introduction ................................................................................................. 408 Using the MultipartResolver .......................................................................... 408 Handling a file upload in a form .................................................................... 409 16.9. Handling exceptions ..................................................................................... 412 16.10. Convention over configuration .................................................................... 412 The Controller - ControllerClassNameHandlerMapping .................................. 412 The Model - ModelMap (ModelAndView) ..................................................... 414 The View - RequestToViewNameTranslator .................................................. 415 16.11. Annotation-based controller configuration .................................................... 416 Setting up the dispatcher for annotation support .............................................. 417 Defining a controller with @Controller .......................................................... 417 Mapping requests with @RequestMapping ..................................................... 418 Advanced @RequestMapping options .................................................... 420 Supported handler method arguments and return types .................................... 421 Binding request parameters to method parameters with @RequestParam .......... 422 Providing a link to data from the model with @ModelAttribute ....................... 423 Specifying attributes to store in a Session with @SessionAttributes ................. 424 Mapping cookie values with the @CookieValue annotation ............................ 424 Mapping request header attributes with the @RequestHeader annotation .......... 424 Customizing WebDataBinder initialization ..................................................... 425 Customizing data binding with @InitBinder ........................................... 425 Configuring a custom WebBindingInitializer .......................................... 426 16.12. Further Resources ....................................................................................... 426 17. View technologies ................................................................................................... 427 17.1. Introduction ................................................................................................. 427 17.2. JSP & JSTL ................................................................................................. 427 View resolvers ............................................................................................. 427 'Plain-old' JSPs versus JSTL .......................................................................... 428 Additional tags facilitating development ........................................................ 428 Using Spring's form tag library ...................................................................... 428 Configuration ....................................................................................... 428 The form tag ........................................................................................ 429 The input tag ........................................................................................ 430 The checkbox tag .................................................................................. 430 The checkboxes tag .............................................................................. 432 The radiobutton tag ............................................................................... 432 The radiobuttons tag ............................................................................. 433 The password tag .................................................................................. 433 3.0.M3 Reference Documentation xiii

Spring Framework

The select tag ....................................................................................... 433 The option tag ...................................................................................... 434 The options tag ..................................................................................... 434 The textarea tag .................................................................................... 435 The hidden tag ...................................................................................... 435 The errors tag ....................................................................................... 435 17.3. Tiles ............................................................................................................ 437 Dependencies ............................................................................................... 438 How to integrate Tiles ................................................................................... 438 UrlBasedViewResolver ......................................................................... 438 ResourceBundleViewResolver .............................................................. 439 SimpleSpringPreparerFactory and SpringBeanPreparerFactory ................ 439 17.4. Velocity & FreeMarker ................................................................................. 440 Dependencies ............................................................................................... 440 Context configuration ................................................................................... 440 Creating templates ........................................................................................ 441 Advanced configuration ................................................................................ 441 velocity.properties ................................................................................ 441 FreeMarker .......................................................................................... 442 Bind support and form handling ..................................................................... 442 The bind macros ................................................................................... 442 Simple binding ..................................................................................... 443 Form input generation macros ............................................................... 444 HTML escaping and XHTML compliance ............................................. 448 17.5. XSLT .......................................................................................................... 449 My First Words ............................................................................................ 449 Bean definitions ................................................................................... 449 Standard MVC controller code .............................................................. 449 Convert the model data to XML ............................................................ 450 Defining the view properties .................................................................. 450 Document transformation ...................................................................... 451 Summary ..................................................................................................... 451 17.6. Document views (PDF/Excel) ....................................................................... 452 Introduction ................................................................................................. 452 Configuration and setup ................................................................................ 452 Document view definitions .................................................................... 452 Controller code ..................................................................................... 452 Subclassing for Excel views .................................................................. 453 Subclassing for PDF views .................................................................... 454 17.7. JasperReports ............................................................................................... 455 Dependencies ............................................................................................... 455 Configuration ............................................................................................... 455 Configuring the ViewResolver .............................................................. 455 Configuring the Views .......................................................................... 456 About Report Files ............................................................................... 456 3.0.M3 Reference Documentation xiv

Spring Framework

Using JasperReportsMultiFormatView ................................................... 456 Populating the ModelAndView ...................................................................... 457 Working with Sub-Reports ............................................................................ 458 Configuring Sub-Report Files ................................................................ 458 Configuring Sub-Report Data Sources ................................................... 459 Configuring Exporter Parameters ................................................................... 459 18. REST support ......................................................................................................... 461 18.1. Introduction ................................................................................................. 461 18.2. Creating RESTful services ............................................................................ 461 URI Templates ............................................................................................. 461 Mapping RESTful URLs with the @PathVariable annotation .................. 462 Mapping the request body with the @RequestBody annotation ................ 463 Returning multiple representations ................................................................. 464 Views .......................................................................................................... 466 Feed Views .......................................................................................... 467 XML Marshalling View ........................................................................ 468 HTTP Method Conversion ............................................................................ 468 Supporting Spring form tags .................................................................. 468 ETag support ................................................................................................ 468 Exception Handling ...................................................................................... 469 18.3. Accessing RESTful services on the Client ...................................................... 470 RestTemplate ............................................................................................... 470 HTTP Message Conversion ........................................................................... 472 StringHttpMessageConverter ................................................................. 473 FormHttpMessageConverter .................................................................. 473 ByteArrayMessageConverter ................................................................. 473 MarshallingHttpMessageConverter ........................................................ 473 SourceHttpMessageConverter ............................................................... 473 19. Integrating with other web frameworks ..................................................................... 474 19.1. Introduction ................................................................................................. 474 19.2. Common configuration ................................................................................. 475 19.3. JavaServer Faces 1.1 and 1.2 ......................................................................... 476 DelegatingVariableResolver (JSF 1.1/1.2) ...................................................... 477 SpringBeanVariableResolver (JSF 1.1/1.2) ..................................................... 477 SpringBeanFacesELResolver (JSF 1.2+) ........................................................ 478 FacesContextUtils ........................................................................................ 478 19.4. Apache Struts 1.x and 2.x ............................................................................. 478 ContextLoaderPlugin .................................................................................... 479 DelegatingRequestProcessor ................................................................. 480 DelegatingActionProxy ......................................................................... 480 ActionSupport Classes .................................................................................. 481 19.5. WebWork 2.x ............................................................................................... 481 19.6. Tapestry 3.x and 4.x ..................................................................................... 482 Injecting Spring-managed beans .................................................................... 483 Dependency Injecting Spring Beans into Tapestry pages ......................... 484 3.0.M3 Reference Documentation xv

Spring Framework

Component definition files .................................................................... 485 Adding abstract accessors ...................................................................... 486 Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style ............................................................................................................. 488 19.7. Further Resources ......................................................................................... 489 20. Portlet MVC Framework ......................................................................................... 490 20.1. Introduction ................................................................................................. 490 Controllers - The C in MVC .......................................................................... 491 Views - The V in MVC ................................................................................. 491 Web-scoped beans ........................................................................................ 492 20.2. The DispatcherPortlet ................................................................................... 492 20.3. The ViewRendererServlet ............................................................................. 494 20.4. Controllers ................................................................................................... 495 AbstractController and PortletContentGenerator ............................................. 496 Other simple controllers ................................................................................ 497 Command Controllers ................................................................................... 497 PortletWrappingController ............................................................................ 498 20.5. Handler mappings ........................................................................................ 499 PortletModeHandlerMapping ........................................................................ 500 ParameterHandlerMapping ............................................................................ 500 PortletModeParameterHandlerMapping ......................................................... 500 Adding HandlerInterceptors .......................................................................... 501 HandlerInterceptorAdapter ............................................................................ 502 ParameterMappingInterceptor ....................................................................... 502 20.6. Views and resolving them ............................................................................. 502 20.7. Multipart (file upload) support ...................................................................... 503 Using the PortletMultipartResolver ................................................................ 503 Handling a file upload in a form .................................................................... 504 20.8. Handling exceptions ..................................................................................... 507 20.9. Annotation-based controller configuration ..................................................... 507 Setting up the dispatcher for annotation support .............................................. 507 Defining a controller with @Controller .......................................................... 508 Mapping requests with @RequestMapping ..................................................... 508 Supported handler method arguments ............................................................ 510 Binding request parameters to method parameters with @RequestParam .......... 511 Providing a link to data from the model with @ModelAttribute ....................... 512 Specifying attributes to store in a Session with @SessionAttributes ................. 513 Customizing WebDataBinder initialization ..................................................... 513 Customizing data binding with @InitBinder ........................................... 513 Configuring a custom WebBindingInitializer .......................................... 514 20.10. Portlet application deployment .................................................................... 514 IV. Integration ...................................................................................................................... 515 21. Remoting and web services using Spring .................................................................. 516 21.1. Introduction ................................................................................................. 516 21.2. Exposing services using RMI ........................................................................ 517 3.0.M3 Reference Documentation xvi

Spring Framework

Exporting the service using the RmiServiceExporter ....................................... 517 Linking in the service at the client ................................................................. 518 21.3. Using Hessian or Burlap to remotely call services via HTTP ........................... 518 Wiring up the DispatcherServlet for Hessian and co. ....................................... 519 Exposing your beans by using the HessianServiceExporter .............................. 519 Linking in the service on the client ................................................................ 520 Using Burlap ................................................................................................ 520 Applying HTTP basic authentication to a service exposed through Hessian or Burlap .......................................................................................................... 520 21.4. Exposing services using HTTP invokers ........................................................ 521 Exposing the service object ........................................................................... 521 Linking in the service at the client ................................................................. 522 21.5. Web services ................................................................................................ 522 Exposing servlet-based web services using JAX-RPC ..................................... 523 Accessing web services using JAX-RPC ........................................................ 524 Registering JAX-RPC Bean Mappings ........................................................... 526 Registering your own JAX-RPC Handler ....................................................... 526 Exposing servlet-based web services using JAX-WS ...................................... 527 Exporting standalone web services using JAX-WS ......................................... 528 Exporting web services using the JAX-WS RI's Spring support ....................... 529 Accessing web services using JAX-WS .......................................................... 529 Exposing web services using XFire ................................................................ 530 21.6. JMS ............................................................................................................. 531 Server-side configuration .............................................................................. 532 Client-side configuration ............................................................................... 532 21.7. Auto-detection is not implemented for remote interfaces ................................. 533 21.8. Considerations when choosing a technology ................................................... 533 22. Enterprise Java Beans (EJB) integration ................................................................... 535 22.1. Introduction ................................................................................................. 535 22.2. Accessing EJBs ............................................................................................ 535 Concepts ...................................................................................................... 535 Accessing local SLSBs ................................................................................. 536 Accessing remote SLSBs .............................................................................. 537 Accessing EJB 2.x SLSBs versus EJB 3 SLSBs .............................................. 538 22.3. Using Spring's EJB implementation support classes ........................................ 538 EJB 2.x base classes ..................................................................................... 538 EJB 3 injection interceptor ............................................................................ 540 23. JMS (Java Message Service) .................................................................................... 542 23.1. Introduction ................................................................................................. 542 23.2. Using Spring JMS ........................................................................................ 543 JmsTemplate ................................................................................................ 543 Connections ................................................................................................. 544 Destination Management ............................................................................... 544 Message Listener Containers ......................................................................... 545 SimpleMessageListenerContainer .......................................................... 545 3.0.M3 Reference Documentation xvii

Spring Framework

DefaultMessageListenerContainer ......................................................... 546 ServerSessionMessageListenerContainer ................................................ 546 Transaction management ............................................................................... 546 23.3. Sending a Message ....................................................................................... 547 Using Message Converters ............................................................................ 548 SessionCallback and ProducerCallback .......................................................... 549 23.4. Receiving a message ..................................................................................... 549 Synchronous Reception ................................................................................. 549 Asynchronous Reception - Message-Driven POJOs ........................................ 549 The SessionAwareMessageListener interface ................................................. 550 The MessageListenerAdapter ........................................................................ 551 Processing messages within transactions ........................................................ 553 23.5. Support for JCA Message Endpoints .............................................................. 554 23.6. JMS Namespace Support .............................................................................. 555 24. JMX ....................................................................................................................... 560 24.1. Introduction ................................................................................................. 560 24.2. Exporting your beans to JMX ........................................................................ 560 Creating an MBeanServer ............................................................................. 561 Reusing an existing MBeanServer ................................................................. 562 Lazy-initialized MBeans ............................................................................... 563 Automatic registration of MBeans ................................................................. 563 Controlling the registration behavior .............................................................. 563 24.3. Controlling the management interface of your beans ....................................... 565 The MBeanInfoAssembler Interface .............................................................. 565 Using source-Level metadata ......................................................................... 565 Using JDK 5.0 Annotations ........................................................................... 568 Source-Level Metadata Types ....................................................................... 569 The AutodetectCapableMBeanInfoAssembler interface ................................... 571 Defining management interfaces using Java interfaces .................................... 571 Using MethodNameBasedMBeanInfoAssembler ............................................ 573 24.4. Controlling the ObjectNames for your beans .................................................. 573 Reading ObjectNames from Properties ........................................................... 574 Using the MetadataNamingStrategy ............................................................... 574 The element ........................................................... 575 24.5. JSR-160 Connectors ..................................................................................... 576 Server-side Connectors ................................................................................. 576 Client-side Connectors .................................................................................. 577 JMX over Burlap/Hessian/SOAP ................................................................... 577 24.6. Accessing MBeans via Proxies ...................................................................... 577 24.7. Notifications ................................................................................................ 578 Registering Listeners for Notifications ........................................................... 578 Publishing Notifications ................................................................................ 581 24.8. Further Resources ......................................................................................... 583 25. JCA CCI ................................................................................................................. 584 25.1. Introduction ................................................................................................. 584 3.0.M3 Reference Documentation xviii

Spring Framework

25.2. Configuring CCI .......................................................................................... 584 Connector configuration ................................................................................ 584 ConnectionFactory configuration in Spring .................................................... 585 Configuring CCI connections ........................................................................ 586 Using a single CCI connection ....................................................................... 586 25.3. Using Spring's CCI access support ................................................................. 587 Record conversion ........................................................................................ 587 The CciTemplate .......................................................................................... 588 DAO support ................................................................................................ 589 Automatic output record generation ............................................................... 590 Summary ..................................................................................................... 590 Using a CCI Connection and Interaction directly ............................................ 591 Example for CciTemplate usage .................................................................... 592 25.4. Modeling CCI access as operation objects ...................................................... 594 MappingRecordOperation ............................................................................. 594 MappingCommAreaOperation ....................................................................... 595 Automatic output record generation ............................................................... 595 Summary ..................................................................................................... 595 Example for MappingRecordOperation usage ................................................. 596 Example for MappingCommAreaOperation usage .......................................... 598 25.5. Transactions ................................................................................................. 599 26. Email ..................................................................................................................... 601 26.1. Introduction ................................................................................................. 601 26.2. Usage .......................................................................................................... 601 Basic MailSender and SimpleMailMessage usage ........................................... 602 Using the JavaMailSender and the MimeMessagePreparator ........................... 603 26.3. Using the JavaMail MimeMessageHelper ...................................................... 604 Sending attachments and inline resources ....................................................... 604 Attachments ......................................................................................... 604 Inline resources .................................................................................... 605 Creating email content using a templating library ........................................... 605 A Velocity-based example .................................................................... 606 27. Scheduling and Thread Pooling ................................................................................ 608 27.1. Introduction ................................................................................................. 608 27.2. Using the OpenSymphony Quartz Scheduler .................................................. 608 Using the JobDetailBean ............................................................................... 608 Using the MethodInvokingJobDetailFactoryBean ........................................... 609 Wiring up jobs using triggers and the SchedulerFactoryBean ........................... 610 27.3. Using JDK Timer support ............................................................................. 611 Creating custom timers ................................................................................. 611 Using the MethodInvokingTimerTaskFactoryBean ......................................... 611 Wrapping up: setting up the tasks using the TimerFactoryBean ........................ 612 27.4. The Spring TaskExecutor abstraction ............................................................. 612 TaskExecutor types ....................................................................................... 613 Using a TaskExecutor ................................................................................... 614 3.0.M3 Reference Documentation xix

Spring Framework

28. Dynamic language support ....................................................................................... 616 28.1. Introduction ................................................................................................. 616 28.2. A first example ............................................................................................. 616 28.3. Defining beans that are backed by dynamic languages .................................... 618 Common concepts ........................................................................................ 618 The element ............................................................... 619 Refreshable beans ................................................................................. 619 Inline dynamic language source files ...................................................... 622 Understanding Constructor Injection in the context of dynamic-language-backed beans ............................................................ 622 JRuby beans ................................................................................................. 623 Groovy beans ............................................................................................... 625 Customising Groovy objects via a callback ............................................. 627 BeanShell beans ........................................................................................... 628 28.4. Scenarios ..................................................................................................... 629 Scripted Spring MVC Controllers .................................................................. 629 Scripted Validators ....................................................................................... 630 28.5. Bits and bobs ............................................................................................... 631 AOP - advising scripted beans ....................................................................... 631 Scoping ........................................................................................................ 631 28.6. Further Resources ......................................................................................... 632 29. Annotations and Source Level Metadata Su