Spring Java Application Framework - Reference Documentation 3.0

antlertextureΛογισμικό & κατασκευή λογ/κού

14 Ιουλ 2012 (πριν από 5 χρόνια και 1 μήνα)

7.502 εμφανίσεις

Reference Documentation
3.0
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
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....................................................................................4
Web.................................................................................................................4
AOP and Instrumentation..................................................................................5
Test.................................................................................................................5
1.3.Usage scenarios.................................................................................................5
Dependency Management and Naming Conventions...........................................9
Spring Dependencies and Depending on Spring........................................11
Maven Dependency Management............................................................12
Ivy Dependency Management.................................................................13
Logging.........................................................................................................14
Not Using Commons Logging.................................................................14
Using SLF4J..........................................................................................15
Using Log4J...........................................................................................16
II.What's New in Spring 3.0...................................................................................................18
2.New Features and Enhancements in Spring 3.0.............................................................19
2.1.Java 5..............................................................................................................19
2.2.Improved documentation..................................................................................19
2.3.New articles and tutorials..................................................................................19
2.4.New module organization and build system.......................................................20
2.5.Overview of new features.................................................................................21
Core APIs updated for Java 5..........................................................................22
Spring Expression Language...........................................................................22
The Inversion of Control (IoC) container..........................................................23
Java based bean metadata........................................................................23
Defining bean metadata within components..............................................24
General purpose type conversion systemand field formatting system.................24
The Data Tier.................................................................................................24
The Web Tier.................................................................................................25
Comprehensive REST support.................................................................25
@MVC additions...................................................................................25
Declarative model validation...........................................................................25
Early support for Java EE 6.............................................................................25
Support for embedded databases......................................................................25
III.Core Technologies............................................................................................................26
3.The IoC container.......................................................................................................27
Spring Framework
3.0 Reference Documentation ii
3.1.Introduction to the Spring IoC container and beans.............................................27
3.2.Container overview..........................................................................................27
Configuration metadata...................................................................................28
Instantiating a container..................................................................................30
Composing XML-based configuration metadata.......................................31
Using the container.........................................................................................32
3.3.Bean overview.................................................................................................32
Naming beans.................................................................................................34
Aliasing a bean outside the bean definition...............................................34
Instantiating beans..........................................................................................35
Instantiation with a constructor................................................................36
Instantiation with a static factory method.................................................36
Instantiation using an instance factory method..........................................37
3.4.Dependencies...................................................................................................38
Dependency injection......................................................................................38
Constructor-based dependency injection...................................................38
Setter-based dependency injection...........................................................41
Dependency resolution process................................................................42
Examples of dependency injection...........................................................43
Dependencies and configuration in detail.........................................................45
Straight values (primitives,Strings,and so on).........................................45
References to other beans (collaborators).................................................47
Inner beans.............................................................................................48
Collections.............................................................................................48
Null and empty string values...................................................................51
XML shortcut with the p-namespace........................................................51
Compound property names......................................................................52
Using depends-on...........................................................................................52
Lazy-initialized beans.....................................................................................53
Autowiring collaborators.................................................................................54
Limitations and disadvantages of autowiring............................................55
Excluding a bean fromautowiring...........................................................56
Method injection............................................................................................56
Lookup method injection.........................................................................57
Arbitrary method replacement.................................................................59
3.5.Bean scopes.....................................................................................................60
The singleton scope........................................................................................61
The prototype scope........................................................................................62
Singleton beans with prototype-bean dependencies...........................................63
Request,session,and global session scopes......................................................64
Initial web configuration.........................................................................64
Request scope.........................................................................................65
Session scope.........................................................................................65
Global session scope...............................................................................65
Scoped beans as dependencies.................................................................66
Spring Framework
3.0 Reference Documentation iii
Customscopes...............................................................................................68
Creating a customscope..........................................................................68
Using a customscope..............................................................................69
3.6.Customizing the nature of a bean.......................................................................70
Lifecycle callbacks.........................................................................................70
Initialization callbacks............................................................................71
Destruction callbacks..............................................................................71
Default initialization and destroy methods................................................72
Combining lifecycle mechanisms............................................................73
Startup and shutdown callbacks...............................................................74
Shutting down the Spring IoC container gracefully in non-web applications 76
ApplicationContextAware and BeanNameAware..............................................76
Other Aware interfaces...................................................................................77
3.7.Bean definition inheritance...............................................................................79
3.8.Container extension points................................................................................80
Customizing beans using the BeanPostProcessor Interface................................81
Example:Hello World,BeanPostProcessor-style......................................82
Example:The RequiredAnnotationBeanPostProcessor..............................83
Customizing configuration metadata with BeanFactoryPostProcessor interface...83
Example:the PropertyPlaceholderConfigurer...........................................85
Example:the PropertyOverrideConfigurer...............................................86
Customizing instantiation logic with the FactoryBean Interface.........................87
3.9.Annotation-based container configuration..........................................................88
@Required.....................................................................................................89
@Autowired and @Inject................................................................................89
Fine-tuning annotation-based autowiring with qualifiers...................................92
CustomAutowireConfigurer............................................................................97
@Resource.....................................................................................................98
@PostConstruct and @PreDestroy...................................................................99
3.10.Classpath scanning and managed components................................................100
@Component and further stereotype annotations............................................100
Automatically detecting classes and registering bean definitions......................101
Using filters to customize scanning................................................................102
Defining bean metadata within components....................................................103
Naming autodetected components..................................................................104
Providing a scope for autodetected components..............................................105
Providing qualifier metadata with annotations................................................106
3.11.Java-based container configuration................................................................107
Basic concepts:@Configuration and @Bean..................................................107
Instantiating the Spring container using AnnotationConfigApplicationContext.107
Simple construction..............................................................................108
Building the container programmatically using register(Class<?>...)........108
Enabling component scanning with scan(String...)..................................108
Support for web applications with AnnotationConfigWebApplicationContext
.............................................................................................................109
Spring Framework
3.0 Reference Documentation iv
Composing Java-based configurations............................................................110
Using the @Import annotation...............................................................110
Combining Java and XML configuration................................................112
Using the @Bean annotation.........................................................................115
Declaring a bean...................................................................................115
Injecting dependencies..........................................................................115
Receiving lifecycle callbacks.................................................................116
Specifying bean scope...........................................................................117
Customizing bean naming.....................................................................118
Bean aliasing........................................................................................119
Further information about how Java-based configuration works internally........119
3.12.Registering a LoadTimeWeaver....................................................................120
3.13.Additional Capabilities of the ApplicationContext..........................................121
Internationalization using MessageSource......................................................121
Standard and CustomEvents.........................................................................124
Convenient access to low-level resources.......................................................127
Convenient ApplicationContext instantiation for web applications...................128
Deploying a Spring ApplicationContext as a J2EE RAR file............................128
3.14.The BeanFactory..........................................................................................129
BeanFactory or ApplicationContext?.............................................................130
Glue code and the evil singleton....................................................................131
4.Resources.................................................................................................................132
4.1.Introduction...................................................................................................132
4.2.The Resource interface...................................................................................132
4.3.Built-in Resource implementations..................................................................133
UrlResource.................................................................................................133
ClassPathResource.......................................................................................134
FileSystemResource.....................................................................................134
ServletContextResource................................................................................134
InputStreamResource....................................................................................134
ByteArrayResource......................................................................................135
4.4.The ResourceLoader.......................................................................................135
4.5.The ResourceLoaderAware interface...............................................................136
4.6.Resources as dependencies.............................................................................137
4.7.Application contexts and Resource paths.........................................................137
Constructing application contexts..................................................................137
Constructing ClassPathXmlApplicationContext instances - shortcuts.......138
Wildcards in application context constructor resource paths............................139
Ant-style Patterns.................................................................................139
The classpath*:prefix...........................................................................140
Other notes relating to wildcards............................................................140
FileSystemResource caveats..........................................................................141
5.Validation,Data Binding,and Type Conversion..........................................................143
5.1.Introduction...................................................................................................143
5.2.Validation using Spring's Validator interface....................................................143
Spring Framework
3.0 Reference Documentation v
5.3.Resolving codes to error messages..................................................................145
5.4.Bean manipulation and the BeanWrapper........................................................145
Setting and getting basic and nested properties...............................................146
Built-in PropertyEditor implementations........................................................147
Registering additional customPropertyEditors.......................................150
5.5.Spring 3 Type Conversion..............................................................................153
Converter SPI...............................................................................................153
ConverterFactory..........................................................................................154
GenericConverter.........................................................................................155
ConditionalGenericConverter................................................................155
ConversionService API.................................................................................156
Configuring a ConversionService..................................................................156
Using a ConversionService programatically...................................................157
5.6.Spring 3 Field Formatting...............................................................................157
Formatter SPI...............................................................................................158
Annotation-driven Formatting.......................................................................159
Format Annotation API.........................................................................160
FormatterRegistry SPI..................................................................................161
Configuring Formatting in Spring MVC.........................................................161
5.7.Spring 3 Validation........................................................................................162
Overview of the JSR-303 Bean Validation API...............................................162
Configuring a Bean Validation Implementation..............................................163
Injecting a Validator.............................................................................163
Configuring CustomConstraints............................................................164
Additional Configuration Options..........................................................165
Configuring a DataBinder.............................................................................165
Spring MVC 3 Validation.............................................................................165
Triggering @Controller Input Validation...............................................165
Configuring a Validator for use by Spring MVC.....................................166
Configuring a JSR-303 Validator for use by Spring MVC.......................166
6.Spring Expression Language (SpEL)..........................................................................168
6.1.Introduction...................................................................................................168
6.2.Feature Overview...........................................................................................168
6.3.Expression Evaluation using Spring's Expression Interface...............................169
The EvaluationContext interface....................................................................172
Type Conversion..................................................................................172
6.4.Expression support for defining bean definitions..............................................173
XML based configuration.............................................................................173
Annotation-based configuration.....................................................................173
6.5.Language Reference.......................................................................................175
Literal expressions........................................................................................175
Properties,Arrays,Lists,Maps,Indexers........................................................175
Inline lists....................................................................................................176
Array construction........................................................................................176
Methods.......................................................................................................177
Spring Framework
3.0 Reference Documentation vi
Operators.....................................................................................................177
Relational operators..............................................................................177
Logical operators..................................................................................178
Mathematical operators.........................................................................178
Assignment..................................................................................................179
Types...........................................................................................................179
Constructors.................................................................................................179
Variables......................................................................................................180
The#this and#root variables.................................................................180
Functions.....................................................................................................180
Bean references............................................................................................181
Ternary Operator (If-Then-Else)....................................................................181
The Elvis Operator.......................................................................................182
Safe Navigation operator...............................................................................182
Collection Selection......................................................................................183
Collection Projection....................................................................................183
Expression templating...................................................................................183
6.6.Classes used in the examples...........................................................................184
7.Aspect Oriented Programming with Spring.................................................................187
7.1.Introduction...................................................................................................187
AOP concepts...............................................................................................187
Spring AOP capabilities and goals.................................................................189
AOP Proxies................................................................................................190
7.2.@AspectJ support..........................................................................................191
Enabling @AspectJ Support..........................................................................191
Declaring an aspect.......................................................................................191
Declaring a pointcut......................................................................................192
Supported Pointcut Designators.............................................................193
Combining pointcut expressions............................................................195
Sharing common pointcut definitions.....................................................195
Examples.............................................................................................196
Writing good pointcuts..........................................................................199
Declaring advice...........................................................................................200
Before advice.......................................................................................200
After returning advice...........................................................................200
After throwing advice...........................................................................201
After (finally) advice............................................................................202
Around advice......................................................................................202
Advice parameters................................................................................203
Advice ordering....................................................................................207
Introductions................................................................................................207
Aspect instantiation models...........................................................................208
Example.......................................................................................................209
7.3.Schema-based AOP support............................................................................210
Declaring an aspect.......................................................................................211
Spring Framework
3.0 Reference Documentation vii
Declaring a pointcut......................................................................................211
Declaring advice...........................................................................................213
Before advice.......................................................................................213
After returning advice...........................................................................214
After throwing advice...........................................................................214
After (finally) advice............................................................................215
Around advice......................................................................................215
Advice parameters................................................................................216
Advice ordering....................................................................................218
Introductions................................................................................................218
Aspect instantiation models...........................................................................219
Advisors......................................................................................................219
Example.......................................................................................................219
7.4.Choosing which AOP declaration style to use..................................................221
Spring AOP or full AspectJ?.........................................................................221
@AspectJ or XML for Spring AOP?..............................................................222
7.5.Mixing aspect types........................................................................................223
7.6.Proxying mechanisms.....................................................................................223
Understanding AOP proxies..........................................................................224
7.7.Programmatic creation of @AspectJ Proxies....................................................227
7.8.Using AspectJ with Spring applications...........................................................227
Using AspectJ to dependency inject domain objects with Spring......................227
Unit testing @Configurable objects.......................................................230
Working with multiple application contexts............................................230
Other Spring aspects for AspectJ...................................................................231
Configuring AspectJ aspects using Spring IoC................................................231
Load-time weaving with AspectJ in the Spring Framework.............................232
A first example.....................................................................................233
Aspects................................................................................................236
'META-INF/aop.xml'............................................................................236
Required libraries (JARS).....................................................................236
Spring configuration.............................................................................237
Environment-specific configuration.......................................................239
7.9.Further Resources..........................................................................................242
8.Spring AOP APIs......................................................................................................243
8.1.Introduction...................................................................................................243
8.2.Pointcut API in Spring....................................................................................243
Concepts......................................................................................................243
Operations on pointcuts.................................................................................244
AspectJ expression pointcuts.........................................................................244
Convenience pointcut implementations..........................................................244
Static pointcuts.....................................................................................245
Dynamic pointcuts................................................................................246
Pointcut superclasses....................................................................................246
Custompointcuts..........................................................................................247
Spring Framework
3.0 Reference Documentation viii
8.3.Advice API in Spring.....................................................................................247
Advice lifecycles..........................................................................................247
Advice types in Spring..................................................................................247
Interception around advice....................................................................247
Before advice.......................................................................................248
Throws advice......................................................................................249
After Returning advice..........................................................................250
Introduction advice...............................................................................251
8.4.Advisor API in Spring....................................................................................254
8.5.Using the ProxyFactoryBean to create AOP proxies.........................................254
Basics..........................................................................................................254
JavaBean properties......................................................................................255
JDK- and CGLIB-based proxies....................................................................256
Proxying interfaces.......................................................................................257
Proxying classes...........................................................................................259
Using'global'advisors..................................................................................259
8.6.Concise proxy definitions...............................................................................260
8.7.Creating AOP proxies programmatically with the ProxyFactory........................261
8.8.Manipulating advised objects..........................................................................261
8.9.Using the"autoproxy"facility.........................................................................263
Autoproxy bean definitions...........................................................................263
BeanNameAutoProxyCreator................................................................263
DefaultAdvisorAutoProxyCreator..........................................................264
AbstractAdvisorAutoProxyCreator........................................................265
Using metadata-driven auto-proxying............................................................265
8.10.Using TargetSources....................................................................................267
Hot swappable target sources.........................................................................268
Pooling target sources...................................................................................269
Prototype target sources................................................................................270
ThreadLocal target sources............................................................................270
8.11.Defining new Advice types...........................................................................271
8.12.Further resources..........................................................................................271
9.Testing.....................................................................................................................272
9.1.Introduction to testing.....................................................................................272
9.2.Unit testing....................................................................................................272
Mock objects................................................................................................272
JNDI....................................................................................................272
Servlet API..........................................................................................272
Portlet API...........................................................................................273
Unit testing support classes...........................................................................273
General utilities....................................................................................273
Spring MVC.........................................................................................273
9.3.Integration testing..........................................................................................273
Overview.....................................................................................................273
Goals of integration testing............................................................................274
Spring Framework
3.0 Reference Documentation ix
Context management and caching..........................................................274
Dependency Injection of test fixtures.....................................................275
Transaction management.......................................................................275
Support classes for integration testing....................................................276
JDBC testing support....................................................................................276
Annotations..................................................................................................276
Spring TestContext Framework.....................................................................282
Key abstractions...................................................................................282
Context management and caching..........................................................283
Dependency Injection of test fixtures.....................................................285
Transaction management.......................................................................288
TestContext support classes...................................................................290
PetClinic example.........................................................................................293
9.4.Further Resources..........................................................................................295
IV.Data Access....................................................................................................................296
10.Transaction Management.........................................................................................297
10.1.Introduction to Spring Framework transaction management............................297
10.2.Advantages of the Spring Framework's transaction support model...................297
Global transactions.......................................................................................298
Local transactions.........................................................................................298
Spring Framework's consistent programming model.......................................298
10.3.Understanding the Spring Framework transaction abstraction..........................299
10.4.Synchronizing resources with transactions.....................................................303
High-level synchronization approach.............................................................303
Low-level synchronization approach..............................................................303
TransactionAwareDataSourceProxy...............................................................304
10.5.Declarative transaction management..............................................................304
Understanding the Spring Framework's declarative transaction implementation 306
Example of declarative transaction implementation.........................................307
Rolling back a declarative transaction............................................................311
Configuring different transactional semantics for different beans.....................312
<tx:advice/> settings.....................................................................................314
Using @Transactional...................................................................................315
@Transactional settings........................................................................319
Multiple Transaction Managers with @Transactional..............................320
Customshortcut annotations..................................................................321
Transaction propagation................................................................................321
Required..............................................................................................322
RequiresNew........................................................................................322
Nested.................................................................................................323
Advising transactional operations..................................................................323
Using @Transactional with AspectJ...............................................................326
10.6.Programmatic transaction management..........................................................327
Using the TransactionTemplate.....................................................................327
Specifying transaction settings...............................................................328
Spring Framework
3.0 Reference Documentation x
Using the PlatformTransactionManager.........................................................329
10.7.Choosing between programmatic and declarative transaction management.......330
10.8.Application server-specific integration...........................................................330
IBMWebSphere...........................................................................................331
BEA WebLogic Server.................................................................................331
Oracle OC4J.................................................................................................331
10.9.Solutions to common problems.....................................................................331
Use of the wrong transaction manager for a specific DataSource......................331
10.10.Further Resources.......................................................................................331
11.DAO support..........................................................................................................333
11.1.Introduction.................................................................................................333
11.2.Consistent exception hierarchy......................................................................333
11.3.Annotations used for configuring DAO or Repository classes..........................334
12.Data access with JDBC............................................................................................336
12.1.Introduction to Spring Framework JDBC.......................................................336
Choosing an approach for JDBC database access............................................336
Package hierarchy.........................................................................................337
12.2.Using the JDBC core classes to control basic JDBC processing and error handling
.............................................................................................................................338
JdbcTemplate...............................................................................................338
Examples of JdbcTemplate class usage..................................................339
JdbcTemplate best practices..................................................................341
NamedParameterJdbcTemplate......................................................................342
SimpleJdbcTemplate.....................................................................................344
SQLExceptionTranslator...............................................................................346
Executing statements....................................................................................347
Running queries...........................................................................................348
Updating the database...................................................................................349
Retrieving auto-generated keys......................................................................349
12.3.Controlling database connections..................................................................350
DataSource..................................................................................................350
DataSourceUtils...........................................................................................351
SmartDataSource..........................................................................................351
AbstractDataSource......................................................................................352
SingleConnectionDataSource........................................................................352
DriverManagerDataSource............................................................................352
TransactionAwareDataSourceProxy...............................................................352
DataSourceTransactionManager....................................................................353
NativeJdbcExtractor.....................................................................................353
12.4.JDBC batch operations.................................................................................354
Batch operations with the JdbcTemplate.........................................................354
Batch operations with the SimpleJdbcTemplate..............................................355
12.5.Simplifying JDBC operations with the SimpleJdbc classes..............................356
Inserting data using SimpleJdbcInsert............................................................356
Retrieving auto-generated keys using SimpleJdbcInsert...................................357
Spring Framework
3.0 Reference Documentation xi
Specifying columns for a SimpleJdbcInsert....................................................357
Using SqlParameterSource to provide parameter values..................................358
Calling a stored procedure with SimpleJdbcCall.............................................359
Explicitly declaring parameters to use for a SimpleJdbcCall............................361
How to define SqlParameters.........................................................................362
Calling a stored function using SimpleJdbcCall..............................................362
Returning ResultSet/REF Cursor froma SimpleJdbcCall.................................363
12.6.Modeling JDBC operations as Java objects....................................................364
SqlQuery......................................................................................................365
MappingSqlQuery........................................................................................365
SqlUpdate....................................................................................................366
StoredProcedure...........................................................................................367
12.7.Common problems with parameter and data value handling............................370
Providing SQL type information for parameters..............................................370
Handling BLOB and CLOB objects...............................................................370
Passing in lists of values for IN clause...........................................................372
Handling complex types for stored procedure calls.........................................372
12.8.Embedded database support..........................................................................374
Why use an embedded database?...................................................................374
Creating an embedded database instance using Spring XML...........................374
Creating an embedded database instance programmatically.............................374
Extending the embedded database support......................................................374
Using HSQL................................................................................................375
Using H2.....................................................................................................375
Using Derby.................................................................................................375
Testing data access logic with an embedded database......................................375
12.9.Initializing a DataSource...............................................................................376
Initializing a database instance using Spring XML..........................................376
Initialization of Other Components that Depend on the Database.............377
13.Object Relational Mapping (ORM) Data Access.......................................................379
13.1.Introduction to ORMwith Spring..................................................................379
13.2.General ORMintegration considerations........................................................380
Resource and transaction management...........................................................380
Exception translation....................................................................................381
13.3.Hibernate.....................................................................................................382
SessionFactory setup in a Spring container.....................................................382
Implementing DAOs based on plain Hibernate 3 API......................................383
Declarative transaction demarcation...............................................................384
Programmatic transaction demarcation...........................................................386
Transaction management strategies................................................................387
Comparing container-managed and locally defined resources..........................389
Spurious application server warnings with Hibernate......................................390
13.4.JDO.............................................................................................................391
PersistenceManagerFactory setup..................................................................391
Implementing DAOs based on the plain JDO API...........................................392
Spring Framework
3.0 Reference Documentation xii
Transaction management...............................................................................394
JdoDialect....................................................................................................395
13.5.JPA.............................................................................................................396
Three options for JPA setup in a Spring environment......................................396
LocalEntityManagerFactoryBean...........................................................396
Obtaining an EntityManagerFactory fromJNDI......................................397
LocalContainerEntityManagerFactoryBean............................................397
Dealing with multiple persistence units..................................................400
Implementing DAOs based on plain JPA........................................................400
Transaction Management..............................................................................403
JpaDialect....................................................................................................404
13.6.iBATIS SQL Maps.......................................................................................404
Setting up the SqlMapClient..........................................................................404
Using SqlMapClientTemplate and SqlMapClientDaoSupport..........................406
Implementing DAOs based on plain iBATIS API...........................................407
14.Marshalling XML using O/X Mappers.....................................................................408
14.1.Introduction.................................................................................................408
14.2.Marshaller and Unmarshaller........................................................................408
Marshaller....................................................................................................408
Unmarshaller................................................................................................409
XmlMappingException.................................................................................410
14.3.Using Marshaller and Unmarshaller...............................................................410
14.4.XML Schema-based Configuration................................................................412
14.5.JAXB..........................................................................................................413
Jaxb2Marshaller...........................................................................................413
XML Schema-based Configuration........................................................413
14.6.Castor..........................................................................................................414
CastorMarshaller..........................................................................................414
Mapping......................................................................................................414
14.7.XMLBeans..................................................................................................415
XmlBeansMarshaller....................................................................................415
XML Schema-based Configuration........................................................415
14.8.JiBX............................................................................................................416
JibxMarshaller..............................................................................................416
XML Schema-based Configuration........................................................416
14.9.XStream......................................................................................................417
XStreamMarshaller.......................................................................................417
V.The Web..........................................................................................................................419
15.Web MVC framework.............................................................................................420
15.1.Introduction to Spring Web MVC framework.................................................420
Features of Spring Web MVC.......................................................................421
Pluggability of other MVC implementations...................................................422
15.2.The DispatcherServlet..................................................................................422
15.3.Implementing Controllers.............................................................................427
Defining a controller with @Controller..........................................................428
Spring Framework
3.0 Reference Documentation xiii
Mapping requests with @RequestMapping.....................................................428
URI Templates.....................................................................................430
Advanced @RequestMapping options....................................................432
Supported handler method arguments and return types............................433
Binding request parameters to method parameters with @RequestParam..435
Mapping the request body with the @RequestBody annotation................436
Mapping the response body with the @ResponseBody annotation...........437
Using HttpEntity<?>.............................................................................437
Providing a link to data fromthe model with @ModelAttribute...............438
Specifying attributes to store in a session with @SessionAttributes..........439
Mapping cookie values with the @CookieValue annotation....................439
Mapping request header attributes with the @RequestHeader annotation..440
Customizing WebDataBinder initialization.............................................440
15.4.Handler mappings........................................................................................441
Intercepting requests - the HandlerInterceptor interface...................................442
15.5.Resolving views...........................................................................................444
Resolving views with the ViewResolver interface...........................................444
Chaining ViewResolvers...............................................................................446
Redirecting to views.....................................................................................447
RedirectView.......................................................................................447
The redirect:prefix...............................................................................447
The forward:prefix...............................................................................448
ContentNegotiatingViewResolver..................................................................448
15.6.Using locales...............................................................................................451
AcceptHeaderLocaleResolver........................................................................451
CookieLocaleResolver..................................................................................451
SessionLocaleResolver.................................................................................452
LocaleChangeInterceptor..............................................................................452
15.7.Using themes...............................................................................................452
Overview of themes......................................................................................452
Defining themes...........................................................................................453
Theme resolvers...........................................................................................453
15.8.Spring's multipart (fileupload) support...........................................................454
Introduction.................................................................................................454
Using the MultipartResolver..........................................................................454
Handling a file upload in a form....................................................................455
15.9.Handling exceptions.....................................................................................456
HandlerExceptionResolver............................................................................456
@ExceptionHandler......................................................................................457
15.10.Convention over configuration support........................................................457
The Controller ControllerClassNameHandlerMapping....................................458
The Model ModelMap (ModelAndView).......................................................459
The View - RequestToViewNameTranslator..................................................460
15.11.ETag support..............................................................................................461
15.12.Configuring Spring MVC............................................................................462
Spring Framework
3.0 Reference Documentation xiv
mvc:annotation-driven..................................................................................462
mvc:interceptors...........................................................................................463
mvc:view-controller......................................................................................463
mvc:resources..............................................................................................464
mvc:default-servlet-handler...........................................................................465
15.13.More Spring Web MVC Resources..............................................................466
16.View technologies...................................................................................................467
16.1.Introduction.................................................................................................467
16.2.JSP &JSTL.................................................................................................467
View resolvers.............................................................................................467
'Plain-old'JSPs versus JSTL..........................................................................468
Additional tags facilitating development........................................................468
Using Spring's formtag library......................................................................468
Configuration.......................................................................................468
The formtag........................................................................................469
The input tag........................................................................................470
The checkbox tag..................................................................................470
The checkboxes tag..............................................................................472
The radiobutton tag...............................................................................472
The radiobuttons tag.............................................................................473
The password tag..................................................................................473
The select tag.......................................................................................473
The option tag......................................................................................474
The options tag.....................................................................................474
The textarea tag....................................................................................475
The hidden tag......................................................................................475
The errors tag.......................................................................................476
HTTP Method Conversion....................................................................478
16.3.Tiles............................................................................................................478
Dependencies...............................................................................................479
How to integrate Tiles...................................................................................479
UrlBasedViewResolver.........................................................................479
ResourceBundleViewResolver..............................................................480
SimpleSpringPreparerFactory and SpringBeanPreparerFactory................480
16.4.Velocity &FreeMarker.................................................................................481
Dependencies...............................................................................................481
Context configuration...................................................................................481
Creating templates........................................................................................482
Advanced configuration................................................................................482
velocity.properties................................................................................482
FreeMarker..........................................................................................483
Bind support and formhandling.....................................................................483
The bind macros...................................................................................483
Simple binding.....................................................................................484
Forminput generation macros...............................................................485
Spring Framework
3.0 Reference Documentation xv
HTML escaping and XHTML compliance.............................................489
16.5.XSLT..........................................................................................................490
My First Words............................................................................................490
Bean definitions...................................................................................490
Standard MVC controller code..............................................................490
Convert the model data to XML............................................................491
Defining the view properties..................................................................491
Document transformation......................................................................492
Summary.....................................................................................................492
16.6.Document views (PDF/Excel).......................................................................493
Introduction.................................................................................................493
Configuration and setup................................................................................493
Document view definitions....................................................................493
Controller code.....................................................................................493
Subclassing for Excel views..................................................................494
Subclassing for PDF views....................................................................495
16.7.JasperReports...............................................................................................496
Dependencies...............................................................................................496
Configuration...............................................................................................496
Configuring the ViewResolver..............................................................496
Configuring the Views..........................................................................497
About Report Files...............................................................................497
Using JasperReportsMultiFormatView...................................................497
Populating the ModelAndView......................................................................498
Working with Sub-Reports............................................................................499
Configuring Sub-Report Files................................................................499
Configuring Sub-Report Data Sources...................................................500
Configuring Exporter Parameters...................................................................500
16.8.Feed Views..................................................................................................501
16.9.XML Marshalling View................................................................................502
16.10.JSON Mapping View..................................................................................502
17.Integrating with other web frameworks.....................................................................503
17.1.Introduction.................................................................................................503
17.2.Common configuration.................................................................................504
17.3.JavaServer Faces 1.1 and 1.2.........................................................................505
DelegatingVariableResolver (JSF 1.1/1.2)......................................................505
SpringBeanVariableResolver (JSF 1.1/1.2).....................................................506
SpringBeanFacesELResolver (JSF 1.2+)........................................................506
FacesContextUtils........................................................................................507
17.4.Apache Struts 1.x and 2.x.............................................................................507
ContextLoaderPlugin....................................................................................508
DelegatingRequestProcessor.................................................................509
DelegatingActionProxy.........................................................................509
ActionSupport Classes..................................................................................510
17.5.WebWork 2.x...............................................................................................510
Spring Framework
3.0 Reference Documentation xvi
17.6.Tapestry 3.x and 4.x.....................................................................................511
Injecting Spring-managed beans....................................................................512
Dependency Injecting Spring Beans into Tapestry pages.........................513
Component definition files....................................................................514
Adding abstract accessors......................................................................515
Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style
.............................................................................................................517
17.7.Further Resources.........................................................................................518
18.Portlet MVC Framework.........................................................................................519
18.1.Introduction.................................................................................................519
Controllers - The C in MVC..........................................................................520
Views - The V in MVC.................................................................................520
Web-scoped beans........................................................................................521
18.2.The DispatcherPortlet...................................................................................521
18.3.The ViewRendererServlet.............................................................................523
18.4.Controllers...................................................................................................524
AbstractController and PortletContentGenerator.............................................524
Other simple controllers................................................................................526
Command Controllers...................................................................................526
PortletWrappingController............................................................................527
18.5.Handler mappings........................................................................................527
PortletModeHandlerMapping........................................................................528
ParameterHandlerMapping............................................................................529
PortletModeParameterHandlerMapping.........................................................529
Adding HandlerInterceptors..........................................................................530
HandlerInterceptorAdapter............................................................................530
ParameterMappingInterceptor.......................................................................530
18.6.Views and resolving them.............................................................................531
18.7.Multipart (file upload) support......................................................................531
Using the PortletMultipartResolver................................................................532
Handling a file upload in a form....................................................................532
18.8.Handling exceptions.....................................................................................535
18.9.Annotation-based controller configuration.....................................................536
Setting up the dispatcher for annotation support..............................................536
Defining a controller with @Controller..........................................................536
Mapping requests with @RequestMapping.....................................................537
Supported handler method arguments............................................................538
Binding request parameters to method parameters with @RequestParam..........540
Providing a link to data fromthe model with @ModelAttribute.......................541
Specifying attributes to store in a Session with @SessionAttributes.................541
Customizing WebDataBinder initialization.....................................................542
Customizing data binding with @InitBinder...........................................542
Configuring a customWebBindingInitializer..........................................542
18.10.Portlet application deployment....................................................................543
VI.Integration......................................................................................................................544
Spring Framework
3.0 Reference Documentation xvii
19.Remoting and web services using Spring..................................................................545
19.1.Introduction.................................................................................................545
19.2.Exposing services using RMI........................................................................546
Exporting the service using the RmiServiceExporter.......................................546
Linking in the service at the client.................................................................547
19.3.Using Hessian or Burlap to remotely call services via HTTP...........................548
Wiring up the DispatcherServlet for Hessian and co........................................548
Exposing your beans by using the HessianServiceExporter..............................548
Linking in the service on the client................................................................549
Using Burlap................................................................................................549
Applying HTTP basic authentication to a service exposed through Hessian or
Burlap..........................................................................................................550
19.4.Exposing services using HTTP invokers........................................................550
Exposing the service object...........................................................................550
Linking in the service at the client.................................................................551
19.5.Web services................................................................................................552
Exposing servlet-based web services using JAX-RPC.....................................553
Accessing web services using JAX-RPC........................................................553
Registering JAX-RPC Bean Mappings...........................................................555
Registering your own JAX-RPC Handler.......................................................556
Exposing servlet-based web services using JAX-WS......................................556
Exporting standalone web services using JAX-WS.........................................557
Exporting web services using the JAX-WS RI's Spring support.......................558
Accessing web services using JAX-WS..........................................................558
19.6.JMS.............................................................................................................559
Server-side configuration..............................................................................560
Client-side configuration...............................................................................561
19.7.Auto-detection is not implemented for remote interfaces.................................562
19.8.Considerations when choosing a technology...................................................562
19.9.Accessing RESTful services on the Client......................................................563
RestTemplate...............................................................................................563
Dealing with request and response headers.............................................565
HTTP Message Conversion...........................................................................566
StringHttpMessageConverter.................................................................566
FormHttpMessageConverter..................................................................566
ByteArrayMessageConverter.................................................................567
MarshallingHttpMessageConverter........................................................567
MappingJacksonHttpMessageConverter.................................................567
SourceHttpMessageConverter...............................................................567
BufferedImageHttpMessageConverter...................................................567
20.Enterprise JavaBeans (EJB) integration....................................................................568
20.1.Introduction.................................................................................................568
20.2.Accessing EJBs............................................................................................568
Concepts......................................................................................................568
Accessing local SLSBs.................................................................................569
Spring Framework
3.0 Reference Documentation xviii
Accessing remote SLSBs..............................................................................570
Accessing EJB 2.x SLSBs versus EJB 3 SLSBs..............................................571
20.3.Using Spring's EJB implementation support classes........................................571
EJB 2.x base classes.....................................................................................571
EJB 3 injection interceptor............................................................................573
21.JMS (Java Message Service)....................................................................................575
21.1.Introduction.................................................................................................575
21.2.Using Spring JMS........................................................................................575
JmsTemplate................................................................................................575
Connections.................................................................................................576
Caching Messaging Resources...............................................................577
SingleConnectionFactory......................................................................577
CachingConnectionFactory...................................................................577
Destination Management...............................................................................577
Message Listener Containers.........................................................................578
SimpleMessageListenerContainer..........................................................579
DefaultMessageListenerContainer.........................................................579
Transaction management...............................................................................579
21.3.Sending a Message.......................................................................................580
Using Message Converters............................................................................581
SessionCallback and ProducerCallback..........................................................582
21.4.Receiving a message.....................................................................................582
Synchronous Reception.................................................................................582
Asynchronous Reception - Message-Driven POJOs........................................582
The SessionAwareMessageListener interface.................................................583
The MessageListenerAdapter........................................................................583
Processing messages within transactions........................................................585
21.5.Support for JCA Message Endpoints..............................................................586
21.6.JMS Namespace Support..............................................................................588
22.JMX.......................................................................................................................593
22.1.Introduction.................................................................................................593
22.2.Exporting your beans to JMX........................................................................593
Creating an MBeanServer.............................................................................594
Reusing an existing MBeanServer.................................................................595
Lazy-initialized MBeans...............................................................................596
Automatic registration of MBeans.................................................................596
Controlling the registration behavior..............................................................596
22.3.Controlling the management interface of your beans.......................................598
The MBeanInfoAssembler Interface..............................................................598
Using Source-Level Metadata (JDK 5.0 annotations)......................................598
Source-Level Metadata Types.......................................................................600
The AutodetectCapableMBeanInfoAssembler interface...................................602
Defining management interfaces using Java interfaces....................................603
Using MethodNameBasedMBeanInfoAssembler............................................604
22.4.Controlling the ObjectNames for your beans..................................................604
Spring Framework
3.0 Reference Documentation xix
Reading ObjectNames fromProperties...........................................................605
Using the MetadataNamingStrategy...............................................................606
The <context:mbean-export/> element...........................................................606
22.5.JSR-160 Connectors.....................................................................................607
Server-side Connectors.................................................................................607
Client-side Connectors..................................................................................608
JMX over Burlap/Hessian/SOAP...................................................................608
22.6.Accessing MBeans via Proxies......................................................................609
22.7.Notifications................................................................................................609
Registering Listeners for Notifications...........................................................609
Publishing Notifications................................................................................613
22.8.Further Resources.........................................................................................614
23.JCA CCI.................................................................................................................615
23.1.Introduction.................................................................................................615
23.2.Configuring CCI..........................................................................................615
Connector configuration................................................................................615
ConnectionFactory configuration in Spring....................................................616
Configuring CCI connections........................................................................617
Using a single CCI connection.......................................................................617
23.3.Using Spring's CCI access support.................................................................618
Record conversion........................................................................................618
The CciTemplate..........................................................................................619
DAO support................................................................................................620
Automatic output record generation...............................................................621
Summary.....................................................................................................621
Using a CCI Connection and Interaction directly............................................622
Example for CciTemplate usage....................................................................623
23.4.Modeling CCI access as operation objects......................................................625
MappingRecordOperation.............................................................................625
MappingCommAreaOperation.......................................................................626
Automatic output record generation...............................................................626
Summary.....................................................................................................626
Example for MappingRecordOperation usage.................................................627
Example for MappingCommAreaOperation usage..........................................629
23.5.Transactions.................................................................................................630
24.Email.....................................................................................................................632
24.1.Introduction.................................................................................................632
24.2.Usage..........................................................................................................632
Basic MailSender and SimpleMailMessage usage...........................................633
Using the JavaMailSender and the MimeMessagePreparator...........................634
24.3.Using the JavaMail MimeMessageHelper......................................................635
Sending attachments and inline resources.......................................................635
Attachments.........................................................................................635
Inline resources....................................................................................635
Creating email content using a templating library...........................................636
Spring Framework
3.0 Reference Documentation xx
A Velocity-based example....................................................................637
25.Task Execution and Scheduling................................................................................639
25.1.Introduction.................................................................................................639
25.2.The Spring TaskExecutor abstraction.............................................................639