760
Reference Documentation (Work in progress) 3.0.0.M4 Copyright © 2004-2009 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 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 Reference 3.0.0.M1

Embed Size (px)

Citation preview

Reference Documentation(Work in progress)

3.0.0.M4Copyright 2004-2009 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 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 ContentsI. Overview of Spring Framework ..............................................................................................1 Preface ............................................................................................................................ ii 1. Introduction to Spring Framework ..................................................................................3 1.1. Dependency Injection .........................................................................................3 1.2. Modules ............................................................................................................4 Core Container .................................................................................................5 Data Access/Integration ....................................................................................6 Web .................................................................................................................6 AOP and Instrumentation ..................................................................................7 Test .................................................................................................................7 1.3. Usage scenarios .................................................................................................7 II. What's New in Spring 3.0 ...................................................................................................12 2. New Features and Enhancements in Spring 3.0 .............................................................13 2.1. Java 5 ..............................................................................................................13 2.2. Improved documentation ..................................................................................13 2.3. New getting started tutorial ...............................................................................13 2.4. New module organization and build system .......................................................14 2.5. Overview of new features .................................................................................15 Core APIs updated for Java 5 ..........................................................................15 Spring Expression Language ...........................................................................16 The Inversion of Control (IoC) container ..........................................................16 Java based bean metadata ........................................................................16 Defining bean metadata within components ..............................................17 The Data Tier .................................................................................................18 The Web Tier .................................................................................................18 Comprehensive REST support .................................................................18 @MVC additions ...................................................................................18 Declarative model validation ...........................................................................18 Early support for Java EE 6 .............................................................................18 Support for embedded databases ......................................................................19 III. Core Technologies ............................................................................................................20 3. The IoC container .......................................................................................................21 3.1. Introduction to the Spring IoC container and beans .............................................21 3.2. Container overview ..........................................................................................21 Configuration metadata ...................................................................................22 Instantiating a container ..................................................................................24 Composing XML-based configuration metadata .......................................25 Using the container .........................................................................................26 3.3. Bean overview .................................................................................................26 Naming beans .................................................................................................28

3.0.0.M4

Reference Documentation

ii

Spring Framework

Aliasing a bean outside the bean definition ...............................................28 Instantiating beans ..........................................................................................29 Instantiation with a constructor ................................................................30 Instantiation with a static factory method .................................................30 Instantiation using an instance factory method ..........................................31 3.4. Dependencies ...................................................................................................31 Dependency injection ......................................................................................31 Constructor-based dependency injection ...................................................32 Setter-based dependency injection ...........................................................33 Dependency resolution process ................................................................35 Examples of dependency injection ...........................................................36 Dependencies and configuration in detail .........................................................38 Straight values (primitives, Strings, and so on) .........................................38 References to other beans (collaborators) .................................................40 Inner beans .............................................................................................41 Collections .............................................................................................41 Null and empty string values ...................................................................43 XML shortcut with the p-namespace ........................................................44 Compound property names ......................................................................45 Using depends-on ...........................................................................................45 Lazy-initialized beans .....................................................................................46 Autowiring collaborators .................................................................................47 Limitations and disadvantages of autowiring ............................................48 Excluding a bean from autowiring ...........................................................49 Checking for dependencies ..............................................................................49 Method injection ............................................................................................50 Lookup method injection .........................................................................51 Arbitrary method replacement .................................................................52 3.5. Bean scopes .....................................................................................................53 The singleton scope ........................................................................................54 The prototype scope ........................................................................................55 Singleton beans with prototype-bean dependencies ...........................................56 Request, session, and global session scopes ......................................................57 Initial web configuration .........................................................................57 Request scope .........................................................................................58 Session scope .........................................................................................58 Global session scope ...............................................................................59 Scoped beans as dependencies .................................................................59 Custom scopes ...............................................................................................61 Creating a custom scope ..........................................................................62 Using a custom scope ..............................................................................62 3.6. Customizing the nature of a bean .......................................................................63 Lifecycle callbacks .........................................................................................64 Initialization callbacks ............................................................................64 Destruction callbacks ..............................................................................65 3.0.0.M4 Reference Documentation iii

Spring Framework

Default initialization and destroy methods ................................................65 Combining lifecycle mechanisms ............................................................66 Shutting down the Spring IoC container gracefully in non-web applications 67 ApplicationContextAware and BeanNameAware ..............................................68 3.7. Bean definition inheritance ...............................................................................69 3.8. Container extension points ................................................................................70 Customizing beans using the BeanPostProcessor Interface ................................70 Example: Hello World, BeanPostProcessor-style ......................................72 Example: The RequiredAnnotationBeanPostProcessor ..............................73 Customizing configuration metadata with BeanFactoryPostProcessor interface ...73 Example: the PropertyPlaceholderConfigurer ...........................................74 Example: the PropertyOverrideConfigurer ...............................................76 Customizing instantiation logic with the FactoryBean Interface .........................77 3.9. Annotation-based container configuration ..........................................................77 @Required .....................................................................................................78 @Autowired ...................................................................................................79 Fine-tuning annotation-based autowiring with qualifiers ...................................81 CustomAutowireConfigurer ............................................................................86 @Resource .....................................................................................................86 @PostConstruct and @PreDestroy ...................................................................88 3.10. Classpath scanning and managed components ..................................................88 @Component and further stereotype annotations ..............................................89 Automatically detecting classes and registering bean definitions ........................89 Using filters to customize scanning ..................................................................90 Defining bean metadata within components ......................................................91 Naming autodetected components ....................................................................93 Providing a scope for autodetected components ................................................93 Providing qualifier metadata with annotations ..................................................94 3.11. Java-based container configuration ..................................................................95 Using the @Configuration annotation ..............................................................95 Using the @Bean annotation ...........................................................................95 Declaring a bean .....................................................................................96 Injecting dependencies ............................................................................96 Receiving lifecycle callbacks ...................................................................96 Specifying bean scope .............................................................................98 Customizing bean naming .......................................................................99 3.12. Registering a LoadTimeWeaver ......................................................................99 3.13. Additional Capabilities of the ApplicationContext .......................................... 100 Internationalization using MessageSource ...................................................... 100 Standard and Custom Events ......................................................................... 103 Convenient access to low-level resources ....................................................... 106 Convenient ApplicationContext instantiation for web applications ................... 106 Deploying a Spring ApplicationContext as a J2EE RAR file ............................ 107 3.14. The BeanFactory .......................................................................................... 108 BeanFactory or ApplicationContext? ............................................................. 108 3.0.0.M4 Reference Documentation iv

Spring Framework

Glue code and the evil singleton .................................................................... 110 4. Resources ................................................................................................................. 111 4.1. Introduction ................................................................................................... 111 4.2. The Resource interface ................................................................................... 111 4.3. Built-in Resource implementations .................................................................. 112 UrlResource ................................................................................................. 112 ClassPathResource ....................................................................................... 113 FileSystemResource ..................................................................................... 113 ServletContextResource ................................................................................ 113 InputStreamResource .................................................................................... 113 ByteArrayResource ...................................................................................... 114 4.4. The ResourceLoader ....................................................................................... 114 4.5. The ResourceLoaderAware interface ............................................................... 115 4.6. Resources as dependencies ............................................................................. 116 4.7. Application contexts and Resource paths ......................................................... 116 Constructing application contexts .................................................................. 116 Constructing ClassPathXmlApplicationContext instances - shortcuts ....... 117 Wildcards in application context constructor resource paths ............................ 118 Ant-style Patterns ................................................................................. 118 The classpath*: prefix ........................................................................... 119 Other notes relating to wildcards ............................................................ 119 FileSystemResource caveats .......................................................................... 120 5. Validation, Data-binding, the BeanWrapper, and PropertyEditors ................................ 122 5.1. Introduction ................................................................................................... 122 5.2. Validation using Spring's Validator interface .................................................... 122 5.3. Resolving codes to error messages .................................................................. 124 5.4. Bean manipulation and the BeanWrapper ........................................................ 124 Setting and getting basic and nested properties ............................................... 125 Built-in PropertyEditor implementations ........................................................ 126 Registering additional custom PropertyEditors ....................................... 129 6. Spring Expression Language (SpEL) .......................................................................... 133 6.1. Introduction ................................................................................................... 133 6.2. Feature Overview ........................................................................................... 133 6.3. Expression Evaluation using Spring's Expression Interface ............................... 134 The EvaluationContext interface .................................................................... 136 Type Conversion .................................................................................. 136 6.4. Expression support for defining bean definitions .............................................. 137 XML based configuration ............................................................................. 137 Annotation-based configuration ..................................................................... 138 6.5. Language Reference ....................................................................................... 139 Literal expressions ........................................................................................ 139 Properties, Arrays, Lists, Maps, Indexers ........................................................ 139 Methods ....................................................................................................... 140 Operators ..................................................................................................... 141 Relational operators .............................................................................. 141 3.0.0.M4 Reference Documentation v

Spring Framework

Logical operators .................................................................................. 141 Mathematical operators ......................................................................... 142 Assignment .................................................................................................. 142 Types ........................................................................................................... 143 Constructors ................................................................................................. 143 Variables ...................................................................................................... 143 The #this variable ................................................................................. 144 Functions ..................................................................................................... 144 Ternary Operator (If-Then-Else) .................................................................... 144 The Elvis Operator ....................................................................................... 145 Safe Navigation operator ............................................................................... 146 Collection Selection ...................................................................................... 146 Collection Projection .................................................................................... 147 Expression templating ................................................................................... 147 6.6. Classes used in the examples ........................................................................... 147 7. Aspect Oriented Programming with Spring ................................................................. 151 7.1. Introduction ................................................................................................... 151 AOP concepts ............................................................................................... 151 Spring AOP capabilities and goals ................................................................. 153 AOP Proxies ................................................................................................ 154 7.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 7.3. Schema-based AOP support ............................................................................ 173 Declaring an aspect ....................................................................................... 173 Declaring a pointcut ...................................................................................... 174 Declaring advice ........................................................................................... 175 Before advice ....................................................................................... 175 After returning advice ........................................................................... 176 3.0.0.M4 Reference Documentation vi

Spring Framework

After throwing advice ........................................................................... 177 After (finally) advice ............................................................................ 177 Around advice ...................................................................................... 178 Advice parameters ................................................................................ 178 Advice ordering .................................................................................... 180 Introductions ................................................................................................ 180 Aspect instantiation models ........................................................................... 181 Advisors ...................................................................................................... 181 Example ....................................................................................................... 182 7.4. Choosing which AOP declaration style to use .................................................. 184 Spring AOP or full AspectJ? ......................................................................... 184 @AspectJ or XML for Spring AOP? .............................................................. 184 7.5. Mixing aspect types ........................................................................................ 185 7.6. Proxying mechanisms ..................................................................................... 185 Understanding AOP proxies .......................................................................... 186 7.7. Programmatic creation of @AspectJ Proxies .................................................... 189 7.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 7.9. Further Resources .......................................................................................... 202 8. Spring AOP APIs ...................................................................................................... 204 8.1. Introduction ................................................................................................... 204 8.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 8.3. Advice API in Spring ..................................................................................... 208 Advice lifecycles .......................................................................................... 208 Advice types in Spring .................................................................................. 208 Interception around advice .................................................................... 208 3.0.0.M4 Reference Documentation vii

Spring Framework

Before advice ....................................................................................... 209 Throws advice ...................................................................................... 210 After Returning advice .......................................................................... 211 Introduction advice ............................................................................... 212 8.4. Advisor API in Spring .................................................................................... 215 8.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 8.6. Concise proxy definitions ............................................................................... 221 8.7. Creating AOP proxies programmatically with the ProxyFactory ........................ 222 8.8. Manipulating advised objects .......................................................................... 222 8.9. Using the "autoproxy" facility ......................................................................... 224 Autoproxy bean definitions ........................................................................... 224 BeanNameAutoProxyCreator ................................................................ 224 DefaultAdvisorAutoProxyCreator .......................................................... 225 AbstractAdvisorAutoProxyCreator ........................................................ 226 Using metadata-driven auto-proxying ............................................................ 226 8.10. Using TargetSources .................................................................................... 229 Hot swappable target sources ......................................................................... 229 Pooling target sources ................................................................................... 230 Prototype target sources ................................................................................ 231 ThreadLocal target sources ............................................................................ 231 8.11. Defining new Advice types ........................................................................... 232 8.12. Further resources .......................................................................................... 232 9. Testing ..................................................................................................................... 234 9.1. Introduction ................................................................................................... 234 9.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 9.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 3.0.0.M4 Reference Documentation viii

Spring Framework

JDBC testing support .................................................................................... 238 Annotations .................................................................................................. 239 Spring TestContext Framework ..................................................................... 243 Key abstractions ................................................................................... 244 Context management and caching .......................................................... 245 Dependency Injection of test fixtures ..................................................... 247 Transaction management ....................................................................... 250 TestContext support classes ................................................................... 252 PetClinic example ......................................................................................... 255 9.4. Further Resources .......................................................................................... 257 IV. Data Access .................................................................................................................... 258 10. Transaction Management ......................................................................................... 259 10.1. Introduction to Spring Framework transaction management ............................ 259 10.2. Advantages of the Spring Framework's transaction support model ................... 259 Global transactions ....................................................................................... 260 Local transactions ......................................................................................... 260 Spring Framework's consistent programming model ....................................... 260 10.3. Understanding the Spring Framework transaction abstraction .......................... 261 10.4. Synchronizing resources with transactions ..................................................... 265 High-level synchronization approach ............................................................. 265 Low-level synchronization approach .............................................................. 265 TransactionAwareDataSourceProxy ............................................................... 266 10.5. Declarative transaction management .............................................................. 266 Understanding the Spring Framework's declarative transaction implementation 268 Example of declarative transaction implementation ......................................... 269 Rolling back a declarative transaction ............................................................ 273 Configuring different transactional semantics for different beans ..................... 274 settings ..................................................................................... 276 Using @Transactional ................................................................................... 277 @Transactional settings ........................................................................ 281 Transaction propagation ................................................................................ 282 Required .............................................................................................. 282 RequiresNew ........................................................................................ 283 Nested ................................................................................................. 284 Advising transactional operations .................................................................. 284 Using @Transactional with AspectJ ............................................................... 287 10.6. Programmatic transaction management .......................................................... 288 Using the TransactionTemplate ..................................................................... 288 Specifying transaction settings ............................................................... 289 Using the PlatformTransactionManager ......................................................... 290 10.7. Choosing between programmatic and declarative transaction management ....... 291 10.8. Application server-specific integration ........................................................... 291 IBM WebSphere ........................................................................................... 292 BEA WebLogic Server ................................................................................. 292 Oracle OC4J ................................................................................................. 292 3.0.0.M4 Reference Documentation ix

Spring Framework

10.9. Solutions to common problems ..................................................................... 292 Use of the wrong transaction manager for a specific DataSource ...................... 292 10.10. Further Resources ....................................................................................... 292 11. DAO support .......................................................................................................... 294 11.1. Introduction ................................................................................................. 294 11.2. Consistent exception hierarchy ...................................................................... 294 11.3. Annotations used for configuring DAO or Repository classes .......................... 295 12. Data access using JDBC .......................................................................................... 297 12.1. Introduction ................................................................................................. 297 Choosing a style ........................................................................................... 297 The package hierarchy .................................................................................. 298 12.2. Using the JDBC Core classes to control basic JDBC processing and error handling ............................................................................................................................. 299 JdbcTemplate ............................................................................................... 299 Examples ............................................................................................. 299 JdbcTemplate idioms (best practices) ..................................................... 301 NamedParameterJdbcTemplate ...................................................................... 303 SimpleJdbcTemplate ..................................................................................... 305 DataSource .................................................................................................. 307 SQLExceptionTranslator ............................................................................... 308 Executing statements .................................................................................... 309 Running Queries ........................................................................................... 310 Updating the database ................................................................................... 311 Retrieving auto-generated keys ...................................................................... 311 12.3. Controlling database connections .................................................................. 312 DataSourceUtils ........................................................................................... 312 SmartDataSource .......................................................................................... 312 AbstractDataSource ...................................................................................... 312 SingleConnectionDataSource ........................................................................ 312 DriverManagerDataSource ............................................................................ 313 TransactionAwareDataSourceProxy ............................................................... 313 DataSourceTransactionManager .................................................................... 313 NativeJdbcExtractor ..................................................................................... 314 12.4. JDBC batch operations ................................................................................. 314 Batch operations with the JdbcTemplate ......................................................... 314 Batch operations with the SimpleJdbcTemplate .............................................. 315 12.5. Simplifying JDBC operations with the SimpleJdbc classes .............................. 316 Inserting data using SimpleJdbcInsert ............................................................ 317 Retrieving auto-generated keys using SimpleJdbcInsert ................................... 317 Specifying the columns to use for a SimpleJdbcInsert ..................................... 318 Using SqlParameterSource to provide parameter values .................................. 319 Calling a stored procedure using SimpleJdbcCall ............................................ 320 Declaring parameters to use for a SimpleJdbcCall ........................................... 321 How to define SqlParameters ......................................................................... 322 Calling a stored function using SimpleJdbcCall .............................................. 323 3.0.0.M4 Reference Documentation x

Spring Framework

Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................. 324 12.6. Modeling JDBC operations as Java objects .................................................... 325 SqlQuery ...................................................................................................... 325 MappingSqlQuery ........................................................................................ 325 SqlUpdate .................................................................................................... 326 StoredProcedure ........................................................................................... 327 12.7. Common issues with parameter and data value handling ................................. 331 Providing SQL type information for parameters .............................................. 331 Handling BLOB and CLOB objects ............................................................... 331 Passing in lists of values for IN clause ........................................................... 333 Handling complex types for stored procedure calls ......................................... 333 12.8. Embedded database support .......................................................................... 334 Why use an embedded database? ................................................................... 335 Creating an embedded database instance using Spring XML ........................... 335 Creating an embedded database instance programatically ................................ 335 Extending the embedded database support ...................................................... 335 Using HSQL ................................................................................................ 336 Using H2 ..................................................................................................... 336 Using Derby ................................................................................................. 336 Unit testing data access logic with an EmbeddedDatabase ............................... 336 13. Object Relational Mapping (ORM) Data Access ....................................................... 337 13.1. Introduction to ORM with Spring .................................................................. 337 13.2. General ORM integration considerations ........................................................ 338 Resource and transaction management ........................................................... 338 Exception translation .................................................................................... 339 13.3. Hibernate ..................................................................................................... 340 SessionFactory setup in a Spring container ..................................................... 340 Implementing DAOs based on plain Hibernate 3 API ...................................... 341 Declarative transaction demarcation ............................................................... 342 Programmatic transaction demarcation ........................................................... 344 Transaction management strategies ................................................................ 345 Comparing container-managed and locally defined resources .......................... 347 Spurious application server warnings with Hibernate ...................................... 348 13.4. JDO ............................................................................................................. 349 PersistenceManagerFactory setup .................................................................. 349 Implementing DAOs based on the plain JDO API ........................................... 350 Transaction management ............................................................................... 352 JdoDialect .................................................................................................... 353 13.5. JPA ............................................................................................................. 354 Three options for JPA setup in a Spring environment ...................................... 354 LocalEntityManagerFactoryBean ........................................................... 354 Obtaining an EntityManagerFactory from JNDI ...................................... 355 LocalContainerEntityManagerFactoryBean ............................................ 355 Dealing with multiple persistence units .................................................. 359 Implementing DAOs based on plain JPA ........................................................ 360 3.0.0.M4 Reference Documentation xi

Spring Framework

Transaction Management .............................................................................. 362 JpaDialect .................................................................................................... 363 13.6. iBATIS SQL Maps ....................................................................................... 364 Setting up the SqlMapClient .......................................................................... 364 Using SqlMapClientTemplate and SqlMapClientDaoSupport .......................... 366 Implementing DAOs based on plain iBATIS API ........................................... 366 14. Marshalling XML using O/X Mappers ..................................................................... 368 14.1. Introduction ................................................................................................. 368 14.2. Marshaller and Unmarshaller ........................................................................ 368 Marshaller .................................................................................................... 368 Unmarshaller ................................................................................................ 369 XmlMappingException ................................................................................. 370 14.3. Using Marshaller and Unmarshaller ............................................................... 370 14.4. XML Schema-based Configuration ................................................................ 372 14.5. JAXB .......................................................................................................... 373 Jaxb2Marshaller ........................................................................................... 373 XML Schema-based Configuration ........................................................ 374 14.6. Castor .......................................................................................................... 374 CastorMarshaller .......................................................................................... 374 Mapping ...................................................................................................... 375 14.7. XMLBeans .................................................................................................. 375 XmlBeansMarshaller .................................................................................... 375 XML Schema-based Configuration ........................................................ 375 14.8. JiBX ............................................................................................................ 376 JibxMarshaller .............................................................................................. 376 XML Schema-based Configuration ........................................................ 376 14.9. XStream ...................................................................................................... 377 XStreamMarshaller ....................................................................................... 377 V. The Web .......................................................................................................................... 378 15. Web MVC framework ............................................................................................. 379 15.1. Introduction to Spring Web MVC framework ................................................. 379 Features of Spring Web MVC ....................................................................... 380 Pluggability of other MVC implementations ................................................... 381 15.2. The DispatcherServlet .................................................................................. 381 15.3. Implementing Controllers ............................................................................. 386 Defining a controller with @Controller .......................................................... 387 Mapping requests with @RequestMapping ..................................................... 387 URI Templates ..................................................................................... 389 Advanced @RequestMapping options .................................................... 390 Supported handler method arguments and return types ............................ 391 Binding request parameters to method parameters with @RequestParam .. 394 Mapping the request body with the @RequestBody annotation ................ 394 Mapping the response body with the @ResponseBody annotation ........... 395 Providing a link to data from the model with @ModelAttribute ............... 395 Specifying attributes to store in a session with @SessionAttributes .......... 396 3.0.0.M4 Reference Documentation xii

Spring Framework

Mapping cookie values with the @CookieValue annotation .................... 397 Mapping request header attributes with the @RequestHeader annotation .. 397 Customizing WebDataBinder initialization ............................................. 398 15.4. Handler mappings ........................................................................................ 399 Intercepting requests - the HandlerInterceptor interface ................................... 400 15.5. Resolving views ........................................................................................... 401 Resolving views with the ViewResolver interface ........................................... 401 Chaining ViewResolvers ............................................................................... 403 Redirecting to views ..................................................................................... 404 RedirectView ....................................................................................... 404 The redirect: prefix ............................................................................... 405 The forward: prefix ............................................................................... 405 ContentNegotiatingViewResolver .................................................................. 405 15.6. Using locales ............................................................................................... 408 AcceptHeaderLocaleResolver ........................................................................ 408 CookieLocaleResolver .................................................................................. 408 SessionLocaleResolver ................................................................................. 409 LocaleChangeInterceptor .............................................................................. 409 15.7. Using themes ............................................................................................... 409 Overview of themes ...................................................................................... 409 Defining themes ........................................................................................... 410 Theme resolvers ........................................................................................... 410 15.8. Spring's multipart (fileupload) support ........................................................... 411 Introduction ................................................................................................. 411 Using the MultipartResolver .......................................................................... 411 Handling a file upload in a form .................................................................... 412 15.9. Handling exceptions ..................................................................................... 415 HandlerExceptionResolver ............................................................................ 415 @ExceptionHandler ...................................................................................... 415 15.10. Convention over configuration support ........................................................ 416 The Controller ControllerClassNameHandlerMapping .................................... 416 The Model ModelMap (ModelAndView) ....................................................... 417 The View - RequestToViewNameTranslator .................................................. 419 15.11. ETag support .............................................................................................. 420 15.12. More Spring Web MVC Resources .............................................................. 421 16. View technologies ................................................................................................... 422 16.1. Introduction ................................................................................................. 422 16.2. JSP & JSTL ................................................................................................. 422 View resolvers ............................................................................................. 422 'Plain-old' JSPs versus JSTL .......................................................................... 423 Additional tags facilitating development ........................................................ 423 Using Spring's form tag library ...................................................................... 423 Configuration ....................................................................................... 423 The form tag ........................................................................................ 423 The input tag ........................................................................................ 425 3.0.0.M4 Reference Documentation xiii

Spring Framework

The checkbox tag .................................................................................. 425 The checkboxes tag .............................................................................. 427 The radiobutton tag ............................................................................... 427 The radiobuttons tag ............................................................................. 427 The password tag .................................................................................. 428 The select tag ....................................................................................... 428 The option tag ...................................................................................... 429 The options tag ..................................................................................... 429 The textarea tag .................................................................................... 430 The hidden tag ...................................................................................... 430 The errors tag ....................................................................................... 430 HTTP Method Conversion .................................................................... 432 16.3. Tiles ............................................................................................................ 433 Dependencies ............................................................................................... 433 How to integrate Tiles ................................................................................... 434 UrlBasedViewResolver ......................................................................... 434 ResourceBundleViewResolver .............................................................. 434 SimpleSpringPreparerFactory and SpringBeanPreparerFactory ................ 435 16.4. Velocity & FreeMarker ................................................................................. 436 Dependencies ............................................................................................... 436 Context configuration ................................................................................... 436 Creating templates ........................................................................................ 437 Advanced configuration ................................................................................ 437 velocity.properties ................................................................................ 437 FreeMarker .......................................................................................... 438 Bind support and form handling ..................................................................... 438 The bind macros ................................................................................... 438 Simple binding ..................................................................................... 439 Form input generation macros ............................................................... 440 HTML escaping and XHTML compliance ............................................. 444 16.5. XSLT .......................................................................................................... 444 My First Words ............................................................................................ 445 Bean definitions ................................................................................... 445 Standard MVC controller code .............................................................. 445 Convert the model data to XML ............................................................ 446 Defining the view properties .................................................................. 446 Document transformation ...................................................................... 447 Summary ..................................................................................................... 447 16.6. Document views (PDF/Excel) ....................................................................... 448 Introduction ................................................................................................. 448 Configuration and setup ................................................................................ 448 Document view definitions .................................................................... 448 Controller code ..................................................................................... 448 Subclassing for Excel views .................................................................. 449 Subclassing for PDF views .................................................................... 450 3.0.0.M4 Reference Documentation xiv

Spring Framework

16.7. JasperReports ............................................................................................... 450 Dependencies ............................................................................................... 451 Configuration ............................................................................................... 451 Configuring the ViewResolver .............................................................. 451 Configuring the Views .......................................................................... 451 About Report Files ............................................................................... 452 Using JasperReportsMultiFormatView ................................................... 452 Populating the ModelAndView ...................................................................... 453 Working with Sub-Reports ............................................................................ 454 Configuring Sub-Report Files ................................................................ 454 Configuring Sub-Report Data Sources ................................................... 455 Configuring Exporter Parameters ................................................................... 455 16.8. Feed Views .................................................................................................. 456 16.9. XML Marshalling View ................................................................................ 457 17. Integrating with other web frameworks ..................................................................... 458 17.1. Introduction ................................................................................................. 458 17.2. Common configuration ................................................................................. 459 17.3. JavaServer Faces 1.1 and 1.2 ......................................................................... 460 DelegatingVariableResolver (JSF 1.1/1.2) ...................................................... 461 SpringBeanVariableResolver (JSF 1.1/1.2) ..................................................... 461 SpringBeanFacesELResolver (JSF 1.2+) ........................................................ 462 FacesContextUtils ........................................................................................ 462 17.4. Apache Struts 1.x and 2.x ............................................................................. 462 ContextLoaderPlugin .................................................................................... 463 DelegatingRequestProcessor ................................................................. 464 DelegatingActionProxy ......................................................................... 464 ActionSupport Classes .................................................................................. 465 17.5. WebWork 2.x ............................................................................................... 465 17.6. Tapestry 3.x and 4.x ..................................................................................... 466 Injecting Spring-managed beans .................................................................... 467 Dependency Injecting Spring Beans into Tapestry pages ......................... 468 Component definition files .................................................................... 469 Adding abstract accessors ...................................................................... 470 Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style ............................................................................................................. 472 17.7. Further Resources ......................................................................................... 473 18. Portlet MVC Framework ......................................................................................... 475 18.1. Introduction ................................................................................................. 475 Controllers - The C in MVC .......................................................................... 476 Views - The V in MVC ................................................................................. 476 Web-scoped beans ........................................................................................ 477 18.2. The DispatcherPortlet ................................................................................... 477 18.3. The ViewRendererServlet ............................................................................. 479 18.4. Controllers ................................................................................................... 480 AbstractController and PortletContentGenerator ............................................. 481 3.0.0.M4 Reference Documentation xv

Spring Framework

Other simple controllers ................................................................................ 482 Command Controllers ................................................................................... 482 PortletWrappingController ............................................................................ 483 18.5. Handler mappings ........................................................................................ 484 PortletModeHandlerMapping ........................................................................ 485 ParameterHandlerMapping ............................................................................ 485 PortletModeParameterHandlerMapping ......................................................... 485 Adding HandlerInterceptors .......................................................................... 486 HandlerInterceptorAdapter ............................................................................ 487 ParameterMappingInterceptor ....................................................................... 487 18.6. Views and resolving them ............................................................................. 487 18.7. Multipart (file upload) support ...................................................................... 488 Using the PortletMultipartResolver ................................................................ 488 Handling a file upload in a form .................................................................... 489 18.8. Handling exceptions ..................................................................................... 492 18.9. Annotation-based controller configuration ..................................................... 492 Setting up the dispatcher for annotation support .............................................. 492 Defining a controller with @Controller .......................................................... 493 Mapping requests with @RequestMapping ..................................................... 493 Supported handler method arguments ............................................................ 495 Binding request parameters to method parameters with @RequestParam .......... 496 Providing a link to data from the model with @ModelAttribute ....................... 497 Specifying attributes to store in a Session with @SessionAttributes ................. 498 Customizing WebDataBinder initialization ..................................................... 498 Customizing data binding with @InitBinder ........................................... 498 Configuring a custom WebBindingInitializer .......................................... 499 18.10. Portlet application deployment .................................................................... 499 VI. Integration ...................................................................................................................... 500 19. Remoting and web services using Spring .................................................................. 501 19.1. Introduction ................................................................................................. 501 19.2. Exposing services using RMI ........................................................................ 502 Exporting the service using the RmiServiceExporter ....................................... 502 Linking in the service at the client ................................................................. 503 19.3. Using Hessian or Burlap to remotely call services via HTTP ........................... 504 Wiring up the DispatcherServlet for Hessian and co. ....................................... 504 Exposing your beans by using the HessianServiceExporter .............................. 504 Linking in the service on the client ................................................................ 505 Using Burlap ................................................................................................ 505 Applying HTTP basic authentication to a service exposed through Hessian or Burlap .......................................................................................................... 506 19.4. Exposing services using HTTP invokers ........................................................ 506 Exposing the service object ........................................................................... 506 Linking in the service at the client ................................................................. 507 19.5. Web services ................................................................................................ 508 Exposing servlet-based web services using JAX-RPC ..................................... 509 3.0.0.M4 Reference Documentation xvi

Spring Framework

Accessing web services using JAX-RPC ........................................................ 509 Registering JAX-RPC Bean Mappings ........................................................... 511 Registering your own JAX-RPC Handler ....................................................... 512 Exposing servlet-based web services using JAX-WS ...................................... 512 Exporting standalone web services using JAX-WS ......................................... 513 Exporting web services using the JAX-WS RI's Spring support ....................... 514 Accessing web services using JAX-WS .......................................................... 514 Exposing web services using XFire ................................................................ 515 19.6. JMS ............................................................................................................. 516 Server-side configuration .............................................................................. 517 Client-side configuration ............................................................................... 518 19.7. Auto-detection is not implemented for remote interfaces ................................. 518 19.8. Considerations when choosing a technology ................................................... 519 19.9. Accessing RESTful services on the Client ...................................................... 519 RestTemplate ............................................................................................... 520 HTTP Message Conversion ........................................................................... 522 StringHttpMessageConverter ................................................................. 523 FormHttpMessageConverter .................................................................. 523 ByteArrayMessageConverter ................................................................. 523 MarshallingHttpMessageConverter ........................................................ 523 SourceHttpMessageConverter ............................................................... 523 BufferedImageHttpMessageConverter ................................................... 523 20. Enterprise JavaBeans (EJB) integration .................................................................... 525 20.1. Introduction ................................................................................................. 525 20.2. Accessing EJBs ............................................................................................ 525 Concepts ...................................................................................................... 525 Accessing local SLSBs ................................................................................. 526 Accessing remote SLSBs .............................................................................. 527 Accessing EJB 2.x SLSBs versus EJB 3 SLSBs .............................................. 528 20.3. Using Spring's EJB implementation support classes ........................................ 528 EJB 2.x base classes ..................................................................................... 528 EJB 3 injection interceptor ............................................................................ 530 21. JMS (Java Message Service) .................................................................................... 532 21.1. Introduction ................................................................................................. 532 21.2. Using Spring JMS ........................................................................................ 532 JmsTemplate ................................................................................................ 532 Connections ................................................................................................. 533 Caching Messaging Resources ............................................................... 534 SingleConnectionFactory ...................................................................... 534 CachingConnectionFactory ................................................................... 534 Destination Management ............................................................................... 534 Message Listener Containers ......................................................................... 535 SimpleMessageListenerContainer .......................................................... 536 DefaultMessageListenerContainer ......................................................... 536 ServerSessionMessageListenerContainer ................................................ 536 3.0.0.M4 Reference Documentation xvii

Spring Framework

Transaction management ............................................................................... 536 21.3. Sending a Message ....................................................................................... 537 Using Message Converters ............................................................................ 538 SessionCallback and ProducerCallback .......................................................... 539 21.4. Receiving a message ..................................................................................... 539 Synchronous Reception ................................................................................. 539 Asynchronous Reception - Message-Driven POJOs ........................................ 539 The SessionAwareMessageListener interface ................................................. 540 The MessageListenerAdapter ........................................................................ 541 Processing messages within transactions ........................................................ 542 21.5. Support for JCA Message Endpoints .............................................................. 543 21.6. JMS Namespace Support .............................................................................. 545 22. JMX ....................................................................................................................... 550 22.1. Introduction ................................................................................................. 550 22.2. Exporting your beans to JMX ........................................................................ 550 Creating an MBeanServer ............................................................................. 551 Reusing an existing MBeanServer ................................................................. 552 Lazy-initialized MBeans ............................................................................... 553 Automatic registration of MBeans ................................................................. 553 Controlling the registration behavior .............................................................. 553 22.3. Controlling the management interface of your beans ....................................... 555 The MBeanInfoAssembler Interface .............................................................. 555 Using source-Level metadata ......................................................................... 555 Using JDK 5.0 Annotations ........................................................................... 558 Source-Level Metadata Types ....................................................................... 559 The AutodetectCapableMBeanInfoAssembler interface ................................... 561 Defining management interfaces using Java interfaces .................................... 561 Using MethodNameBasedMBeanInfoAssembler ............................................ 563 22.4. Controlling the ObjectNames for your beans .................................................. 563 Reading ObjectNames from Properties ........................................................... 564 Using the MetadataNamingStrategy ............................................................... 564 The element ........................................................... 565 22.5. JSR-160 Connectors ..................................................................................... 566 Server-side Connectors ................................................................................. 566 Client-side Connectors .................................................................................. 567 JMX over Burlap/Hessian/SOAP ................................................................... 567 22.6. Accessing MBeans via Proxies ...................................................................... 567 22.7. Notifications ................................................................................................ 568 Registering Listeners for Notifications ........................................................... 568 Publishing Notifications ................................................................................ 571 22.8. Further Resources ......................................................................................... 573 23. JCA CCI ................................................................................................................. 574 23.1. Introduction ................................................................................................. 574 23.2. Configuring CCI .......................................................................................... 574 Connector configuration ................................................................................ 574 3.0.0.M4 Reference Documentation xviii

Spring Framework

ConnectionFactory configuration in Spring .................................................... 575 Configuring CCI connections ........................................................................ 576 Using a single CCI connection ....................................................................... 576 23.3. Using Spring's CCI access support ................................................................. 577 Record conversion ........................................................................................ 577 The CciTemplate .......................................................................................... 578 DAO support ................................................................................................ 579 Automatic output record generation ............................................................... 580 Summary ..................................................................................................... 580 Using a CCI Connection and Interaction directly ............................................ 581 Example for CciTemplate usage .................................................................... 582 23.4. Modeling CCI access as operation objects ...................................................... 584 MappingRecordOperation ............................................................................. 584 MappingCommAreaOperation ....................................................................... 585 Automatic output record generation ............................................................... 585 Summary ..................................................................................................... 585 Example for MappingRecordOperation usage ................................................. 586 Example for MappingCommAreaOperation usage .......................................... 588 23.5. Transactions ................................................................................................. 589 24. Email ..................................................................................................................... 591 24.1. Introduction ................................................................................................. 591 24.2. Usage .......................................................................................................... 591 Basic MailSender and SimpleMailMessage usage ........................................... 592 Using the JavaMailSender and the MimeMessagePreparator ........................... 593 24.3. Using the JavaMail MimeMessageHelper ...................................................... 594 Sending attachments and inline resources ....................................................... 594 Attachments ......................................................................................... 594 Inline resources .................................................................................... 595 Creating email content using a templating library ........................................... 595 A Velocity-based example .................................................................... 596 25. Scheduling and Thread Pooling ................................................................................ 598 25.1. Introduction ................................................................................................. 598 25.2. Using the OpenSymphony Quartz Scheduler .................................................. 598 Using the JobDetailBean ............................................................................... 598 Using the MethodInvokingJobDetailFactoryBean ........................................... 599 Wiring up jobs using triggers and the SchedulerFactoryBean ........................... 600 25.3. Using JDK Timer support ............................................................................. 601 Creating custom timers ................................................................................. 601 Using the MethodInvokingTimerTaskFactoryBean ......................................... 601 Wrapping up: setting up the tasks using the TimerFactoryBean ........................ 602 25.4. The Spring TaskExecutor abstraction ............................................................. 602 TaskExecutor types ....................................................................................... 603 Using a TaskExecutor ................................................................................... 604 26. Dynamic language support ....................................................................................... 606 26.1. Introduction ................................................................................................. 606 3.0.0.M4 Reference Documentation xix

Spring Framework

26.2. A first example ............................................................................................. 606 26.3. Defining beans that are backed by dynamic languages .................................... 608 Common concepts ........................................................................................ 608 The element ............................................................... 609 Refreshable beans ................................................................................. 609 Inline dynamic language source files ...................................................... 612 Understanding Constructor Injection in the context of dynamic-language-backed beans ............................................................ 612 JRuby beans ................................................................................................. 613 Groovy beans ............................................................................................... 615 Customising Groovy objects via a callback ............................................. 617 BeanShell beans ........................................................................................... 618 26.4. Scenarios ..................................................................................................... 619 Scripted Spring MVC Controllers .................................................................. 619 Scripted Validators ....................................................................................... 620 26.5. Bits and bobs ............................................................................................... 621 AOP - advising scripted beans ....................................................................... 621 Scoping ........................................................................................................ 621 26.6. Further Resources ......................................................................................... 622 27. Annotations and Source Level Metadata Support ...................................................... 623 27.1. Introduction ................................................................................................. 623 27.2. Annotations ................................................................................................. 623 @Required ................................................................................................... 623 Other @Annotations in Spring ....................................................................... 625 VII. Appendices ................................................................................................................... 626 A. Classic Spring Usage ................................................................................................ 627 A.1. Classic ORM usage .................................................................