Spring Framework Reference Documentation v3.1

Alex EvangInternet and Web Development

Aug 30, 2011 (6 years and 24 days ago)

6,991 views

The Spring Framework is a lightweight solution and a potential one-stop-shop for building your enterprise-ready applications. However, Spring is modular, allowing you to use only those parts that you need, without having to bring in the rest. You can use the IoC container, with Struts on top, but you can also use only the Hibernate integration code or the JDBC abstraction layer. The Spring Framework supports declarative transaction management, remote access to your logic through RMI or web services, and various options for persisting your data. It offers a full-featured MVC framework, and enables you to integrate AOP transparently into your software.

Reference Documentation
3.1
Copyright ©2004-2011 Rod Johnson,Juergen Hoeller,Keith Donald,Colin Sampaleanu,Rob
Harrop,Alef Arendsen,Thomas Risberg,Darren Davison,Dmitriy Kopylenko,Mark Pollack,
Thierry Templier,Erwin Vervaet,Portia Tung,Ben Hale,Adrian Colyer,John Lewis,Costin
Leau,Mark Fisher,Sam Brannen,Ramnivas Laddad,Arjen Poutsma,Chris Beams,Tareq
Abedrabbo,Andy Clement,Dave Syer,Oliver Gierke,Rossen Stoyanchev
Copies of this document may be made for your own use and for distribution to others,provided
that you do not charge any fee for such copies and further provided that each copy contains this
Copyright Notice,whether distributed in print or electronically.
Table of Contents
I.Overview of Spring Framework..............................................................................................1
1.Introduction to Spring Framework..................................................................................2
1.1.Dependency Injection and Inversion of Control....................................................2
1.2.Modules............................................................................................................3
Core Container.................................................................................................3
Data Access/Integration....................................................................................3
Web.................................................................................................................4
AOP and Instrumentation..................................................................................4
Test.................................................................................................................4
1.3.Usage scenarios.................................................................................................5
Dependency Management and Naming Conventions...........................................6
Spring Dependencies and Depending on Spring..........................................8
Maven Dependency Management..............................................................8
Ivy Dependency Management.................................................................10
Logging.........................................................................................................10
Not Using Commons Logging.................................................................11
Using SLF4J..........................................................................................11
Using Log4J...........................................................................................13
II.What's New in Spring 3......................................................................................................15
2.New Features and Enhancements in Spring 3.0.............................................................16
2.1.Java 5..............................................................................................................16
2.2.Improved documentation..................................................................................16
2.3.New articles and tutorials..................................................................................16
2.4.New module organization and build system.......................................................17
2.5.Overview of new features.................................................................................18
Core APIs updated for Java 5..........................................................................19
Spring Expression Language...........................................................................19
The Inversion of Control (IoC) container..........................................................20
Java based bean metadata........................................................................20
Defining bean metadata within components..............................................21
General purpose type conversion systemand field formatting system.................21
The Data Tier.................................................................................................21
The Web Tier.................................................................................................22
Comprehensive REST support.................................................................22
@MVC additions...................................................................................22
Declarative model validation...........................................................................22
Early support for Java EE 6.............................................................................22
Support for embedded databases......................................................................22
3.New Features and Enhancements in Spring 3.1.............................................................23
3.1.Overview of new features.................................................................................23
Spring Framework
3.1 Reference Documentation ii
Cache Abstraction..........................................................................................23
Bean Definition Profiles..................................................................................23
Environment Abstraction................................................................................23
PropertySource Abstraction.............................................................................23
Code equivalents for Spring's XML namespaces...............................................24
Builder-style APIs for code-based Hibernate configuration................................24
TestContext framework support for @Configuration classes and bean definition
profiles..........................................................................................................24
c:namespace for more concise constructor injection.........................................24
Support for injection against non-standard JavaBeans setters.............................24
Support for Servlet 3 code-based configuration of Servlet Container..................25
Support for Servlet 3 MultipartResolver...........................................................25
JPA EntityManagerFactory bootstrapping without persistence.xml....................25
New HandlerMethod-based Support Classes For Annotated Controller Processing
.......................................................................................................................25
Consumes and Produces @RequestMapping Conditions...................................26
Working With URI Template Variables In Controller Methods..........................26
Validation For @RequestBody Method Arguments...........................................27
III.Core Technologies............................................................................................................28
4.The IoC container.......................................................................................................29
4.1.Introduction to the Spring IoC container and beans.............................................29
4.2.Container overview..........................................................................................29
Configuration metadata...................................................................................30
Instantiating a container..................................................................................31
Composing XML-based configuration metadata.......................................33
Using the container.........................................................................................33
4.3.Bean overview.................................................................................................34
Naming beans.................................................................................................35
Aliasing a bean outside the bean definition...............................................36
Instantiating beans..........................................................................................37
Instantiation with a constructor................................................................37
Instantiation with a static factory method.................................................38
Instantiation using an instance factory method..........................................38
4.4.Dependencies...................................................................................................40
Dependency injection......................................................................................40
Constructor-based dependency injection...................................................40
Setter-based dependency injection...........................................................42
Dependency resolution process................................................................43
Examples of dependency injection...........................................................45
Dependencies and configuration in detail.........................................................47
Straight values (primitives,Strings,and so on).........................................47
References to other beans (collaborators).................................................48
Inner beans.............................................................................................49
Collections.............................................................................................50
Null and empty string values...................................................................52
Spring Framework
3.1 Reference Documentation iii
XML shortcut with the p-namespace........................................................53
XML shortcut with the c-namespace........................................................54
Compound property names......................................................................55
Using depends-on...........................................................................................55
Lazy-initialized beans.....................................................................................56
Autowiring collaborators.................................................................................56
Limitations and disadvantages of autowiring............................................58
Excluding a bean fromautowiring...........................................................58
Method injection............................................................................................59
Lookup method injection.........................................................................60
Arbitrary method replacement.................................................................61
4.5.Bean scopes.....................................................................................................62
The singleton scope........................................................................................63
The prototype scope........................................................................................64
Singleton beans with prototype-bean dependencies...........................................65
Request,session,and global session scopes......................................................65
Initial web configuration.........................................................................65
Request scope.........................................................................................66
Session scope.........................................................................................66
Global session scope...............................................................................67
Scoped beans as dependencies.................................................................67
Customscopes...............................................................................................69
Creating a customscope..........................................................................69
Using a customscope..............................................................................70
4.6.Customizing the nature of a bean.......................................................................71
Lifecycle callbacks.........................................................................................72
Initialization callbacks............................................................................72
Destruction callbacks..............................................................................73
Default initialization and destroy methods................................................73
Combining lifecycle mechanisms............................................................75
Startup and shutdown callbacks...............................................................75
Shutting down the Spring IoC container gracefully in non-web applications 77
ApplicationContextAware and BeanNameAware..............................................78
Other Aware interfaces...................................................................................78
4.7.Bean definition inheritance...............................................................................80
4.8.Container Extension Points...............................................................................82
Customizing beans using a BeanPostProcessor.................................................82
Example:Hello World,BeanPostProcessor-style......................................83
Example:The RequiredAnnotationBeanPostProcessor..............................84
Customizing configuration metadata with a BeanFactoryPostProcessor..............85
Example:the PropertyPlaceholderConfigurer...........................................86
Example:the PropertyOverrideConfigurer...............................................87
Customizing instantiation logic with a FactoryBean..........................................88
4.9.Annotation-based container configuration..........................................................89
@Required.....................................................................................................90
Spring Framework
3.1 Reference Documentation iv
@Autowired and @Inject................................................................................91
Fine-tuning annotation-based autowiring with qualifiers...................................94
CustomAutowireConfigurer............................................................................99
@Resource...................................................................................................100
@PostConstruct and @PreDestroy.................................................................101
4.10.Classpath scanning and managed components................................................101
@Component and further stereotype annotations............................................102
Automatically detecting classes and registering bean definitions......................102
Using filters to customize scanning................................................................103
Defining bean metadata within components....................................................104
Naming autodetected components..................................................................106
Providing a scope for autodetected components..............................................107
Providing qualifier metadata with annotations................................................107
4.11.Using JSR 330 standard annotations..............................................................108
Dependency Injection with @Inject and @Named..........................................109
@Named:a standard equivalent to the @Component annotation......................109
Limitations of the standard approach..............................................................110
4.12.Java-based container configuration................................................................111
Basic concepts:@Configuration and @Bean..................................................111
Instantiating the Spring container using AnnotationConfigApplicationContext.111
Simple construction..............................................................................112
Building the container programmatically using register(Class<?>...)........112
Enabling component scanning with scan(String...)..................................112
Support for web applications with AnnotationConfigWebApplicationContext
.............................................................................................................113
Composing Java-based configurations............................................................114
Using the @Import annotation...............................................................114
Combining Java and XML configuration................................................117
Using the @Bean annotation.........................................................................119
Declaring a bean...................................................................................119
Injecting dependencies..........................................................................120
Receiving lifecycle callbacks.................................................................120
Specifying bean scope...........................................................................121
Customizing bean naming.....................................................................123
Bean aliasing........................................................................................123
Further information about how Java-based configuration works internally........123
4.13.Registering a LoadTimeWeaver....................................................................124
4.14.Additional Capabilities of the ApplicationContext..........................................125
Internationalization using MessageSource......................................................125
Standard and CustomEvents.........................................................................128
Convenient access to low-level resources.......................................................131
Convenient ApplicationContext instantiation for web applications...................132
Deploying a Spring ApplicationContext as a J2EE RAR file............................133
4.15.The BeanFactory..........................................................................................133
BeanFactory or ApplicationContext?.............................................................134
Spring Framework
3.1 Reference Documentation v
Glue code and the evil singleton....................................................................135
5.Resources.................................................................................................................137
5.1.Introduction...................................................................................................137
5.2.The Resource interface...................................................................................137
5.3.Built-in Resource implementations..................................................................138
UrlResource.................................................................................................138
ClassPathResource.......................................................................................139
FileSystemResource.....................................................................................139
ServletContextResource................................................................................139
InputStreamResource....................................................................................139
ByteArrayResource......................................................................................140
5.4.The ResourceLoader.......................................................................................140
5.5.The ResourceLoaderAware interface...............................................................141
5.6.Resources as dependencies.............................................................................142
5.7.Application contexts and Resource paths.........................................................142
Constructing application contexts..................................................................142
Constructing ClassPathXmlApplicationContext instances - shortcuts.......143
Wildcards in application context constructor resource paths............................144
Ant-style Patterns.................................................................................144
The classpath*:prefix...........................................................................145
Other notes relating to wildcards............................................................145
FileSystemResource caveats..........................................................................146
6.Validation,Data Binding,and Type Conversion..........................................................148
6.1.Introduction...................................................................................................148
6.2.Validation using Spring's Validator interface....................................................148
6.3.Resolving codes to error messages..................................................................150
6.4.Bean manipulation and the BeanWrapper........................................................150
Setting and getting basic and nested properties...............................................151
Built-in PropertyEditor implementations........................................................152
Registering additional customPropertyEditors.......................................155
6.5.Spring 3 Type Conversion..............................................................................158
Converter SPI...............................................................................................158
ConverterFactory..........................................................................................159
GenericConverter.........................................................................................160
ConditionalGenericConverter................................................................160
ConversionService API.................................................................................161
Configuring a ConversionService..................................................................161
Using a ConversionService programatically...................................................162
6.6.Spring 3 Field Formatting...............................................................................162
Formatter SPI...............................................................................................163
Annotation-driven Formatting.......................................................................164
Format Annotation API.........................................................................165
FormatterRegistry SPI..................................................................................166
FormatterRegistrar SPI.................................................................................166
Configuring Formatting in Spring MVC.........................................................167
Spring Framework
3.1 Reference Documentation vi
6.7.Spring 3 Validation........................................................................................168
Overview of the JSR-303 Bean Validation API...............................................168
Configuring a Bean Validation Implementation..............................................169
Injecting a Validator.............................................................................169
Configuring CustomConstraints............................................................170
Additional Configuration Options..........................................................170
Configuring a DataBinder.............................................................................170
Spring MVC 3 Validation.............................................................................171
Triggering @Controller Input Validation...............................................171
Configuring a Validator for use by Spring MVC.....................................171
Configuring a JSR-303 Validator for use by Spring MVC.......................172
7.Spring Expression Language (SpEL)..........................................................................173
7.1.Introduction...................................................................................................173
7.2.Feature Overview...........................................................................................173
7.3.Expression Evaluation using Spring's Expression Interface...............................174
The EvaluationContext interface....................................................................177
Type Conversion..................................................................................177
7.4.Expression support for defining bean definitions..............................................178
XML based configuration.............................................................................178
Annotation-based configuration.....................................................................178
7.5.Language Reference.......................................................................................180
Literal expressions........................................................................................180
Properties,Arrays,Lists,Maps,Indexers........................................................180
Inline lists....................................................................................................181
Array construction........................................................................................181
Methods.......................................................................................................182
Operators.....................................................................................................182
Relational operators..............................................................................182
Logical operators..................................................................................183
Mathematical operators.........................................................................183
Assignment..................................................................................................184
Types...........................................................................................................184
Constructors.................................................................................................184
Variables......................................................................................................185
The#this and#root variables.................................................................185
Functions.....................................................................................................185
Bean references............................................................................................186
Ternary Operator (If-Then-Else)....................................................................186
The Elvis Operator.......................................................................................187
Safe Navigation operator...............................................................................187
Collection Selection......................................................................................188
Collection Projection....................................................................................188
Expression templating...................................................................................189
7.6.Classes used in the examples...........................................................................189
8.Aspect Oriented Programming with Spring.................................................................193
Spring Framework
3.1 Reference Documentation vii
8.1.Introduction...................................................................................................193
AOP concepts...............................................................................................193
Spring AOP capabilities and goals.................................................................195
AOP Proxies................................................................................................196
8.2.@AspectJ support..........................................................................................197
Enabling @AspectJ Support..........................................................................197
Declaring an aspect.......................................................................................197
Declaring a pointcut......................................................................................198
Supported Pointcut Designators.............................................................199
Combining pointcut expressions............................................................201
Sharing common pointcut definitions.....................................................201
Examples.............................................................................................202
Writing good pointcuts..........................................................................205
Declaring advice...........................................................................................206
Before advice.......................................................................................206
After returning advice...........................................................................206
After throwing advice...........................................................................207
After (finally) advice............................................................................208
Around advice......................................................................................208
Advice parameters................................................................................209
Advice ordering....................................................................................213
Introductions................................................................................................213
Aspect instantiation models...........................................................................214
Example.......................................................................................................215
8.3.Schema-based AOP support............................................................................216
Declaring an aspect.......................................................................................217
Declaring a pointcut......................................................................................217
Declaring advice...........................................................................................219
Before advice.......................................................................................219
After returning advice...........................................................................220
After throwing advice...........................................................................220
After (finally) advice............................................................................221
Around advice......................................................................................221
Advice parameters................................................................................222
Advice ordering....................................................................................224
Introductions................................................................................................224
Aspect instantiation models...........................................................................225
Advisors......................................................................................................225
Example.......................................................................................................225
8.4.Choosing which AOP declaration style to use..................................................227
Spring AOP or full AspectJ?.........................................................................227
@AspectJ or XML for Spring AOP?..............................................................228
8.5.Mixing aspect types........................................................................................229
8.6.Proxying mechanisms.....................................................................................229
Understanding AOP proxies..........................................................................230
Spring Framework
3.1 Reference Documentation viii
8.7.Programmatic creation of @AspectJ Proxies....................................................232
8.8.Using AspectJ with Spring applications...........................................................232
Using AspectJ to dependency inject domain objects with Spring......................233
Unit testing @Configurable objects.......................................................235
Working with multiple application contexts............................................236
Other Spring aspects for AspectJ...................................................................236
Configuring AspectJ aspects using Spring IoC................................................237
Load-time weaving with AspectJ in the Spring Framework.............................238
A first example.....................................................................................238
Aspects................................................................................................241
'META-INF/aop.xml'............................................................................242
Required libraries (JARS).....................................................................242
Spring configuration.............................................................................242
Environment-specific configuration.......................................................245
8.9.Further Resources..........................................................................................248
9.Spring AOP APIs......................................................................................................249
9.1.Introduction...................................................................................................249
9.2.Pointcut API in Spring....................................................................................249
Concepts......................................................................................................249
Operations on pointcuts.................................................................................250
AspectJ expression pointcuts.........................................................................250
Convenience pointcut implementations..........................................................250
Static pointcuts.....................................................................................251
Dynamic pointcuts................................................................................252
Pointcut superclasses....................................................................................252
Custompointcuts..........................................................................................253
9.3.Advice API in Spring.....................................................................................253
Advice lifecycles..........................................................................................253
Advice types in Spring..................................................................................253
Interception around advice....................................................................253
Before advice.......................................................................................254
Throws advice......................................................................................255
After Returning advice..........................................................................256
Introduction advice...............................................................................257
9.4.Advisor API in Spring....................................................................................260
9.5.Using the ProxyFactoryBean to create AOP proxies.........................................260
Basics..........................................................................................................260
JavaBean properties......................................................................................261
JDK- and CGLIB-based proxies....................................................................262
Proxying interfaces.......................................................................................263
Proxying classes...........................................................................................265
Using'global'advisors..................................................................................265
9.6.Concise proxy definitions...............................................................................266
9.7.Creating AOP proxies programmatically with the ProxyFactory........................267
9.8.Manipulating advised objects..........................................................................267
Spring Framework
3.1 Reference Documentation ix
9.9.Using the"autoproxy"facility.........................................................................269
Autoproxy bean definitions...........................................................................269
BeanNameAutoProxyCreator................................................................269
DefaultAdvisorAutoProxyCreator..........................................................270
AbstractAdvisorAutoProxyCreator........................................................271
Using metadata-driven auto-proxying............................................................271
9.10.Using TargetSources....................................................................................273
Hot swappable target sources.........................................................................274
Pooling target sources...................................................................................275
Prototype target sources................................................................................276
ThreadLocal target sources............................................................................276
9.11.Defining new Advice types...........................................................................277
9.12.Further resources..........................................................................................277
10.Testing...................................................................................................................278
10.1.Introduction to testing...................................................................................278
10.2.Unit testing..................................................................................................278
Mock objects................................................................................................278
JNDI....................................................................................................278
Servlet API..........................................................................................278
Portlet API...........................................................................................279
Unit testing support classes...........................................................................279
General utilities....................................................................................279
Spring MVC.........................................................................................279
10.3.Integration testing.........................................................................................279
Overview.....................................................................................................279
Goals of integration testing............................................................................280
Context management and caching..........................................................281
Dependency Injection of test fixtures.....................................................281
Transaction management.......................................................................282
Support classes for integration testing....................................................282
JDBC testing support....................................................................................282
Annotations..................................................................................................283
Spring TestContext Framework.....................................................................288
Key abstractions...................................................................................288
Context management and caching..........................................................289
Dependency Injection of test fixtures.....................................................291
Transaction management.......................................................................295
TestContext support classes...................................................................297
PetClinic example.........................................................................................299
10.4.Further Resources.........................................................................................301
IV.Data Access....................................................................................................................302
11.Transaction Management.........................................................................................303
11.1.Introduction to Spring Framework transaction management............................303
11.2.Advantages of the Spring Framework's transaction support model...................303
Global transactions.......................................................................................304
Spring Framework
3.1 Reference Documentation x
Local transactions.........................................................................................304
Spring Framework's consistent programming model.......................................304
11.3.Understanding the Spring Framework transaction abstraction..........................305
11.4.Synchronizing resources with transactions.....................................................309
High-level synchronization approach.............................................................309
Low-level synchronization approach..............................................................309
TransactionAwareDataSourceProxy...............................................................310
11.5.Declarative transaction management..............................................................310
Understanding the Spring Framework's declarative transaction implementation 312
Example of declarative transaction implementation.........................................312
Rolling back a declarative transaction............................................................316
Configuring different transactional semantics for different beans.....................317
<tx:advice/> settings.....................................................................................319
Using @Transactional...................................................................................320
@Transactional settings........................................................................324
Multiple Transaction Managers with @Transactional..............................325
Customshortcut annotations..................................................................326
Transaction propagation................................................................................327
Required..............................................................................................327
RequiresNew........................................................................................327
Nested.................................................................................................327
Advising transactional operations..................................................................328
Using @Transactional with AspectJ...............................................................330
11.6.Programmatic transaction management..........................................................331
Using the TransactionTemplate.....................................................................332
Specifying transaction settings...............................................................333
Using the PlatformTransactionManager.........................................................334
11.7.Choosing between programmatic and declarative transaction management.......334
11.8.Application server-specific integration...........................................................334
IBMWebSphere...........................................................................................335
BEA WebLogic Server.................................................................................335
Oracle OC4J.................................................................................................335
11.9.Solutions to common problems.....................................................................336
Use of the wrong transaction manager for a specific DataSource......................336
11.10.Further Resources.......................................................................................336
12.DAO support..........................................................................................................337
12.1.Introduction.................................................................................................337
12.2.Consistent exception hierarchy......................................................................337
12.3.Annotations used for configuring DAO or Repository classes..........................338
13.Data access with JDBC............................................................................................340
13.1.Introduction to Spring Framework JDBC.......................................................340
Choosing an approach for JDBC database access............................................340
Package hierarchy.........................................................................................341
13.2.Using the JDBC core classes to control basic JDBC processing and error handling
.............................................................................................................................342
Spring Framework
3.1 Reference Documentation xi
JdbcTemplate...............................................................................................342
Examples of JdbcTemplate class usage..................................................343
JdbcTemplate best practices..................................................................345
NamedParameterJdbcTemplate......................................................................346
SimpleJdbcTemplate.....................................................................................348
SQLExceptionTranslator...............................................................................350
Executing statements....................................................................................351
Running queries...........................................................................................352
Updating the database...................................................................................353
Retrieving auto-generated keys......................................................................353
13.3.Controlling database connections..................................................................354
DataSource..................................................................................................354
DataSourceUtils...........................................................................................355
SmartDataSource..........................................................................................355
AbstractDataSource......................................................................................356
SingleConnectionDataSource........................................................................356
DriverManagerDataSource............................................................................356
TransactionAwareDataSourceProxy...............................................................356
DataSourceTransactionManager....................................................................357
NativeJdbcExtractor.....................................................................................357
13.4.JDBC batch operations.................................................................................358
Basic batch operations with the JdbcTemplate................................................358
Batch operations with a List of objects...........................................................359
Batch operations with multiple batches..........................................................360
13.5.Simplifying JDBC operations with the SimpleJdbc classes..............................361
Inserting data using SimpleJdbcInsert............................................................361
Retrieving auto-generated keys using SimpleJdbcInsert...................................362
Specifying columns for a SimpleJdbcInsert....................................................362
Using SqlParameterSource to provide parameter values..................................363
Calling a stored procedure with SimpleJdbcCall.............................................364
Explicitly declaring parameters to use for a SimpleJdbcCall............................366
How to define SqlParameters.........................................................................367
Calling a stored function using SimpleJdbcCall..............................................367
Returning ResultSet/REF Cursor froma SimpleJdbcCall.................................368
13.6.Modeling JDBC operations as Java objects....................................................369
SqlQuery......................................................................................................370
MappingSqlQuery........................................................................................370
SqlUpdate....................................................................................................371
StoredProcedure...........................................................................................372
13.7.Common problems with parameter and data value handling............................375
Providing SQL type information for parameters..............................................375
Handling BLOB and CLOB objects...............................................................375
Passing in lists of values for IN clause...........................................................377
Handling complex types for stored procedure calls.........................................377
13.8.Embedded database support..........................................................................379
Spring Framework
3.1 Reference Documentation xii
Why use an embedded database?...................................................................379
Creating an embedded database instance using Spring XML...........................379
Creating an embedded database instance programmatically.............................379
Extending the embedded database support......................................................379
Using HSQL................................................................................................380
Using H2.....................................................................................................380
Using Derby.................................................................................................380
Testing data access logic with an embedded database......................................380
13.9.Initializing a DataSource...............................................................................381
Initializing a database instance using Spring XML..........................................381
Initialization of Other Components that Depend on the Database.............382
14.Object Relational Mapping (ORM) Data Access.......................................................384
14.1.Introduction to ORMwith Spring..................................................................384
14.2.General ORMintegration considerations........................................................385
Resource and transaction management...........................................................385
Exception translation....................................................................................386
14.3.Hibernate.....................................................................................................387
SessionFactory setup in a Spring container.....................................................387
Implementing DAOs based on plain Hibernate 3 API......................................388
Declarative transaction demarcation...............................................................389
Programmatic transaction demarcation...........................................................391
Transaction management strategies................................................................392
Comparing container-managed and locally defined resources..........................394
Spurious application server warnings with Hibernate......................................395
14.4.JDO.............................................................................................................396
PersistenceManagerFactory setup..................................................................396
Implementing DAOs based on the plain JDO API...........................................397
Transaction management...............................................................................399
JdoDialect....................................................................................................400
14.5.JPA.............................................................................................................401
Three options for JPA setup in a Spring environment......................................401
LocalEntityManagerFactoryBean...........................................................401
Obtaining an EntityManagerFactory fromJNDI......................................402
LocalContainerEntityManagerFactoryBean............................................402
Dealing with multiple persistence units..................................................405
Implementing DAOs based on plain JPA........................................................405
Transaction Management..............................................................................408
JpaDialect....................................................................................................409
14.6.iBATIS SQL Maps.......................................................................................409
Setting up the SqlMapClient..........................................................................409
Using SqlMapClientTemplate and SqlMapClientDaoSupport..........................411
Implementing DAOs based on plain iBATIS API...........................................412
15.Marshalling XML using O/X Mappers.....................................................................413
15.1.Introduction.................................................................................................413
15.2.Marshaller and Unmarshaller........................................................................413
Spring Framework
3.1 Reference Documentation xiii
Marshaller....................................................................................................413
Unmarshaller................................................................................................414
XmlMappingException.................................................................................415
15.3.Using Marshaller and Unmarshaller...............................................................415
15.4.XML Schema-based Configuration................................................................417
15.5.JAXB..........................................................................................................418
Jaxb2Marshaller...........................................................................................418
XML Schema-based Configuration........................................................418
15.6.Castor..........................................................................................................419
CastorMarshaller..........................................................................................419
Mapping......................................................................................................419
15.7.XMLBeans..................................................................................................420
XmlBeansMarshaller....................................................................................420
XML Schema-based Configuration........................................................420
15.8.JiBX............................................................................................................421
JibxMarshaller..............................................................................................421
XML Schema-based Configuration........................................................421
15.9.XStream......................................................................................................422
XStreamMarshaller.......................................................................................422
V.The Web..........................................................................................................................423
16.Web MVC framework.............................................................................................424
16.1.Introduction to Spring Web MVC framework.................................................424
Features of Spring Web MVC.......................................................................425
Pluggability of other MVC implementations...................................................426
16.2.The DispatcherServlet..................................................................................426
16.3.Implementing Controllers.............................................................................431
Defining a controller with @Controller..........................................................431
Mapping Requests With @RequestMapping...................................................432
URI Template Patterns..........................................................................434
Path Patterns........................................................................................435
Consumable Media Types.....................................................................435
Producible Media Types........................................................................436
Request Parameters and Header Values..................................................436
Defining @RequestMapping handler methods................................................437
Supported method argument types.........................................................437
Supported method return types..............................................................439
Binding request parameters to method parameters with @RequestParam..440
Mapping the request body with the @RequestBody annotation................440
Mapping the response body with the @ResponseBody annotation...........442
Using HttpEntity<?>.............................................................................442
Command and FormObjects.................................................................443
Specifying attributes to store in a session with @SessionAttributes..........444
Mapping cookie values with the @CookieValue annotation....................444
Mapping request header attributes with the @RequestHeader annotation..445
Method Parameters And Type Conversion.............................................445
Spring Framework
3.1 Reference Documentation xiv
Customizing WebDataBinder initialization.............................................446
16.4.Handler mappings........................................................................................447
Intercepting requests with a HandlerInterceptor..............................................448
16.5.Resolving views...........................................................................................449
Resolving views with the ViewResolver interface...........................................450
Chaining ViewResolvers...............................................................................451
Redirecting to views.....................................................................................452
RedirectView.......................................................................................453
The redirect:prefix...............................................................................453
The forward:prefix...............................................................................454
ContentNegotiatingViewResolver..................................................................454
16.6.Using locales...............................................................................................456
AcceptHeaderLocaleResolver........................................................................457
CookieLocaleResolver..................................................................................457
SessionLocaleResolver.................................................................................458
LocaleChangeInterceptor..............................................................................458
16.7.Using themes...............................................................................................458
Overview of themes......................................................................................458
Defining themes...........................................................................................458
Theme resolvers...........................................................................................459
16.8.Spring's multipart (fileupload) support...........................................................460
Introduction.................................................................................................460
Using the MultipartResolver..........................................................................460
Handling a file upload in a form....................................................................461
16.9.Handling exceptions.....................................................................................462
HandlerExceptionResolver............................................................................462
@ExceptionHandler......................................................................................462
16.10.Convention over configuration support........................................................463
The Controller ControllerClassNameHandlerMapping....................................463
The Model ModelMap (ModelAndView).......................................................464
The View - RequestToViewNameTranslator..................................................466
16.11.ETag support..............................................................................................467
16.12.Configuring Spring MVC............................................................................468
mvc:annotation-driven..................................................................................468
mvc:interceptors...........................................................................................469
mvc:view-controller......................................................................................470
mvc:resources..............................................................................................470
mvc:default-servlet-handler...........................................................................472
16.13.More Spring Web MVC Resources..............................................................472
17.View technologies...................................................................................................474
17.1.Introduction.................................................................................................474
17.2.JSP &JSTL.................................................................................................474
View resolvers.............................................................................................474
'Plain-old'JSPs versus JSTL..........................................................................475
Additional tags facilitating development........................................................475
Spring Framework
3.1 Reference Documentation xv
Using Spring's formtag library......................................................................475
Configuration.......................................................................................475
The formtag........................................................................................476
The input tag........................................................................................477
The checkbox tag..................................................................................477
The checkboxes tag..............................................................................479
The radiobutton tag...............................................................................479
The radiobuttons tag.............................................................................480
The password tag..................................................................................480
The select tag.......................................................................................480
The option tag......................................................................................481
The options tag.....................................................................................481
The textarea tag....................................................................................482
The hidden tag......................................................................................482
The errors tag.......................................................................................483
HTTP Method Conversion....................................................................485
17.3.Tiles............................................................................................................485
Dependencies...............................................................................................486
How to integrate Tiles...................................................................................486
UrlBasedViewResolver.........................................................................486
ResourceBundleViewResolver..............................................................487
SimpleSpringPreparerFactory and SpringBeanPreparerFactory................487
17.4.Velocity &FreeMarker.................................................................................488
Dependencies...............................................................................................488
Context configuration...................................................................................488
Creating templates........................................................................................489
Advanced configuration................................................................................489
velocity.properties................................................................................489
FreeMarker..........................................................................................490
Bind support and formhandling.....................................................................490
The bind macros...................................................................................490
Simple binding.....................................................................................491
Forminput generation macros...............................................................492
HTML escaping and XHTML compliance.............................................496
17.5.XSLT..........................................................................................................497
My First Words............................................................................................497
Bean definitions...................................................................................497
Standard MVC controller code..............................................................497
Convert the model data to XML............................................................498
Defining the view properties..................................................................498
Document transformation......................................................................499
Summary.....................................................................................................499
17.6.Document views (PDF/Excel).......................................................................500
Introduction.................................................................................................500
Configuration and setup................................................................................500
Spring Framework
3.1 Reference Documentation xvi
Document view definitions....................................................................500
Controller code.....................................................................................500
Subclassing for Excel views..................................................................501
Subclassing for PDF views....................................................................502
17.7.JasperReports...............................................................................................503
Dependencies...............................................................................................503
Configuration...............................................................................................503
Configuring the ViewResolver..............................................................503
Configuring the Views..........................................................................504
About Report Files...............................................................................504
Using JasperReportsMultiFormatView...................................................504
Populating the ModelAndView......................................................................505
Working with Sub-Reports............................................................................506
Configuring Sub-Report Files................................................................506
Configuring Sub-Report Data Sources...................................................507
Configuring Exporter Parameters...................................................................507
17.8.Feed Views..................................................................................................508
17.9.XML Marshalling View................................................................................509
17.10.JSON Mapping View..................................................................................509
18.Integrating with other web frameworks.....................................................................510
18.1.Introduction.................................................................................................510
18.2.Common configuration.................................................................................511
18.3.JavaServer Faces 1.1 and 1.2.........................................................................512
DelegatingVariableResolver (JSF 1.1/1.2)......................................................512
SpringBeanVariableResolver (JSF 1.1/1.2).....................................................513
SpringBeanFacesELResolver (JSF 1.2+)........................................................513
FacesContextUtils........................................................................................514
18.4.Apache Struts 1.x and 2.x.............................................................................514
ContextLoaderPlugin....................................................................................515
DelegatingRequestProcessor.................................................................516
DelegatingActionProxy.........................................................................516
ActionSupport Classes..................................................................................517
18.5.WebWork 2.x...............................................................................................517
18.6.Tapestry 3.x and 4.x.....................................................................................518
Injecting Spring-managed beans....................................................................519
Dependency Injecting Spring Beans into Tapestry pages.........................520
Component definition files....................................................................521
Adding abstract accessors......................................................................522
Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style
.............................................................................................................524
18.7.Further Resources.........................................................................................525
19.Portlet MVC Framework.........................................................................................526
19.1.Introduction.................................................................................................526
Controllers - The C in MVC..........................................................................527
Views - The V in MVC.................................................................................527
Spring Framework
3.1 Reference Documentation xvii
Web-scoped beans........................................................................................528
19.2.The DispatcherPortlet...................................................................................528
19.3.The ViewRendererServlet.............................................................................530
19.4.Controllers...................................................................................................531
AbstractController and PortletContentGenerator.............................................531
Other simple controllers................................................................................533
Command Controllers...................................................................................533
PortletWrappingController............................................................................534
19.5.Handler mappings........................................................................................534
PortletModeHandlerMapping........................................................................535
ParameterHandlerMapping............................................................................536
PortletModeParameterHandlerMapping.........................................................536
Adding HandlerInterceptors..........................................................................537
HandlerInterceptorAdapter............................................................................537
ParameterMappingInterceptor.......................................................................537
19.6.Views and resolving them.............................................................................538
19.7.Multipart (file upload) support......................................................................538
Using the PortletMultipartResolver................................................................539
Handling a file upload in a form....................................................................539
19.8.Handling exceptions.....................................................................................542
19.9.Annotation-based controller configuration.....................................................543
Setting up the dispatcher for annotation support..............................................543
Defining a controller with @Controller..........................................................543
Mapping requests with @RequestMapping.....................................................544
Supported handler method arguments............................................................545
Binding request parameters to method parameters with @RequestParam..........547
Providing a link to data fromthe model with @ModelAttribute.......................548
Specifying attributes to store in a Session with @SessionAttributes.................548
Customizing WebDataBinder initialization.....................................................549
Customizing data binding with @InitBinder...........................................549
Configuring a customWebBindingInitializer..........................................549
19.10.Portlet application deployment....................................................................550
VI.Integration......................................................................................................................551
20.Remoting and web services using Spring..................................................................552
20.1.Introduction.................................................................................................552
20.2.Exposing services using RMI........................................................................553
Exporting the service using the RmiServiceExporter.......................................553
Linking in the service at the client.................................................................554
20.3.Using Hessian or Burlap to remotely call services via HTTP...........................555
Wiring up the DispatcherServlet for Hessian and co........................................555
Exposing your beans by using the HessianServiceExporter..............................555
Linking in the service on the client................................................................556
Using Burlap................................................................................................556
Applying HTTP basic authentication to a service exposed through Hessian or
Burlap..........................................................................................................556
Spring Framework
3.1 Reference Documentation xviii
20.4.Exposing services using HTTP invokers........................................................557
Exposing the service object...........................................................................557
Linking in the service at the client.................................................................558
20.5.Web services................................................................................................559
Exposing servlet-based web services using JAX-RPC.....................................560
Accessing web services using JAX-RPC........................................................560
Registering JAX-RPC Bean Mappings...........................................................562
Registering your own JAX-RPC Handler.......................................................563
Exposing servlet-based web services using JAX-WS......................................563
Exporting standalone web services using JAX-WS.........................................564
Exporting web services using the JAX-WS RI's Spring support.......................565
Accessing web services using JAX-WS..........................................................565
20.6.JMS.............................................................................................................566
Server-side configuration..............................................................................567
Client-side configuration...............................................................................568
20.7.Auto-detection is not implemented for remote interfaces.................................569
20.8.Considerations when choosing a technology...................................................569
20.9.Accessing RESTful services on the Client......................................................570
RestTemplate...............................................................................................570
Dealing with request and response headers.............................................572
HTTP Message Conversion...........................................................................573
StringHttpMessageConverter.................................................................573
FormHttpMessageConverter..................................................................573
ByteArrayMessageConverter.................................................................574
MarshallingHttpMessageConverter........................................................574
MappingJacksonHttpMessageConverter.................................................574
SourceHttpMessageConverter...............................................................574
BufferedImageHttpMessageConverter...................................................574
21.Enterprise JavaBeans (EJB) integration....................................................................575
21.1.Introduction.................................................................................................575
21.2.Accessing EJBs............................................................................................575
Concepts......................................................................................................575
Accessing local SLSBs.................................................................................576
Accessing remote SLSBs..............................................................................577
Accessing EJB 2.x SLSBs versus EJB 3 SLSBs..............................................578
21.3.Using Spring's EJB implementation support classes........................................578
EJB 2.x base classes.....................................................................................578
EJB 3 injection interceptor............................................................................580
22.JMS (Java Message Service)....................................................................................582
22.1.Introduction.................................................................................................582
22.2.Using Spring JMS........................................................................................582
JmsTemplate................................................................................................582
Connections.................................................................................................583
Caching Messaging Resources...............................................................584
SingleConnectionFactory......................................................................584
Spring Framework
3.1 Reference Documentation xix
CachingConnectionFactory...................................................................584
Destination Management...............................................................................584
Message Listener Containers.........................................................................585
SimpleMessageListenerContainer..........................................................586
DefaultMessageListenerContainer.........................................................586
Transaction management...............................................................................586
22.3.Sending a Message.......................................................................................587
Using Message Converters............................................................................588
SessionCallback and ProducerCallback..........................................................589
22.4.Receiving a message.....................................................................................589
Synchronous Reception.................................................................................589
Asynchronous Reception - Message-Driven POJOs........................................589
The SessionAwareMessageListener interface.................................................590
The MessageListenerAdapter........................................................................590
Processing messages within transactions........................................................592
22.5.Support for JCA Message Endpoints..............................................................593
22.6.JMS Namespace Support..............................................................................595
23.JMX.......................................................................................................................600
23.1.Introduction.................................................................................................600
23.2.Exporting your beans to JMX........................................................................600
Creating an MBeanServer.............................................................................601
Reusing an existing MBeanServer.................................................................602
Lazy-initialized MBeans...............................................................................603
Automatic registration of MBeans.................................................................603
Controlling the registration behavior..............................................................603
23.3.Controlling the management interface of your beans.......................................605
The MBeanInfoAssembler Interface..............................................................605
Using Source-Level Metadata (JDK 5.0 annotations)......................................605
Source-Level Metadata Types.......................................................................607
The AutodetectCapableMBeanInfoAssembler interface...................................609
Defining management interfaces using Java interfaces....................................610
Using MethodNameBasedMBeanInfoAssembler............................................611
23.4.Controlling the ObjectNames for your beans..................................................611
Reading ObjectNames fromProperties...........................................................612
Using the MetadataNamingStrategy...............................................................613
The <context:mbean-export/> element...........................................................613
23.5.JSR-160 Connectors.....................................................................................614
Server-side Connectors.................................................................................614
Client-side Connectors..................................................................................615
JMX over Burlap/Hessian/SOAP...................................................................615
23.6.Accessing MBeans via Proxies......................................................................616
23.7.Notifications................................................................................................616
Registering Listeners for Notifications...........................................................616
Publishing Notifications................................................................................620
23.8.Further Resources.........................................................................................621
Spring Framework
3.1 Reference Documentation xx
24.JCA CCI.................................................................................................................622
24.1.Introduction.................................................................................................622
24.2.Configuring CCI..........................................................................................622
Connector configuration................................................................................622
ConnectionFactory configuration in Spring....................................................623