spring-framework-reference

Préparation du document



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, 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.
Spring Framework
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.0 ...................................................................................................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 system and 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
III. Core Technologies ............................................................................................................23
3. The IoC container .......................................................................................................24
3.0 Reference Documentation ii
Spring Framework
3.1. Introduction to the Spring IoC container and beans .............................................24
3.2. Container overview ..........................................................................................24
Configuration metadata ...................................................................................25
Instantiating a container ..................................................................................26
Composing XML-based configuration metadata .......................................28
Using the container .........................................................................................28
3.3. Bean overview .................................................................................................29
Naming beans .................................................................................................30
Aliasing a bean outside the bean definition ...............................................31
Instantiating beans ..........................................................................................32
Instantiation with a constructor ................................................................32
Instantiation with a static factory method .................................................33
Instantiation using an instance factory method ..........................................33
3.4. Dependencies ...................................................................................................35
Dependency injection ......................................................................................35
Constructor-based dependency injection ...................................................35
Setter-based dependency injection ...........................................................37
Dependency resolution process ................................................................38
Examples of dependency injection ...........................................................40
Dependencies and configuration in detail .........................................................42
Straight values (primitives, Strings, and so on) .........................................42
References to other beans (collaborators) .................................................43
Inner beans .............................................................................................44
Collections .............................................................................................45
Null and empty string values ...................................................................47
XML shortcut with the p-namespace ........................................................48
XML shortcut with the c-namespace ........................................................49
Compound property names ......................................................................50
Using depends-on ...........................................................................................50
Lazy-initialized beans .....................................................................................51
Autowiring collaborators .................................................................................51
Limitations and disadvantages of autowiring ............................................53
Excluding a bean from autowiring ...........................................................53
Method injection ............................................................................................54
Lookup method injection .........................................................................55
Arbitrary method replacement .................................................................56
3.5. Bean scopes .....................................................................................................57
The singleton scope ........................................................................................58
The prototype scope ........................................................................................59
Singleton beans with prototype-bean dependencies ...........................................60
Request, session, and global session scopes ......................................................60
Initial web configuration .........................................................................60
Request scope .........................................................................................61
Session scope .........................................................................................61
Global session scope ...............................................................................62
3.0 Reference Documentation iii
Spring Framework
Scoped beans as dependencies .................................................................62
Custom scopes ...............................................................................................64
Creating a custom scope ..........................................................................64
Using a custom scope ..............................................................................65
3.6. Customizing the nature of a bean .......................................................................66
Lifecycle callbacks .........................................................................................67
Initialization callbacks ............................................................................67
Destruction callbacks ..............................................................................68
Default initialization and destroy methods ................................................68
Combining lifecycle mechanisms ............................................................70
Startup and shutdown callbacks ...............................................................70
Shutting down the Spring IoC container gracefully in non-web applications 72
ApplicationContextAware and BeanNameAware ..............................................73
Other Aware interfaces ...................................................................................73
3.7. Bean definition inheritance ...............................................................................75
3.8. Container Extension Points ...............................................................................77
Customizing beans using a BeanPostProcessor .................................................77
Example: Hello World, BeanPostProcessor-style ......................................78
Example: The RequiredAnnotationBeanPostProcessor ..............................79
Customizing configuration metadata with a BeanFactoryPostProcessor ..............80
Example: the PropertyPlaceholderConfigurer ...........................................81
Example: the PropertyOverrideConfigurer ...............................................82
Customizing instantiation logic with a FactoryBean ..........................................83
3.9. Annotation-based container configuration ..........................................................84
@Required .....................................................................................................85
@Autowired and @Inject ................................................................................86
Fine-tuning annotation-based autowiring with qualifiers ...................................88
CustomAutowireConfigurer ............................................................................94
@Resource .....................................................................................................94
@PostConstruct and @PreDestroy ...................................................................96
3.10. Classpath scanning and managed components ..................................................96
@Component and further stereotype annotations ..............................................97
Automatically detecting classes and registering bean definitions ........................97
Using filters to customize scanning ..................................................................98
Defining bean metadata within components ......................................................99
Naming autodetected components .................................................................. 100
Providing a scope for autodetected components .............................................. 101
Providing qualifier metadata with annotations ................................................ 102
3.11. Using JSR 330 standard annotations .............................................................. 103
Dependency Injection with @Inject and @Named .......................................... 103
@Named: a standard equivalent to the @Component annotation ...................... 104
Limitations of the standard approach .............................................................. 105
3.12. Java-based container configuration ................................................................ 105
Basic concepts: @Configuration and @Bean .................................................. 105
Instantiating the Spring container using AnnotationConfigApplicationContext . 106
3.0 Reference Documentation iv
Spring Framework
Simple construction .............................................................................. 106
Building the container programmatically using register(Class<?>...) ........ 107
Enabling component scanning with scan(String...) .................................. 107
Support for web applications with AnnotationConfigWebApplicationContext
............................................................................................................. 108
Composing Java-based configurations ............................................................ 109
Using the @Import annotation ............................................................... 109
Combining Java and XML configuration ................................................ 111
Using the @Bean annotation ......................................................................... 114
Declaring a bean ................................................................................... 114
Injecting dependencies .......................................................................... 114
Receiving lifecycle callbacks ................................................................. 115
Specifying bean scope ........................................................................... 116
Customizing bean naming ..................................................................... 117
Bean aliasing ........................................................................................ 118
Further information about how Java-based configuration works internally ........ 118
3.13. Registering a LoadTimeWeaver .................................................................... 119
3.14. Additional Capabilities of the ApplicationContext .......................................... 119
Internationalization using MessageSource ...................................................... 120
Standard and Custom Events ......................................................................... 123
Convenient access to low-level resources ....................................................... 126
Convenient ApplicationContext instantiation for web applications ................... 126
Deploying a Spring ApplicationContext as a J2EE RAR file ............................ 127
3.15. The BeanFactory .......................................................................................... 128
BeanFactory or ApplicationContext? ............................................................. 128
Glue code and the evil singleton .................................................................... 130
4. Resources ................................................................................................................. 131
4.1. Introduction ................................................................................................... 131
4.2. The Resource interface ................................................................................... 131
4.3. Built-in Resource implementations .................................................................. 132
UrlResource ................................................................................................. 132
ClassPathResource ....................................................................................... 133
FileSystemResource ..................................................................................... 133
ServletContextResource ................................................................................ 133
InputStreamResource .................................................................................... 133
ByteArrayResource ...................................................................................... 134
4.4. The ResourceLoader ....................................................................................... 134
4.5. The ResourceLoaderAware interface ............................................................... 135
4.6. Resources as dependencies ............................................................................. 136
4.7. Application contexts and Resource paths ......................................................... 136
Constructing application contexts .................................................................. 136
Constructing ClassPathXmlApplicationContext instances - shortcuts ....... 137
Wildcards in application context constructor resource paths ............................ 138
Ant-style Patterns ................................................................................. 138
The classpath*: prefix ........................................................................... 139
3.0 Reference Documentation v
Spring Framework
Other notes relating to wildcards ............................................................ 139
FileSystemResource caveats .......................................................................... 140
5. Validation, Data Binding, and Type Conversion .......................................................... 142
5.1. Introduction ................................................................................................... 142
5.2. Validation using Spring's Validator interface .................................................... 142
5.3. Resolving codes to error messages .................................................................. 144
5.4. Bean manipulation and the BeanWrapper ........................................................ 144
Setting and getting basic and nested properties ............................................... 145
Built-in PropertyEditor implementations ........................................................ 146
Registering additional custom PropertyEditors ....................................... 149
5.5. Spring 3 Type Conversion .............................................................................. 152
Converter SPI ............................................................................................... 152
ConverterFactory .......................................................................................... 153
GenericConverter ......................................................................................... 154
ConditionalGenericConverter ................................................................ 154
ConversionService API ................................................................................. 155
Configuring a ConversionService .................................................................. 155
Using a ConversionService programatically ................................................... 156
5.6. Spring 3 Field Formatting ............................................................................... 156
Formatter SPI ............................................................................................... 157
Annotation-driven Formatting ....................................................................... 158
Format Annotation API ......................................................................... 159
FormatterRegistry SPI .................................................................................. 160
FormatterRegistrar SPI ................................................................................. 160
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 Custom Constraints ............................................................ 164
Additional Configuration Options .......................................................... 164
Configuring a DataBinder ............................................................................. 164
Spring MVC 3 Validation ............................................................................. 165
Triggering @Controller Input Validation ............................................... 165
Configuring a Validator for use by Spring MVC ..................................... 165
Configuring a JSR-303 Validator for use by Spring MVC ....................... 166
6. Spring Expression Language (SpEL) .......................................................................... 167
6.1. Introduction ................................................................................................... 167
6.2. Feature Overview ........................................................................................... 167
6.3. Expression Evaluation using Spring's Expression Interface ............................... 168
The EvaluationContext interface .................................................................... 171
Type Conversion .................................................................................. 171
6.4. Expression support for defining bean definitions .............................................. 172
XML based configuration ............................................................................. 172
Annotation-based configuration ..................................................................... 172
3.0 Reference Documentation vi
Spring Framework
6.5. Language Reference ....................................................................................... 174
Literal expressions ........................................................................................ 174
Properties, Arrays, Lists, Maps, Indexers ........................................................ 174
Inline lists .................................................................................................... 175
Array construction ........................................................................................ 175
Methods ....................................................................................................... 176
Operators ..................................................................................................... 176
Relational operators .............................................................................. 176
Logical operators .................................................................................. 177
Mathematical operators ......................................................................... 177
Assignment .................................................................................................. 178
Types ........................................................................................................... 178
Constructors ................................................................................................. 178
Variables ...................................................................................................... 179
The #this and #root variables ................................................................. 179
Functions ..................................................................................................... 179
Bean references ............................................................................................ 180
Ternary Operator (If-Then-Else) .................................................................... 180
The Elvis Operator ....................................................................................... 181
Safe Navigation operator ............................................................................... 181
Collection Selection ...................................................................................... 182
Collection Projection .................................................................................... 182
Expression templating ................................................................................... 183
6.6. Classes used in the examples ........................................................................... 183
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
3.0 Reference Documentation vii
Spring Framework
Advice ordering .................................................................................... 207
Introductions ................................................................................................ 207
Aspect instantiation models ........................................................................... 208
Example ....................................................................................................... 209
7.3. Schema-based AOP support ............................................................................ 210
Declaring an aspect ....................................................................................... 211
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 .................................................... 226
7.8. Using AspectJ with Spring applications ........................................................... 226
Using AspectJ to dependency inject domain objects with Spring ...................... 227
Unit testing @Configurable objects ....................................................... 229
Working with multiple application contexts ............................................ 230
Other Spring aspects for AspectJ ................................................................... 230
Configuring AspectJ aspects using Spring IoC ................................................ 231
Load-time weaving with AspectJ in the Spring Framework ............................. 232
A first example ..................................................................................... 232
Aspects ................................................................................................ 235
'META-INF/aop.xml' ............................................................................ 236
Required libraries (JARS) ..................................................................... 236
Spring configuration ............................................................................. 236
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
3.0 Reference Documentation viii
Spring Framework
AspectJ expression pointcuts ......................................................................... 244
Convenience pointcut implementations .......................................................... 244
Static pointcuts ..................................................................................... 245
Dynamic pointcuts ................................................................................ 246
Pointcut superclasses .................................................................................... 246
Custom pointcuts .......................................................................................... 247
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 ........................................................................................... 272
3.0 Reference Documentation ix