0% found this document useful (0 votes)
1K views855 pages

Spring Framework Reference PDF

Uploaded by

Dimas Fahmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views855 pages

Spring Framework Reference PDF

Uploaded by

Dimas Fahmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 855

Spring Framework Reference Documentation

5.0.0.M1

Rod Johnson , Juergen Hoeller , Keith Donald , Colin Sampaleanu , Rob Harrop , Thomas Risberg , Alef
Arendsen , 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 , Phillip Webb , Rob Winch , Brian Clozel , Stephane Nicoll , Sebastien Deleuze
Copyright © 2004-2016

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee
for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
Spring Framework Reference Documentation

Table of Contents
I. Overview of Spring Framework ................................................................................................ 1
1. Getting Started with Spring ............................................................................................. 2
2. Introduction to the Spring Framework .............................................................................. 3
2.1. Dependency Injection and Inversion of Control ...................................................... 3
2.2. Modules .............................................................................................................. 3
Core Container .................................................................................................. 4
AOP and Instrumentation ................................................................................... 5
Messaging ......................................................................................................... 5
Data Access/Integration ...................................................................................... 5
Web .................................................................................................................. 5
Test ................................................................................................................... 6
2.3. Usage scenarios ................................................................................................. 6
Dependency Management and Naming Conventions ............................................ 9
Spring Dependencies and Depending on Spring ......................................... 11
Maven Dependency Management ............................................................. 11
Maven "Bill Of Materials" Dependency ....................................................... 12
Gradle Dependency Management ............................................................. 12
Ivy Dependency Management ................................................................... 12
Distribution Zip Files ................................................................................. 13
Logging ............................................................................................................ 13
Not Using Commons Logging ................................................................... 13
Using SLF4J ............................................................................................ 14
Using Log4J ............................................................................................. 15
II. Core Technologies ............................................................................................................... 17
3. The IoC container ........................................................................................................ 18
3.1. Introduction to the Spring IoC container and beans .............................................. 18
3.2. Container overview ............................................................................................ 18
Configuration metadata ..................................................................................... 19
Instantiating a container .................................................................................... 20
Composing XML-based configuration metadata .......................................... 21
Using the container .......................................................................................... 22
3.3. Bean overview ................................................................................................... 22
Naming beans .................................................................................................. 23
Aliasing a bean outside the bean definition ................................................ 24
Instantiating beans ........................................................................................... 25
Instantiation with a constructor .................................................................. 26
Instantiation with a static factory method .................................................... 26
Instantiation using an instance factory method ........................................... 26
3.4. Dependencies ................................................................................................... 28
Dependency Injection ....................................................................................... 28
Constructor-based dependency injection .................................................... 28
Setter-based dependency injection ............................................................ 30
Dependency resolution process ................................................................. 31
Examples of dependency injection ............................................................. 32
Dependencies and configuration in detail ........................................................... 34
Straight values (primitives, Strings, and so on) ........................................... 34
References to other beans (collaborators) .................................................. 36

5.0.0.M1 Spring Framework iii


Spring Framework Reference Documentation

Inner beans .............................................................................................. 37


Collections ............................................................................................... 37
Null and empty string values ..................................................................... 39
XML shortcut with the p-namespace .......................................................... 40
XML shortcut with the c-namespace .......................................................... 41
Compound property names ....................................................................... 42
Using depends-on ............................................................................................ 42
Lazy-initialized beans ....................................................................................... 42
Autowiring collaborators .................................................................................... 43
Limitations and disadvantages of autowiring ............................................... 44
Excluding a bean from autowiring .............................................................. 45
Method injection ............................................................................................... 45
Lookup method injection ........................................................................... 46
Arbitrary method replacement ................................................................... 48
3.5. Bean scopes ..................................................................................................... 49
The singleton scope ......................................................................................... 50
The prototype scope ......................................................................................... 50
Singleton beans with prototype-bean dependencies ............................................ 51
Request, session, application, and WebSocket scopes ....................................... 51
Initial web configuration ............................................................................ 52
Request scope ......................................................................................... 52
Session scope .......................................................................................... 53
Application scope ..................................................................................... 53
Scoped beans as dependencies ................................................................ 54
Custom scopes ................................................................................................ 56
Creating a custom scope .......................................................................... 56
Using a custom scope .............................................................................. 57
3.6. Customizing the nature of a bean ....................................................................... 58
Lifecycle callbacks ............................................................................................ 58
Initialization callbacks ............................................................................... 59
Destruction callbacks ................................................................................ 59
Default initialization and destroy methods .................................................. 60
Combining lifecycle mechanisms ............................................................... 61
Startup and shutdown callbacks ................................................................ 62
Shutting down the Spring IoC container gracefully in non-web applications
................................................................................................................. 64
ApplicationContextAware and BeanNameAware ................................................. 64
Other Aware interfaces ..................................................................................... 65
3.7. Bean definition inheritance ................................................................................. 66
3.8. Container Extension Points ................................................................................ 68
Customizing beans using a BeanPostProcessor ................................................. 68
Example: Hello World, BeanPostProcessor-style ........................................ 69
Example: The RequiredAnnotationBeanPostProcessor ............................... 71
Customizing configuration metadata with a BeanFactoryPostProcessor ................ 71
Example: the Class name substitution PropertyPlaceholderConfigurer .......... 72
Example: the PropertyOverrideConfigurer .................................................. 73
Customizing instantiation logic with a FactoryBean ............................................. 74
3.9. Annotation-based container configuration ............................................................ 74
@Required ....................................................................................................... 76
@Autowired ..................................................................................................... 76

5.0.0.M1 Spring Framework iv


Spring Framework Reference Documentation

Fine-tuning annotation-based autowiring with @Primary ..................................... 79


Fine-tuning annotation-based autowiring with qualifiers ....................................... 80
Using generics as autowiring qualifiers .............................................................. 85
CustomAutowireConfigurer ................................................................................ 86
@Resource ...................................................................................................... 86
@PostConstruct and @PreDestroy .................................................................... 88
3.10. Classpath scanning and managed components ................................................. 88
@Component and further stereotype annotations ............................................... 88
Meta-annotations .............................................................................................. 89
Automatically detecting classes and registering bean definitions .......................... 90
Using filters to customize scanning ................................................................... 91
Defining bean metadata within components ....................................................... 92
Naming autodetected components ..................................................................... 94
Providing a scope for autodetected components ................................................ 95
Providing qualifier metadata with annotations ..................................................... 96
3.11. Using JSR 330 Standard Annotations ............................................................... 97
Dependency Injection with @Inject and @Named .............................................. 97
@Named: a standard equivalent to the @Component annotation ........................ 98
Limitations of JSR-330 standard annotations ...................................................... 99
3.12. Java-based container configuration ................................................................. 100
Basic concepts: @Bean and @Configuration ................................................... 100
Instantiating the Spring container using AnnotationConfigApplicationContext ....... 101
Simple construction ................................................................................ 101
Building the container programmatically using register(Class<?>…) ........... 101
Enabling component scanning with scan(String…) .................................... 102
Support for web applications with AnnotationConfigWebApplicationContext
............................................................................................................... 102
Using the @Bean annotation .......................................................................... 103
Declaring a bean .................................................................................... 103
Bean dependencies ................................................................................ 104
Receiving lifecycle callbacks ................................................................... 104
Specifying bean scope ............................................................................ 106
Customizing bean naming ....................................................................... 107
Bean aliasing ......................................................................................... 107
Bean description ..................................................................................... 107
Using the @Configuration annotation ............................................................... 107
Injecting inter-bean dependencies ............................................................ 107
Lookup method injection ......................................................................... 108
Further information about how Java-based configuration works internally.... 109
Composing Java-based configurations ............................................................. 110
Using the @Import annotation ................................................................. 110
Conditionally include @Configuration classes or @Bean methods .............. 114
Combining Java and XML configuration ................................................... 115
3.13. Environment abstraction ................................................................................. 117
Bean definition profiles ................................................................................... 117
@Profile ................................................................................................. 118
XML bean definition profiles ............................................................................ 120
Activating a profile .................................................................................. 120
Default profile ......................................................................................... 121
PropertySource abstraction ............................................................................. 121

5.0.0.M1 Spring Framework v


Spring Framework Reference Documentation

@PropertySource ........................................................................................... 122


Placeholder resolution in statements ................................................................ 123
3.14. Registering a LoadTimeWeaver ...................................................................... 123
3.15. Additional Capabilities of the ApplicationContext .............................................. 124
Internationalization using MessageSource ........................................................ 124
Standard and Custom Events .......................................................................... 127
Annotation-based Event Listeners ............................................................ 130
Asynchronous Listeners .......................................................................... 132
Ordering Listeners .................................................................................. 132
Generic Events ....................................................................................... 132
Convenient access to low-level resources ........................................................ 133
Convenient ApplicationContext instantiation for web applications ....................... 133
Deploying a Spring ApplicationContext as a Java EE RAR file ........................... 134
3.16. The BeanFactory ........................................................................................... 134
BeanFactory or ApplicationContext? ................................................................ 135
Glue code and the evil singleton ..................................................................... 136
4. Resources .................................................................................................................. 137
4.1. Introduction ..................................................................................................... 137
4.2. The Resource interface .................................................................................... 137
4.3. Built-in Resource implementations .................................................................... 138
UrlResource ................................................................................................... 138
ClassPathResource ........................................................................................ 138
FileSystemResource ....................................................................................... 139
ServletContextResource .................................................................................. 139
InputStreamResource ..................................................................................... 139
ByteArrayResource ......................................................................................... 139
4.4. The ResourceLoader ....................................................................................... 139
4.5. The ResourceLoaderAware interface ................................................................ 140
4.6. Resources as dependencies ............................................................................. 141
4.7. Application contexts and Resource paths .......................................................... 141
Constructing application contexts ..................................................................... 141
Constructing ClassPathXmlApplicationContext instances - shortcuts .......... 142
Wildcards in application context constructor resource paths ............................... 142
Ant-style Patterns ................................................................................... 143
The Classpath*: portability classpath*: prefix ............................................ 143
Other notes relating to wildcards ............................................................. 144
FileSystemResource caveats .......................................................................... 144
5. Validation, Data Binding, and Type Conversion ............................................................ 146
5.1. Introduction ..................................................................................................... 146
5.2. Validation using Spring’s Validator interface ...................................................... 146
5.3. Resolving codes to error messages .................................................................. 148
5.4. Bean manipulation and the BeanWrapper ......................................................... 149
Setting and getting basic and nested properties ............................................... 149
Built-in PropertyEditor implementations ............................................................ 151
Registering additional custom PropertyEditors .......................................... 154
5.5. Spring Type Conversion ................................................................................... 156
Converter SPI ................................................................................................ 156
ConverterFactory ............................................................................................ 157
GenericConverter ........................................................................................... 157
ConditionalGenericConverter ................................................................... 158

5.0.0.M1 Spring Framework vi


Spring Framework Reference Documentation

ConversionService API ................................................................................... 158


Configuring a ConversionService ..................................................................... 159
Using a ConversionService programmatically ................................................... 160
5.6. Spring Field Formatting .................................................................................... 160
Formatter SPI ................................................................................................. 161
Annotation-driven Formatting ........................................................................... 162
Format Annotation API ............................................................................ 163
FormatterRegistry SPI ..................................................................................... 163
FormatterRegistrar SPI ................................................................................... 164
Configuring Formatting in Spring MVC ............................................................. 164
5.7. Configuring a global date & time format ............................................................ 164
5.8. Spring Validation ............................................................................................. 166
Overview of the JSR-303 Bean Validation API ................................................. 166
Configuring a Bean Validation Provider ............................................................ 166
Injecting a Validator ................................................................................ 167
Configuring Custom Constraints .............................................................. 167
Spring-driven Method Validation .............................................................. 168
Additional Configuration Options .............................................................. 168
Configuring a DataBinder ................................................................................ 168
Spring MVC 3 Validation ................................................................................. 169
6. Spring Expression Language (SpEL) ........................................................................... 170
6.1. Introduction ..................................................................................................... 170
6.2. Feature Overview ............................................................................................ 170
6.3. Expression Evaluation using Spring’s Expression Interface ................................. 171
The EvaluationContext interface ...................................................................... 173
Type Conversion .................................................................................... 173
Parser configuration ........................................................................................ 174
SpEL compilation ............................................................................................ 174
Compiler configuration ............................................................................ 175
Compiler limitations ................................................................................ 176
6.4. Expression support for defining bean definitions ................................................ 176
XML based configuration ................................................................................ 176
Annotation-based configuration ........................................................................ 177
6.5. Language Reference ........................................................................................ 178
Literal expressions .......................................................................................... 178
Properties, Arrays, Lists, Maps, Indexers ......................................................... 178
Inline lists ....................................................................................................... 179
Inline Maps .................................................................................................... 179
Array construction ........................................................................................... 180
Methods ......................................................................................................... 180
Operators ....................................................................................................... 180
Relational operators ................................................................................ 180
Logical operators .................................................................................... 181
Mathematical operators ........................................................................... 181
Assignment .................................................................................................... 182
Types ............................................................................................................. 182
Constructors ................................................................................................... 182
Variables ........................................................................................................ 183
The #this and #root variables .................................................................. 183
Functions ....................................................................................................... 183

5.0.0.M1 Spring Framework vii


Spring Framework Reference Documentation

Bean references ............................................................................................. 184


Ternary Operator (If-Then-Else) ....................................................................... 184
The Elvis Operator ......................................................................................... 184
Safe Navigation operator ................................................................................ 185
Collection Selection ........................................................................................ 185
Collection Projection ....................................................................................... 186
Expression templating ..................................................................................... 186
6.6. Classes used in the examples .......................................................................... 187
7. Aspect Oriented Programming with Spring ................................................................... 191
7.1. Introduction ..................................................................................................... 191
AOP concepts ................................................................................................ 191
Spring AOP capabilities and goals ................................................................... 193
AOP Proxies .................................................................................................. 194
7.2. @AspectJ support ........................................................................................... 194
Enabling @AspectJ Support ............................................................................ 194
Enabling @AspectJ Support with Java configuration ................................. 194
Enabling @AspectJ Support with XML configuration ................................. 195
Declaring an aspect ........................................................................................ 195
Declaring a pointcut ........................................................................................ 196
Supported Pointcut Designators .............................................................. 196
Combining pointcut expressions .............................................................. 198
Sharing common pointcut definitions ........................................................ 198
Examples ............................................................................................... 200
Writing good pointcuts ............................................................................ 202
Declaring advice ............................................................................................. 203
Before advice ......................................................................................... 203
After returning advice .............................................................................. 203
After throwing advice .............................................................................. 204
After (finally) advice ................................................................................ 205
Around advice ........................................................................................ 205
Advice parameters .................................................................................. 206
Advice ordering ...................................................................................... 209
Introductions ................................................................................................... 210
Aspect instantiation models ............................................................................. 210
Example ......................................................................................................... 211
7.3. Schema-based AOP support ............................................................................ 213
Declaring an aspect ........................................................................................ 213
Declaring a pointcut ........................................................................................ 214
Declaring advice ............................................................................................. 215
Before advice ......................................................................................... 215
After returning advice .............................................................................. 216
After throwing advice .............................................................................. 216
After (finally) advice ................................................................................ 217
Around advice ........................................................................................ 217
Advice parameters .................................................................................. 218
Advice ordering ...................................................................................... 219
Introductions ................................................................................................... 220
Aspect instantiation models ............................................................................. 220
Advisors ......................................................................................................... 220
Example ......................................................................................................... 221

5.0.0.M1 Spring Framework viii


Spring Framework Reference Documentation

7.4. Choosing which AOP declaration style to use .................................................... 223


Spring AOP or full AspectJ? ........................................................................... 223
@AspectJ or XML for Spring AOP? ................................................................. 224
7.5. Mixing aspect types ......................................................................................... 224
7.6. Proxying mechanisms ...................................................................................... 225
Understanding AOP proxies ............................................................................ 225
7.7. Programmatic creation of @AspectJ Proxies ..................................................... 228
7.8. Using AspectJ with Spring applications ............................................................. 228
Using AspectJ to dependency inject domain objects with Spring ........................ 228
Unit testing @Configurable objects .......................................................... 231
Working with multiple application contexts ................................................ 231
Other Spring aspects for AspectJ .................................................................... 231
Configuring AspectJ aspects using Spring IoC ................................................. 232
Load-time weaving with AspectJ in the Spring Framework ................................. 233
A first example ....................................................................................... 233
Aspects .................................................................................................. 236
'META-INF/aop.xml' ................................................................................ 236
Required libraries (JARS) ........................................................................ 237
Spring configuration ................................................................................ 237
Environment-specific configuration ........................................................... 239
7.9. Further Resources ........................................................................................... 241
8. Spring AOP APIs ....................................................................................................... 242
8.1. Introduction ..................................................................................................... 242
8.2. Pointcut API in Spring ...................................................................................... 242
Concepts ........................................................................................................ 242
Operations on pointcuts .................................................................................. 243
AspectJ expression pointcuts .......................................................................... 243
Convenience pointcut implementations ............................................................ 243
Static pointcuts ....................................................................................... 243
Dynamic pointcuts .................................................................................. 244
Pointcut superclasses ..................................................................................... 245
Custom pointcuts ............................................................................................ 245
8.3. Advice API in Spring ........................................................................................ 245
Advice lifecycles ............................................................................................. 245
Advice types in Spring .................................................................................... 245
Interception around advice ...................................................................... 245
Before advice ......................................................................................... 246
Throws advice ........................................................................................ 247
After Returning advice ............................................................................ 248
Introduction advice .................................................................................. 249
8.4. Advisor API in Spring ....................................................................................... 251
8.5. Using the ProxyFactoryBean to create AOP proxies ........................................... 251
Basics ............................................................................................................ 251
JavaBean properties ....................................................................................... 252
JDK- and CGLIB-based proxies ...................................................................... 253
Proxying interfaces ......................................................................................... 253
Proxying classes ............................................................................................ 255
Using 'global' advisors .................................................................................... 256
8.6. Concise proxy definitions ................................................................................. 256
8.7. Creating AOP proxies programmatically with the ProxyFactory ............................ 257

5.0.0.M1 Spring Framework ix


Spring Framework Reference Documentation

8.8. Manipulating advised objects ............................................................................ 258


8.9. Using the "auto-proxy" facility ........................................................................... 259
Autoproxy bean definitions .............................................................................. 259
BeanNameAutoProxyCreator ................................................................... 259
DefaultAdvisorAutoProxyCreator .............................................................. 260
AbstractAdvisorAutoProxyCreator ............................................................ 261
Using metadata-driven auto-proxying ............................................................... 261
8.10. Using TargetSources ...................................................................................... 263
Hot swappable target sources ......................................................................... 263
Pooling target sources .................................................................................... 263
Prototype target sources ................................................................................. 265
ThreadLocal target sources ............................................................................. 265
8.11. Defining new Advice types ............................................................................. 265
8.12. Further resources ........................................................................................... 266
III. Testing .............................................................................................................................. 267
9. Introduction to Spring Testing ...................................................................................... 268
10. Unit Testing .............................................................................................................. 269
10.1. Mock Objects ................................................................................................. 269
Environment ................................................................................................... 269
JNDI .............................................................................................................. 269
Servlet API ..................................................................................................... 269
10.2. Unit Testing support Classes .......................................................................... 269
General testing utilities ................................................................................... 269
Spring MVC ................................................................................................... 270
11. Integration Testing .................................................................................................... 271
11.1. Overview ....................................................................................................... 271
11.2. Goals of Integration Testing ............................................................................ 271
Context management and caching .................................................................. 271
Dependency Injection of test fixtures ............................................................... 272
Transaction management ................................................................................ 272
Support classes for integration testing ............................................................. 273
11.3. JDBC Testing Support ................................................................................... 273
11.4. Annotations ................................................................................................... 273
Spring Testing Annotations ............................................................................. 273
@BootstrapWith ..................................................................................... 274
@ContextConfiguration ........................................................................... 274
@WebAppConfiguration .......................................................................... 274
@ContextHierarchy ................................................................................. 275
@ActiveProfiles ...................................................................................... 275
@TestPropertySource ............................................................................. 276
@DirtiesContext ..................................................................................... 276
@TestExecutionListeners ........................................................................ 278
@Commit ............................................................................................... 278
@Rollback .............................................................................................. 278
@BeforeTransaction ............................................................................... 279
@AfterTransaction .................................................................................. 279
@Sql ..................................................................................................... 279
@SqlConfig ............................................................................................ 279
@SqlGroup ............................................................................................ 280
Standard Annotation Support .......................................................................... 280

5.0.0.M1 Spring Framework x


Spring Framework Reference Documentation

Spring JUnit 4 Testing Annotations .................................................................. 280


@IfProfileValue ....................................................................................... 281
@ProfileValueSourceConfiguration .......................................................... 281
@Timed ................................................................................................. 281
@Repeat ................................................................................................ 282
Meta-Annotation Support for Testing ................................................................ 282
11.5. Spring TestContext Framework ....................................................................... 283
Key abstractions ............................................................................................. 283
TestContext ............................................................................................ 284
TestContextManager ............................................................................... 284
TestExecutionListener ............................................................................. 284
Context Loaders ..................................................................................... 284
Bootstrapping the TestContext framework ........................................................ 285
TestExecutionListener configuration ................................................................. 286
Registering custom TestExecutionListeners .............................................. 286
Automatic discovery of default TestExecutionListeners .............................. 286
Ordering TestExecutionListeners ............................................................. 286
Merging TestExecutionListeners .............................................................. 287
Context management ...................................................................................... 287
Context configuration with XML resources ................................................ 288
Context configuration with Groovy scripts ................................................. 289
Context configuration with annotated classes ........................................... 290
Mixing XML, Groovy scripts, and annotated classes .................................. 291
Context configuration with context initializers ............................................ 292
Context configuration inheritance ............................................................. 292
Context configuration with environment profiles ........................................ 294
Context configuration with test property sources ....................................... 298
Loading a WebApplicationContext ........................................................... 301
Context caching ...................................................................................... 303
Context hierarchies ................................................................................. 304
Dependency injection of test fixtures ................................................................ 306
Testing request and session scoped beans ...................................................... 309
Transaction management ................................................................................ 311
Test-managed transactions ..................................................................... 311
Enabling and disabling transactions ......................................................... 311
Transaction rollback and commit behavior ................................................ 312
Programmatic transaction management ................................................... 312
Executing code outside of a transaction ................................................... 313
Configuring a transaction manager .......................................................... 313
Demonstration of all transaction-related annotations ................................. 314
Executing SQL scripts .................................................................................... 315
Executing SQL scripts programmatically .................................................. 315
Executing SQL scripts declaratively with @Sql ......................................... 316
TestContext Framework support classes .......................................................... 319
Spring JUnit 4 Runner ............................................................................ 319
Spring JUnit 4 Rules .............................................................................. 320
JUnit 4 support classes ........................................................................... 320
TestNG support classes .......................................................................... 321
11.6. Spring MVC Test Framework .......................................................................... 322
Server-Side Tests ........................................................................................... 322

5.0.0.M1 Spring Framework xi


Spring Framework Reference Documentation

Static Imports ......................................................................................... 323


Setup Options ........................................................................................ 323
Performing Requests .............................................................................. 325
Defining Expectations ............................................................................. 326
Filter Registrations .................................................................................. 327
Differences between Out-of-Container and End-to-End Integration Tests.... 327
Further Server-Side Test Examples ......................................................... 328
HtmlUnit Integration ........................................................................................ 328
Why HtmlUnit Integration? ...................................................................... 328
MockMvc and HtmlUnit ........................................................................... 331
MockMvc and WebDriver ........................................................................ 333
MockMvc and Geb ................................................................................. 338
Client-Side REST Tests .................................................................................. 339
Static Imports ......................................................................................... 340
Further Examples of Client-side REST Tests ............................................ 340
11.7. PetClinic Example .......................................................................................... 341
12. Further Resources .................................................................................................... 343
IV. Data Access ..................................................................................................................... 344
13. Transaction Management .......................................................................................... 345
13.1. Introduction to Spring Framework transaction management .............................. 345
13.2. Advantages of the Spring Framework’s transaction support model ..................... 345
Global transactions ......................................................................................... 345
Local transactions ........................................................................................... 346
Spring Framework’s consistent programming model ......................................... 346
13.3. Understanding the Spring Framework transaction abstraction ............................ 347
13.4. Synchronizing resources with transactions ....................................................... 350
High-level synchronization approach ................................................................ 350
Low-level synchronization approach ................................................................. 351
TransactionAwareDataSourceProxy ................................................................. 351
13.5. Declarative transaction management ............................................................... 351
Understanding the Spring Framework’s declarative transaction implementation... 353
Example of declarative transaction implementation ........................................... 353
Rolling back a declarative transaction .............................................................. 357
Configuring different transactional semantics for different beans ........................ 358
<tx:advice/> settings ....................................................................................... 360
Using @Transactional ..................................................................................... 361
@Transactional settings .......................................................................... 366
Multiple Transaction Managers with @Transactional ................................. 367
Custom shortcut annotations ................................................................... 368
Transaction propagation .................................................................................. 368
Required ................................................................................................ 368
RequiresNew .......................................................................................... 369
Nested ................................................................................................... 369
Advising transactional operations ..................................................................... 369
Using @Transactional with AspectJ ................................................................. 372
13.6. Programmatic transaction management ........................................................... 373
Using the TransactionTemplate ....................................................................... 373
Specifying transaction settings ................................................................ 375
Using the PlatformTransactionManager ............................................................ 375
13.7. Choosing between programmatic and declarative transaction management ........ 376

5.0.0.M1 Spring Framework xii


Spring Framework Reference Documentation

13.8. Transaction bound event ................................................................................ 376


13.9. Application server-specific integration .............................................................. 376
IBM WebSphere ............................................................................................. 377
Oracle WebLogic Server ................................................................................. 377
13.10. Solutions to common problems ..................................................................... 377
Use of the wrong transaction manager for a specific DataSource ....................... 377
13.11. Further Resources ....................................................................................... 377
14. DAO support ............................................................................................................ 379
14.1. Introduction .................................................................................................... 379
14.2. Consistent exception hierarchy ....................................................................... 379
14.3. Annotations used for configuring DAO or Repository classes ............................ 380
15. Data access with JDBC ............................................................................................ 382
15.1. Introduction to Spring Framework JDBC .......................................................... 382
Choosing an approach for JDBC database access ........................................... 382
Package hierarchy .......................................................................................... 383
15.2. Using the JDBC core classes to control basic JDBC processing and error
handling ................................................................................................................. 384
JdbcTemplate ................................................................................................. 384
Examples of JdbcTemplate class usage ................................................... 384
JdbcTemplate best practices ................................................................... 386
NamedParameterJdbcTemplate ....................................................................... 388
SQLExceptionTranslator .................................................................................. 390
Executing statements ...................................................................................... 391
Running queries ............................................................................................. 392
Updating the database .................................................................................... 393
Retrieving auto-generated keys ....................................................................... 393
15.3. Controlling database connections .................................................................... 393
DataSource .................................................................................................... 393
DataSourceUtils .............................................................................................. 395
SmartDataSource ........................................................................................... 395
AbstractDataSource ........................................................................................ 395
SingleConnectionDataSource .......................................................................... 395
DriverManagerDataSource .............................................................................. 395
TransactionAwareDataSourceProxy ................................................................. 396
DataSourceTransactionManager ...................................................................... 396
NativeJdbcExtractor ........................................................................................ 396
15.4. JDBC batch operations .................................................................................. 397
Basic batch operations with the JdbcTemplate ................................................. 397
Batch operations with a List of objects ............................................................. 398
Batch operations with multiple batches ............................................................ 399
15.5. Simplifying JDBC operations with the SimpleJdbc classes ................................ 399
Inserting data using SimpleJdbcInsert .............................................................. 400
Retrieving auto-generated keys using SimpleJdbcInsert .................................... 400
Specifying columns for a SimpleJdbcInsert ...................................................... 401
Using SqlParameterSource to provide parameter values ................................... 402
Calling a stored procedure with SimpleJdbcCall ............................................... 402
Explicitly declaring parameters to use for a SimpleJdbcCall ............................... 404
How to define SqlParameters .......................................................................... 405
Calling a stored function using SimpleJdbcCall ................................................. 405
Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................... 406

5.0.0.M1 Spring Framework xiii


Spring Framework Reference Documentation

15.6. Modeling JDBC operations as Java objects ..................................................... 407


SqlQuery ........................................................................................................ 407
MappingSqlQuery ........................................................................................... 408
SqlUpdate ...................................................................................................... 409
StoredProcedure ............................................................................................. 409
15.7. Common problems with parameter and data value handling .............................. 412
Providing SQL type information for parameters ................................................. 412
Handling BLOB and CLOB objects .................................................................. 413
Passing in lists of values for IN clause ............................................................ 414
Handling complex types for stored procedure calls ........................................... 414
15.8. Embedded database support .......................................................................... 416
Why use an embedded database? .................................................................. 416
Creating an embedded database using Spring XML .......................................... 416
Creating an embedded database programmatically ........................................... 416
Selecting the embedded database type ........................................................... 417
Using HSQL ........................................................................................... 417
Using H2 ................................................................................................ 417
Using Derby ........................................................................................... 417
Testing data access logic with an embedded database ..................................... 417
Generating unique names for embedded databases ......................................... 418
Extending the embedded database support ...................................................... 418
15.9. Initializing a DataSource ................................................................................. 419
Initializing a database using Spring XML .......................................................... 419
Initialization of other components that depend on the database .................. 420
16. Object Relational Mapping (ORM) Data Access .......................................................... 422
16.1. Introduction to ORM with Spring ..................................................................... 422
16.2. General ORM integration considerations ......................................................... 423
Resource and transaction management ........................................................... 423
Exception translation ....................................................................................... 424
16.3. Hibernate ....................................................................................................... 424
SessionFactory setup in a Spring container ...................................................... 424
Implementing DAOs based on plain Hibernate API ........................................... 425
Declarative transaction demarcation ................................................................ 426
Programmatic transaction demarcation ............................................................ 428
Transaction management strategies ................................................................ 429
Comparing container-managed and locally defined resources ............................ 431
Spurious application server warnings with Hibernate ......................................... 432
16.4. JPA ............................................................................................................... 433
Three options for JPA setup in a Spring environment ........................................ 433
LocalEntityManagerFactoryBean .............................................................. 433
Obtaining an EntityManagerFactory from JNDI ......................................... 433
LocalContainerEntityManagerFactoryBean ............................................... 434
Dealing with multiple persistence units ..................................................... 436
Implementing DAOs based on plain JPA .......................................................... 436
Transaction Management ................................................................................ 438
JpaDialect ...................................................................................................... 439
17. Marshalling XML using O/X Mappers ......................................................................... 440
17.1. Introduction .................................................................................................... 440
Ease of configuration ...................................................................................... 440
Consistent Interfaces ...................................................................................... 440

5.0.0.M1 Spring Framework xiv


Spring Framework Reference Documentation

Consistent Exception Hierarchy ....................................................................... 440


17.2. Marshaller and Unmarshaller .......................................................................... 440
Marshaller ...................................................................................................... 440
Unmarshaller .................................................................................................. 441
XmlMappingException ..................................................................................... 442
17.3. Using Marshaller and Unmarshaller ................................................................. 442
17.4. XML Schema-based Configuration .................................................................. 444
17.5. JAXB ............................................................................................................. 444
Jaxb2Marshaller ............................................................................................. 444
XML Schema-based Configuration ........................................................... 445
17.6. Castor ........................................................................................................... 445
CastorMarshaller ............................................................................................ 445
Mapping ......................................................................................................... 446
XML Schema-based Configuration ........................................................... 446
17.7. JiBX .............................................................................................................. 447
JibxMarshaller ................................................................................................ 447
XML Schema-based Configuration ........................................................... 447
17.8. XStream ........................................................................................................ 447
XStreamMarshaller ......................................................................................... 448
V. The Web ........................................................................................................................... 449
18. Web MVC framework ................................................................................................ 450
18.1. Introduction to Spring Web MVC framework .................................................... 450
Features of Spring Web MVC ......................................................................... 450
Pluggability of other MVC implementations ...................................................... 452
18.2. The DispatcherServlet .................................................................................... 452
Special Bean Types In the WebApplicationContext ........................................... 456
Default DispatcherServlet Configuration ........................................................... 457
DispatcherServlet Processing Sequence .......................................................... 457
18.3. Implementing Controllers ................................................................................ 459
Defining a controller with @Controller .............................................................. 459
Mapping Requests With @RequestMapping ..................................................... 460
Composed @RequestMapping Variants ................................................... 461
@Controller and AOP Proxying ............................................................... 462
New Support Classes for @RequestMapping methods in Spring MVC 3.1.. 462
URI Template Patterns ........................................................................... 463
URI Template Patterns with Regular Expressions ..................................... 464
Path Patterns ......................................................................................... 464
Path Pattern Comparison ........................................................................ 465
Path Patterns with Placeholders .............................................................. 465
Suffix Pattern Matching ........................................................................... 465
Suffix Pattern Matching and RFD ............................................................ 465
Matrix Variables ...................................................................................... 466
Consumable Media Types ....................................................................... 468
Producible Media Types .......................................................................... 468
Request Parameters and Header Values ................................................. 469
HTTP HEAD and HTTP OPTIONS .......................................................... 469
Defining @RequestMapping handler methods .................................................. 470
Supported method argument types .......................................................... 470
Supported method return types ............................................................... 472
Binding request parameters to method parameters with @RequestParam... 473

5.0.0.M1 Spring Framework xv


Spring Framework Reference Documentation

Mapping the request body with the @RequestBody annotation .................. 474
Mapping the response body with the @ResponseBody annotation ............. 475
Creating REST Controllers with the @RestController annotation ................ 476
Using HttpEntity ...................................................................................... 476
Using @ModelAttribute on a method ....................................................... 476
Using @ModelAttribute on a method argument ......................................... 477
Using @SessionAttributes to store model attributes in the HTTP session
between requests ................................................................................... 479
Using @SessionAttribute to access pre-existing global session attributes.... 480
Using @RequestAttribute to access request attributes .............................. 480
Working with "application/x-www-form-urlencoded" data ............................ 480
Mapping cookie values with the @CookieValue annotation ........................ 481
Mapping request header attributes with the @RequestHeader annotation... 481
Method Parameters And Type Conversion ............................................... 482
Customizing WebDataBinder initialization ................................................. 482
Advising controllers with @ControllerAdvice and @RestControllerAdvice.... 483
Jackson Serialization View Support ......................................................... 484
Jackson JSONP Support ........................................................................ 485
Asynchronous Request Processing .................................................................. 486
Exception Handling for Async Requests ................................................... 487
Intercepting Async Requests ................................................................... 488
HTTP Streaming ..................................................................................... 488
HTTP Streaming With Server-Sent Events ............................................... 488
HTTP Streaming Directly To The OutputStream ....................................... 489
Configuring Asynchronous Request Processing ........................................ 489
Testing Controllers ......................................................................................... 490
18.4. Handler mappings .......................................................................................... 490
Intercepting requests with a HandlerInterceptor ................................................ 491
18.5. Resolving views ............................................................................................. 493
Resolving views with the ViewResolver interface .............................................. 493
Chaining ViewResolvers ................................................................................. 495
Redirecting to Views ....................................................................................... 495
RedirectView .......................................................................................... 496
The redirect: prefix ................................................................................. 497
The forward: prefix ................................................................................. 497
ContentNegotiatingViewResolver ..................................................................... 497
18.6. Using flash attributes ..................................................................................... 499
18.7. Building URIs ................................................................................................. 500
Building URIs to Controllers and methods ........................................................ 501
Building URIs to Controllers and methods from views ....................................... 502
18.8. Using locales ................................................................................................. 503
Obtaining Time Zone Information .................................................................... 503
AcceptHeaderLocaleResolver .......................................................................... 503
CookieLocaleResolver ..................................................................................... 503
SessionLocaleResolver ................................................................................... 504
LocaleChangeInterceptor ................................................................................ 504
18.9. Using themes ................................................................................................ 504
Overview of themes ........................................................................................ 504
Defining themes ............................................................................................. 505
Theme resolvers ............................................................................................. 505

5.0.0.M1 Spring Framework xvi


Spring Framework Reference Documentation

18.10. Spring’s multipart (file upload) support ........................................................... 506


Introduction .................................................................................................... 506
Using a MultipartResolver with Commons FileUpload ........................................ 506
Using a MultipartResolver with Servlet 3.0 ....................................................... 506
Handling a file upload in a form ...................................................................... 507
Handling a file upload request from programmatic clients .................................. 508
18.11. Handling exceptions ..................................................................................... 509
HandlerExceptionResolver .............................................................................. 509
@ExceptionHandler ........................................................................................ 509
Handling Standard Spring MVC Exceptions ...................................................... 510
Annotating Business Exceptions With @ResponseStatus .................................. 511
Customizing the Default Servlet Container Error Page ...................................... 511
18.12. Web Security ............................................................................................... 512
18.13. Convention over configuration support ........................................................... 512
The Controller ControllerClassNameHandlerMapping ........................................ 512
The Model ModelMap (ModelAndView) ............................................................ 513
The View - RequestToViewNameTranslator ..................................................... 514
18.14. HTTP caching support .................................................................................. 515
Cache-Control HTTP header ........................................................................... 516
HTTP caching support for static resources ....................................................... 516
Support for the Cache-Control, ETag and Last-Modified response headers in
Controllers ...................................................................................................... 517
Shallow ETag support ..................................................................................... 518
18.15. Code-based Servlet container initialization ..................................................... 519
18.16. Configuring Spring MVC ............................................................................... 520
Enabling the MVC Java Config or the MVC XML Namespace ............................ 521
Customizing the Provided Configuration ........................................................... 522
Conversion and Formatting ............................................................................. 523
Validation ....................................................................................................... 524
Interceptors .................................................................................................... 525
Content Negotiation ........................................................................................ 526
View Controllers ............................................................................................. 527
View Resolvers .............................................................................................. 527
Serving of Resources ..................................................................................... 528
Falling Back On the "Default" Servlet To Serve Resources ................................ 531
Path Matching ................................................................................................ 532
Message Converters ....................................................................................... 533
Advanced Customizations with MVC Java Config ............................................. 534
Advanced Customizations with the MVC Namespace ........................................ 535
19. View technologies ..................................................................................................... 536
19.1. Introduction .................................................................................................... 536
19.2. Thymeleaf ..................................................................................................... 536
19.3. Groovy Markup Templates .............................................................................. 536
Configuration .................................................................................................. 536
Example ......................................................................................................... 537
19.4. FreeMarker .................................................................................................... 537
Dependencies ................................................................................................ 537
Context configuration ...................................................................................... 537
Creating templates ......................................................................................... 537
Advanced FreeMarker configuration ................................................................. 538

5.0.0.M1 Spring Framework xvii


Spring Framework Reference Documentation

Bind support and form handling ....................................................................... 538


The bind macros .................................................................................... 538
Simple binding ........................................................................................ 538
Form input generation macros ................................................................. 539
HTML escaping and XHTML compliance ................................................. 543
19.5. JSP & JSTL .................................................................................................. 543
View resolvers ................................................................................................ 543
'Plain-old' JSPs versus JSTL ........................................................................... 544
Additional tags facilitating development ............................................................ 544
Using Spring’s form tag library ........................................................................ 544
Configuration .......................................................................................... 544
The form tag .......................................................................................... 545
The input tag .......................................................................................... 546
The checkbox tag ................................................................................... 546
The checkboxes tag ............................................................................... 548
The radiobutton tag ................................................................................ 548
The radiobuttons tag ............................................................................... 548
The password tag ................................................................................... 549
The select tag ........................................................................................ 549
The option tag ........................................................................................ 549
The options tag ...................................................................................... 550
The textarea tag ..................................................................................... 551
The hidden tag ....................................................................................... 551
The errors tag ........................................................................................ 551
HTTP Method Conversion ....................................................................... 553
HTML5 Tags .......................................................................................... 554
19.6. Script templates ............................................................................................. 554
Dependencies ................................................................................................ 554
How to integrate script based templating .......................................................... 555
19.7. XML Marshalling View .................................................................................... 557
19.8. Tiles .............................................................................................................. 557
Dependencies ................................................................................................ 557
How to integrate Tiles ..................................................................................... 557
UrlBasedViewResolver ............................................................................ 558
ResourceBundleViewResolver ................................................................. 558
SimpleSpringPreparerFactory and SpringBeanPreparerFactory ................. 559
19.9. XSLT ............................................................................................................. 559
My First Words ............................................................................................... 560
Bean definitions ...................................................................................... 560
Standard MVC controller code ................................................................. 560
Document transformation ........................................................................ 561
19.10. Document views (PDF/Excel) ........................................................................ 561
Introduction .................................................................................................... 561
Configuration and setup .................................................................................. 562
Document view definitions ....................................................................... 562
Controller code ....................................................................................... 562
Subclassing for Excel views .................................................................... 562
Subclassing for PDF views ..................................................................... 564
19.11. Feed Views ................................................................................................. 564
19.12. JSON Mapping View .................................................................................... 565

5.0.0.M1 Spring Framework xviii


Spring Framework Reference Documentation

19.13. XML Mapping View ...................................................................................... 565


20. CORS Support ......................................................................................................... 566
20.1. Introduction .................................................................................................... 566
20.2. Controller method CORS configuration ............................................................ 566
20.3. Global CORS configuration ............................................................................. 567
JavaConfig ..................................................................................................... 567
XML namespace ............................................................................................ 568
20.4. Advanced Customization ................................................................................ 568
20.5. Filter based CORS support ............................................................................. 568
21. Integrating with other web frameworks ....................................................................... 570
21.1. Introduction .................................................................................................... 570
21.2. Common configuration ................................................................................... 571
21.3. JavaServer Faces 1.2 .................................................................................... 572
SpringBeanFacesELResolver (JSF 1.2+) ......................................................... 572
FacesContextUtils ........................................................................................... 572
21.4. Apache Struts 2.x .......................................................................................... 572
21.5. Tapestry 5.x .................................................................................................. 573
21.6. Further Resources ......................................................................................... 573
22. WebSocket Support .................................................................................................. 574
22.1. Introduction .................................................................................................... 574
WebSocket Fallback Options ........................................................................... 574
A Messaging Architecture ............................................................................... 575
Sub-Protocol Support in WebSocket ................................................................ 575
Should I Use WebSocket? .............................................................................. 575
22.2. WebSocket API ............................................................................................. 576
Create and Configure a WebSocketHandler ..................................................... 576
Customizing the WebSocket Handshake .......................................................... 577
WebSocketHandler Decoration ........................................................................ 578
Deployment Considerations ............................................................................. 578
Configuring the WebSocket Engine ................................................................. 579
Configuring allowed origins ............................................................................. 581
22.3. SockJS Fallback Options ................................................................................ 582
Overview of SockJS ....................................................................................... 582
Enable SockJS ............................................................................................... 583
HTTP Streaming in IE 8, 9: Ajax/XHR vs IFrame .............................................. 584
Heartbeat Messages ....................................................................................... 585
Servlet 3 Async Requests ............................................................................... 585
CORS Headers for SockJS ............................................................................. 586
SockJS Client ................................................................................................. 586
22.4. STOMP Over WebSocket Messaging Architecture ........................................... 588
Overview of STOMP ....................................................................................... 588
Enable STOMP over WebSocket ..................................................................... 589
Flow of Messages .......................................................................................... 591
Annotation Message Handling ......................................................................... 593
Sending Messages ......................................................................................... 595
Simple Broker ................................................................................................ 595
Full-Featured Broker ....................................................................................... 595
Connections To Full-Featured Broker .............................................................. 596
Using Dot as Separator in @MessageMapping Destinations .............................. 597
Authentication ................................................................................................. 598

5.0.0.M1 Spring Framework xix


Spring Framework Reference Documentation

User Destinations ........................................................................................... 599


Listening To ApplicationContext Events and Intercepting Messages ................... 600
STOMP Client ................................................................................................ 601
WebSocket Scope .......................................................................................... 603
Configuration and Performance ....................................................................... 604
Runtime Monitoring ......................................................................................... 607
Testing Annotated Controller Methods ............................................................. 608
23. Web Reactive Framework ......................................................................................... 609
23.1. Introduction .................................................................................................... 609
Reactive Programming .................................................................................... 609
Spring Web Reactive Types ............................................................................ 609
23.2. Spring Web Reactive Overview ....................................................................... 609
Spring Web Reactive Module .......................................................................... 609
Reactive Web Client ....................................................................................... 611
23.3. Getting Started .............................................................................................. 612
Spring Boot Starter ......................................................................................... 612
Manual Bootstrapping ..................................................................................... 612
Extent of Support in 5.0 M1 ............................................................................ 612
VI. Integration ......................................................................................................................... 613
24. Remoting and web services using Spring ................................................................... 614
24.1. Introduction .................................................................................................... 614
24.2. Exposing services using RMI .......................................................................... 615
Exporting the service using the RmiServiceExporter ......................................... 615
Linking in the service at the client ................................................................... 616
24.3. Using Hessian to remotely call services via HTTP ............................................ 616
Wiring up the DispatcherServlet for Hessian and co. ......................................... 616
Exposing your beans by using the HessianServiceExporter ............................... 617
Linking in the service on the client .................................................................. 617
Applying HTTP basic authentication to a service exposed through Hessian ......... 618
24.4. Exposing services using HTTP invokers .......................................................... 618
Exposing the service object ............................................................................ 618
Linking in the service at the client ................................................................... 619
24.5. Web services ................................................................................................. 620
Exposing servlet-based web services using JAX-WS ........................................ 620
Exporting standalone web services using JAX-WS ........................................... 621
Exporting web services using the JAX-WS RI’s Spring support .......................... 621
Accessing web services using JAX-WS ........................................................... 622
24.6. JMS .............................................................................................................. 622
Server-side configuration ................................................................................. 623
Client-side configuration .................................................................................. 624
24.7. AMQP ........................................................................................................... 625
24.8. Auto-detection is not implemented for remote interfaces ................................... 625
24.9. Considerations when choosing a technology .................................................... 625
24.10. Accessing RESTful services on the Client ..................................................... 626
RestTemplate ................................................................................................. 626
Working with the URI .............................................................................. 629
Dealing with request and response headers ............................................. 629
Jackson JSON Views support ................................................................. 630
HTTP Message Conversion ............................................................................ 630
StringHttpMessageConverter ................................................................... 630

5.0.0.M1 Spring Framework xx


Spring Framework Reference Documentation

FormHttpMessageConverter .................................................................... 630


ByteArrayHttpMessageConverter ............................................................. 631
MarshallingHttpMessageConverter ........................................................... 631
MappingJackson2HttpMessageConverter ................................................. 631
MappingJackson2XmlHttpMessageConverter ........................................... 631
SourceHttpMessageConverter ................................................................. 631
BufferedImageHttpMessageConverter ...................................................... 631
Async RestTemplate ....................................................................................... 631
25. Enterprise JavaBeans (EJB) integration ..................................................................... 633
25.1. Introduction .................................................................................................... 633
25.2. Accessing EJBs ............................................................................................. 633
Concepts ........................................................................................................ 633
Accessing local SLSBs ................................................................................... 633
Accessing remote SLSBs ................................................................................ 635
Accessing EJB 2.x SLSBs versus EJB 3 SLSBs ............................................... 635
25.3. Using Spring’s EJB implementation support classes ......................................... 636
EJB 3 injection interceptor .............................................................................. 636
26. JMS (Java Message Service) .................................................................................... 637
26.1. Introduction .................................................................................................... 637
26.2. Using Spring JMS .......................................................................................... 637
JmsTemplate .................................................................................................. 637
Connections ................................................................................................... 638
Caching Messaging Resources ............................................................... 638
SingleConnectionFactory ......................................................................... 639
CachingConnectionFactory ...................................................................... 639
Destination Management ................................................................................. 639
Message Listener Containers .......................................................................... 640
SimpleMessageListenerContainer ............................................................ 640
DefaultMessageListenerContainer ............................................................ 641
Transaction management ................................................................................ 641
26.3. Sending a Message ....................................................................................... 642
Using Message Converters ............................................................................. 643
SessionCallback and ProducerCallback ........................................................... 644
26.4. Receiving a message ..................................................................................... 644
Synchronous Reception .................................................................................. 644
Asynchronous Reception - Message-Driven POJOs .......................................... 644
the SessionAwareMessageListener interface .................................................... 645
the MessageListenerAdapter ........................................................................... 645
Processing messages within transactions ........................................................ 647
26.5. Support for JCA Message Endpoints ............................................................... 648
26.6. Annotation-driven listener endpoints ................................................................ 649
Enable listener endpoint annotations ............................................................... 650
Programmatic endpoints registration ................................................................ 650
Annotated endpoint method signature .............................................................. 651
Response management .................................................................................. 652
26.7. JMS Namespace Support ............................................................................... 653
27. JMX ......................................................................................................................... 658
27.1. Introduction .................................................................................................... 658
27.2. Exporting your beans to JMX .......................................................................... 658
Creating an MBeanServer ............................................................................... 660

5.0.0.M1 Spring Framework xxi


Spring Framework Reference Documentation

Reusing an existing MBeanServer ................................................................... 660


Lazy-initialized MBeans ................................................................................... 661
Automatic registration of MBeans .................................................................... 661
Controlling the registration behavior ................................................................. 661
27.3. Controlling the management interface of your beans ........................................ 662
the MBeanInfoAssembler Interface .................................................................. 663
Using Source-Level Metadata (Java annotations) ............................................. 663
Source-Level Metadata Types ......................................................................... 665
the AutodetectCapableMBeanInfoAssembler interface ...................................... 666
Defining management interfaces using Java interfaces ..................................... 667
Using MethodNameBasedMBeanInfoAssembler ............................................... 668
27.4. Controlling the ObjectNames for your beans .................................................... 669
Reading ObjectNames from Properties ............................................................ 669
Using the MetadataNamingStrategy ................................................................. 670
Configuring annotation based MBean export .................................................... 670
27.5. JSR-160 Connectors ...................................................................................... 671
Server-side Connectors ................................................................................... 671
Client-side Connectors .................................................................................... 672
JMX over Hessian or SOAP ............................................................................ 672
27.6. Accessing MBeans via Proxies ....................................................................... 672
27.7. Notifications ................................................................................................... 673
Registering Listeners for Notifications .............................................................. 673
Publishing Notifications ................................................................................... 676
27.8. Further Resources ......................................................................................... 677
28. JCA CCI .................................................................................................................. 679
28.1. Introduction .................................................................................................... 679
28.2. Configuring CCI ............................................................................................. 679
Connector configuration .................................................................................. 679
ConnectionFactory configuration in Spring ....................................................... 680
Configuring CCI connections ........................................................................... 680
Using a single CCI connection ........................................................................ 681
28.3. Using Spring’s CCI access support ................................................................. 682
Record conversion .......................................................................................... 682
the CciTemplate ............................................................................................. 682
DAO support .................................................................................................. 684
Automatic output record generation ................................................................. 685
Summary ....................................................................................................... 685
Using a CCI Connection and Interaction directly ............................................... 686
Example for CciTemplate usage ...................................................................... 686
28.4. Modeling CCI access as operation objects ...................................................... 688
MappingRecordOperation ................................................................................ 688
MappingCommAreaOperation .......................................................................... 689
Automatic output record generation ................................................................. 690
Summary ....................................................................................................... 690
Example for MappingRecordOperation usage ................................................... 690
Example for MappingCommAreaOperation usage ............................................. 692
28.5. Transactions .................................................................................................. 694
29. Email ....................................................................................................................... 695
29.1. Introduction .................................................................................................... 695
29.2. Usage ........................................................................................................... 695

5.0.0.M1 Spring Framework xxii


Spring Framework Reference Documentation

Basic MailSender and SimpleMailMessage usage ............................................ 696


Using the JavaMailSender and the MimeMessagePreparator ............................. 696
29.3. Using the JavaMail MimeMessageHelper ........................................................ 697
Sending attachments and inline resources ....................................................... 698
Attachments ........................................................................................... 698
Inline resources ...................................................................................... 698
Creating email content using a templating library .............................................. 699
30. Task Execution and Scheduling ................................................................................. 700
30.1. Introduction .................................................................................................... 700
30.2. The Spring TaskExecutor abstraction .............................................................. 700
TaskExecutor types ........................................................................................ 700
Using a TaskExecutor ..................................................................................... 701
30.3. The Spring TaskScheduler abstraction ............................................................ 702
the Trigger interface ....................................................................................... 703
Trigger implementations .................................................................................. 703
TaskScheduler implementations ...................................................................... 704
30.4. Annotation Support for Scheduling and Asynchronous Execution ....................... 704
Enable scheduling annotations ........................................................................ 704
The @Scheduled Annotation ........................................................................... 705
The @Async Annotation ................................................................................. 706
Executor qualification with @Async ................................................................. 707
Exception management with @Async .............................................................. 707
30.5. The Task Namespace .................................................................................... 707
The 'scheduler' element .................................................................................. 707
The 'executor' element .................................................................................... 708
The 'scheduled-tasks' element ......................................................................... 709
30.6. Using the Quartz Scheduler ............................................................................ 709
Using the JobDetailFactoryBean ...................................................................... 710
Using the MethodInvokingJobDetailFactoryBean .............................................. 710
Wiring up jobs using triggers and the SchedulerFactoryBean ............................. 711
31. Dynamic language support ........................................................................................ 713
31.1. Introduction .................................................................................................... 713
31.2. A first example .............................................................................................. 713
31.3. Defining beans that are backed by dynamic languages ..................................... 715
Common concepts .......................................................................................... 715
The <lang:language/> element ................................................................ 716
Refreshable beans .................................................................................. 716
Inline dynamic language source files ....................................................... 718
Understanding Constructor Injection in the context of dynamic-language-
backed beans ......................................................................................... 719
JRuby beans .................................................................................................. 720
Groovy beans ................................................................................................. 721
Customizing Groovy objects via a callback ............................................... 722
BeanShell beans ............................................................................................ 724
31.4. Scenarios ...................................................................................................... 725
Scripted Spring MVC Controllers ..................................................................... 725
Scripted Validators ......................................................................................... 726
31.5. Bits and bobs ................................................................................................ 726
AOP - advising scripted beans ........................................................................ 726
Scoping .......................................................................................................... 727

5.0.0.M1 Spring Framework xxiii


Spring Framework Reference Documentation

31.6.Further Resources ......................................................................................... 727


32. Cache Abstraction .................................................................................................... 728
32.1.Introduction .................................................................................................... 728
32.2.Understanding the cache abstraction ............................................................... 728
32.3.Declarative annotation-based caching ............................................................. 729
@Cacheable annotation .................................................................................. 729
Default Key Generation ........................................................................... 730
Custom Key Generation Declaration ........................................................ 730
Default Cache Resolution ........................................................................ 731
Custom cache resolution ......................................................................... 731
Synchronized caching ............................................................................. 732
Conditional caching ................................................................................ 732
Available caching SpEL evaluation context ............................................... 733
@CachePut annotation ................................................................................... 734
@CacheEvict annotation ................................................................................. 734
@Caching annotation ..................................................................................... 735
@CacheConfig annotation .............................................................................. 735
Enable caching annotations ............................................................................ 735
Using custom annotations ............................................................................... 738
32.4. JCache (JSR-107) annotations ....................................................................... 739
Features summary .......................................................................................... 739
Enabling JSR-107 support .............................................................................. 740
32.5. Declarative XML-based caching ...................................................................... 740
32.6. Configuring the cache storage ........................................................................ 741
JDK ConcurrentMap-based Cache ................................................................... 741
EhCache-based Cache ................................................................................... 742
Caffeine Cache .............................................................................................. 742
GemFire-based Cache .................................................................................... 743
JSR-107 Cache .............................................................................................. 743
Dealing with caches without a backing store .................................................... 743
32.7. Plugging-in different back-end caches ............................................................. 743
32.8. How can I set the TTL/TTI/Eviction policy/XXX feature? .................................... 744
VII. Appendices ...................................................................................................................... 745
33. What’s New in the Spring Framework ........................................................................ 746
34. Migrating to Spring Framework 4.x ............................................................................ 747
35. Spring Annotation Programming Model ...................................................................... 748
36. Classic Spring Usage ............................................................................................... 749
36.1. Classic ORM usage ....................................................................................... 749
Hibernate ....................................................................................................... 749
The HibernateTemplate ........................................................................... 749
Implementing Spring-based DAOs without callbacks ................................. 750
36.2. JMS Usage ................................................................................................... 751
JmsTemplate .................................................................................................. 752
Asynchronous Message Reception .................................................................. 752
Connections ................................................................................................... 752
Transaction Management ................................................................................ 752
37. Classic Spring AOP Usage ....................................................................................... 753
37.1. Pointcut API in Spring .................................................................................... 753
Concepts ........................................................................................................ 753
Operations on pointcuts .................................................................................. 754

5.0.0.M1 Spring Framework xxiv


Spring Framework Reference Documentation

AspectJ expression pointcuts .......................................................................... 754


Convenience pointcut implementations ............................................................ 754
Static pointcuts ....................................................................................... 754
Dynamic pointcuts .................................................................................. 755
Pointcut superclasses ..................................................................................... 756
Custom pointcuts ............................................................................................ 756
37.2. Advice API in Spring ...................................................................................... 756
Advice lifecycles ............................................................................................. 756
Advice types in Spring .................................................................................... 757
Interception around advice ...................................................................... 757
Before advice ......................................................................................... 757
Throws advice ........................................................................................ 758
After Returning advice ............................................................................ 759
Introduction advice .................................................................................. 760
37.3. Advisor API in Spring ..................................................................................... 762
37.4. Using the ProxyFactoryBean to create AOP proxies ......................................... 763
Basics ............................................................................................................ 763
JavaBean properties ....................................................................................... 763
JDK- and CGLIB-based proxies ...................................................................... 764
Proxying interfaces ......................................................................................... 765
Proxying classes ............................................................................................ 767
Using 'global' advisors .................................................................................... 768
37.5. Concise proxy definitions ................................................................................ 768
37.6. Creating AOP proxies programmatically with the ProxyFactory .......................... 769
37.7. Manipulating advised objects .......................................................................... 769
37.8. Using the "autoproxy" facility .......................................................................... 771
Autoproxy bean definitions .............................................................................. 771
BeanNameAutoProxyCreator ................................................................... 771
DefaultAdvisorAutoProxyCreator .............................................................. 772
AbstractAdvisorAutoProxyCreator ............................................................ 773
Using metadata-driven auto-proxying ............................................................... 773
37.9. Using TargetSources ...................................................................................... 775
Hot swappable target sources ......................................................................... 775
Pooling target sources .................................................................................... 776
Prototype target sources ................................................................................. 777
ThreadLocal target sources ............................................................................. 777
37.10. Defining new Advice types ............................................................................ 778
37.11. Further resources ......................................................................................... 778
38. XML Schema-based configuration ............................................................................. 779
38.1. Introduction .................................................................................................... 779
38.2. XML Schema-based configuration ................................................................... 779
Referencing the schemas ............................................................................... 779
the util schema ............................................................................................... 780
<util:constant/> ....................................................................................... 781
<util:property-path/> ................................................................................ 782
<util:properties/> ..................................................................................... 784
<util:list/> ................................................................................................ 784
<util:map/> ............................................................................................. 785
<util:set/> ............................................................................................... 785
the jee schema .............................................................................................. 786

5.0.0.M1 Spring Framework xxv


Spring Framework Reference Documentation

<jee:jndi-lookup/> (simple) ....................................................................... 786


<jee:jndi-lookup/> (with single JNDI environment setting) .......................... 787
<jee:jndi-lookup/> (with multiple JNDI environment settings) ...................... 787
<jee:jndi-lookup/> (complex) .................................................................... 787
<jee:local-slsb/> (simple) ......................................................................... 788
<jee:local-slsb/> (complex) ...................................................................... 788
<jee:remote-slsb/> .................................................................................. 788
the lang schema ............................................................................................. 789
the jms schema .............................................................................................. 789
the tx (transaction) schema ............................................................................. 790
the aop schema ............................................................................................. 790
the context schema ........................................................................................ 791
<property-placeholder/> ........................................................................... 791
<annotation-config/> ............................................................................... 791
<component-scan/> ................................................................................ 791
<load-time-weaver/> ............................................................................... 792
<spring-configured/> ............................................................................... 792
<mbean-export/> .................................................................................... 792
the tool schema .............................................................................................. 792
the jdbc schema ............................................................................................. 792
the cache schema .......................................................................................... 792
the beans schema .......................................................................................... 793
39. Extensible XML authoring ......................................................................................... 794
39.1. Introduction .................................................................................................... 794
39.2. Authoring the schema .................................................................................... 794
39.3. Coding a NamespaceHandler ......................................................................... 795
39.4. BeanDefinitionParser ...................................................................................... 796
39.5. Registering the handler and the schema ......................................................... 797
'META-INF/spring.handlers' ............................................................................. 797
'META-INF/spring.schemas' ............................................................................. 798
39.6. Using a custom extension in your Spring XML configuration .............................. 798
39.7. Meatier examples ........................................................................................... 798
Nesting custom tags within custom tags .......................................................... 798
Custom attributes on 'normal' elements ............................................................ 802
39.8. Further Resources ......................................................................................... 804
40. spring JSP Tag Library ............................................................................................. 805
40.1. Introduction .................................................................................................... 805
40.2. The argument tag .......................................................................................... 805
40.3. The bind tag .................................................................................................. 805
40.4. The escapeBody tag ...................................................................................... 806
40.5. The eval tag .................................................................................................. 806
40.6. The hasBindErrors tag ................................................................................... 807
40.7. The htmlEscape tag ....................................................................................... 807
40.8. The message tag ........................................................................................... 807
40.9. The nestedPath tag ....................................................................................... 808
40.10. The param tag ............................................................................................. 809
40.11. The theme tag ............................................................................................. 809
40.12. The transform tag ........................................................................................ 810
40.13. The url tag ................................................................................................... 810
41. spring-form JSP Tag Library ...................................................................................... 812

5.0.0.M1 Spring Framework xxvi


Spring Framework Reference Documentation

41.1. Introduction .................................................................................................... 812


41.2. The button tag ............................................................................................... 812
41.3. The checkbox tag .......................................................................................... 813
41.4. The checkboxes tag ....................................................................................... 814
41.5. The errors tag ............................................................................................... 815
41.6. The form tag ................................................................................................. 816
41.7. The hidden tag .............................................................................................. 817
41.8. The input tag ................................................................................................. 818
41.9. The label tag ................................................................................................. 819
41.10. The option tag ............................................................................................. 820
41.11. The options tag ............................................................................................ 821
41.12. The password tag ........................................................................................ 822
41.13. The radiobutton tag ...................................................................................... 823
41.14. The radiobuttons tag .................................................................................... 825
41.15. The select tag .............................................................................................. 826
41.16. The textarea tag .......................................................................................... 827

5.0.0.M1 Spring Framework xxvii


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

Spring is designed to be non-intrusive, meaning that your domain logic code generally has no
dependencies on the framework itself. In your integration layer (such as the data access layer), some
dependencies on the data access technology and the Spring libraries will exist. However, it should be
easy to isolate these dependencies from the rest of your code base.

This document is a reference guide to Spring Framework features. If you have any requests, comments,
or questions on this document, please post them on the user mailing list. Questions on the Framework
itself should be asked on StackOverflow (see https://spring.io/questions).
Spring Framework Reference Documentation

1. Getting Started with Spring


This reference guide provides detailed information about the Spring Framework. It provides
comprehensive documentation for all features, as well as some background about the underlying
concepts (such as "Dependency Injection") that Spring has embraced.

If you are just getting started with Spring, you may want to begin using the Spring Framework by
creating a Spring Boot based application. Spring Boot provides a quick (and opinionated) way to create
a production-ready Spring based application. It is based on the Spring Framework, favors convention
over configuration, and is designed to get you up and running as quickly as possible.

You can use start.spring.io to generate a basic project or follow one of the "Getting Started" guides like
the Getting Started Building a RESTful Web Service one. As well as being easier to digest, these guides
are very task focused, and most of them are based on Spring Boot. They also cover other projects from
the Spring portfolio that you might want to consider when solving a particular problem.

5.0.0.M1 Spring Framework 2


Spring Framework Reference Documentation

2. Introduction to the Spring Framework


The Spring Framework is a Java platform that provides comprehensive infrastructure support for
developing Java applications. Spring handles the infrastructure so you can focus on your application.

Spring enables you to build applications from "plain old Java objects" (POJOs) and to apply enterprise
services non-invasively to POJOs. This capability applies to the Java SE programming model and to
full and partial Java EE.

Examples of how you, as an application developer, can benefit from the Spring platform:

• Make a Java method execute in a database transaction without having to deal with transaction APIs.

• Make a local Java method a remote procedure without having to deal with remote APIs.

• Make a local Java method a management operation without having to deal with JMX APIs.

• Make a local Java method a message handler without having to deal with JMS APIs.

2.1 Dependency Injection and Inversion of Control


A Java application — a loose term that runs the gamut from constrained, embedded applications to n-tier,
server-side enterprise applications — typically consists of objects that collaborate to form the application
proper. Thus the objects in an application have dependencies on each other.

Although the Java platform provides a wealth of application development functionality, it lacks the
means to organize the basic building blocks into a coherent whole, leaving that task to architects and
developers. Although you can use design patterns such as Factory, Abstract Factory, Builder, Decorator,
and Service Locator to compose the various classes and object instances that make up an application,
these patterns are simply that: best practices given a name, with a description of what the pattern does,
where to apply it, the problems it addresses, and so forth. Patterns are formalized best practices that
you must implement yourself in your application.

The Spring Framework Inversion of Control (IoC) component addresses this concern by providing a
formalized means of composing disparate components into a fully working application ready for use.
The Spring Framework codifies formalized design patterns as first-class objects that you can integrate
into your own application(s). Numerous organizations and institutions use the Spring Framework in this
manner to engineer robust, maintainable applications.

Background

"The question is, what aspect of control are [they] inverting?" Martin Fowler posed this question
about Inversion of Control (IoC) on his site in 2004. Fowler suggested renaming the principle to
make it more self-explanatory and came up with Dependency Injection.

2.2 Modules
The Spring Framework consists of features organized into about 20 modules. These modules are
grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming),
Instrumentation, Messaging, and Test, as shown in the following diagram.

5.0.0.M1 Spring Framework 3


Spring Framework Reference Documentation

Figure 2.1. Overview of the Spring Framework

The following sections list the available modules for each feature along with their artifact names and the
topics they cover. Artifact names correlate to artifact IDs used in Dependency Management tools.

Core Container

The Core Container consists of the spring-core, spring-beans, spring-context, spring-


context-support, and spring-expression (Spring Expression Language) modules.

The spring-core and spring-beans modules provide the fundamental parts of the framework,
including the IoC and Dependency Injection features. The BeanFactory is a sophisticated
implementation of the factory pattern. It removes the need for programmatic singletons and allows you
to decouple the configuration and specification of dependencies from your actual program logic.

The Context (spring-context) module builds on the solid base provided by the Core and Beans
modules: it is a means to access objects in a framework-style manner that is similar to a JNDI registry.
The Context module inherits its features from the Beans module and adds support for internationalization
(using, for example, resource bundles), event propagation, resource loading, and the transparent
creation of contexts by, for example, a Servlet container. The Context module also supports Java EE
features such as EJB, JMX, and basic remoting. The ApplicationContext interface is the focal
point of the Context module. spring-context-support provides support for integrating common
third-party libraries into a Spring application context, in particular for caching (EhCache, JCache) and
scheduling (CommonJ, Quartz).

The spring-expression module provides a powerful Expression Language for querying and
manipulating an object graph at runtime. It is an extension of the unified expression language (unified
EL) as specified in the JSP 2.1 specification. The language supports setting and getting property values,
property assignment, method invocation, accessing the content of arrays, collections and indexers,

5.0.0.M1 Spring Framework 4


Spring Framework Reference Documentation

logical and arithmetic operators, named variables, and retrieval of objects by name from Spring’s IoC
container. It also supports list projection and selection as well as common list aggregations.

AOP and Instrumentation

The spring-aop module provides an AOP Alliance-compliant aspect-oriented programming


implementation allowing you to define, for example, method interceptors and pointcuts to cleanly
decouple code that implements functionality that should be separated. Using source-level metadata
functionality, you can also incorporate behavioral information into your code, in a manner similar to that
of .NET attributes.

The separate spring-aspects module provides integration with AspectJ.

The spring-instrument module provides class instrumentation support and classloader


implementations to be used in certain application servers. The spring-instrument-tomcat module
contains Spring’s instrumentation agent for Tomcat.

Messaging

Spring Framework 4 includes a spring-messaging module with key abstractions from the Spring
Integration project such as Message, MessageChannel, MessageHandler, and others to serve as a
foundation for messaging-based applications. The module also includes a set of annotations for mapping
messages to methods, similar to the Spring MVC annotation based programming model.

Data Access/Integration

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS, and Transaction modules.

The spring-jdbc module provides a JDBC-abstraction layer that removes the need to do tedious
JDBC coding and parsing of database-vendor specific error codes.

The spring-tx module supports programmatic and declarative transaction management for classes
that implement special interfaces and for all your POJOs (Plain Old Java Objects).

The spring-orm module provides integration layers for popular object-relational mapping APIs,
including JPA and Hibernate. Using the spring-orm module you can use these O/R-mapping
frameworks in combination with all of the other features Spring offers, such as the simple declarative
transaction management feature mentioned previously.

The spring-oxm module provides an abstraction layer that supports Object/XML mapping
implementations such as JAXB, Castor, JiBX and XStream.

The spring-jms module (Java Messaging Service) contains features for producing and consuming
messages. Since Spring Framework 4.1, it provides integration with the spring-messaging module.

Web

The Web layer consists of the spring-web, spring-webmvc and spring-websocket modules.

The spring-web module provides basic web-oriented integration features such as multipart file upload
functionality and the initialization of the IoC container using Servlet listeners and a web-oriented
application context. It also contains an HTTP client and the web-related parts of Spring’s remoting
support.

5.0.0.M1 Spring Framework 5


Spring Framework Reference Documentation

The spring-webmvc module (also known as the Web-Servlet module) contains Spring’s model-
view-controller (MVC) and REST Web Services implementation for web applications. Spring’s MVC
framework provides a clean separation between domain model code and web forms and integrates with
all of the other features of the Spring Framework.

Test

The spring-test module supports the unit testing and integration testing of Spring components with
JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of those
contexts. It also provides mock objects that you can use to test your code in isolation.

2.3 Usage scenarios


The building blocks described previously make Spring a logical choice in many scenarios, from
embedded applications that run on resource-constrained devices to full-fledged enterprise applications
that use Spring’s transaction management functionality and web framework integration.

Figure 2.2. Typical full-fledged Spring web application

Spring’s declarative transaction management features make the web application fully transactional,
just as it would be if you used EJB container-managed transactions. All your custom business logic
can be implemented with simple POJOs and managed by Spring’s IoC container. Additional services
include support for sending email and validation that is independent of the web layer, which lets
you choose where to execute validation rules. Spring’s ORM support is integrated with JPA and
Hibernate; for example, when using Hibernate, you can continue to use your existing mapping files and
standard Hibernate SessionFactory configuration. Form controllers seamlessly integrate the web-
layer with the domain model, removing the need for ActionForms or other classes that transform HTTP
parameters to values for your domain model.

5.0.0.M1 Spring Framework 6


Spring Framework Reference Documentation

Figure 2.3. Spring middle-tier using a third-party web framework

Sometimes circumstances do not allow you to completely switch to a different framework. The Spring
Framework does not force you to use everything within it; it is not an all-or-nothing solution. Existing
front-ends built with Struts, Tapestry, JSF or other UI frameworks can be integrated with a Spring-
based middle-tier, which allows you to use Spring transaction features. You simply need to wire up your
business logic using an ApplicationContext and use a WebApplicationContext to integrate
your web layer.

5.0.0.M1 Spring Framework 7


Spring Framework Reference Documentation

Figure 2.4. Remoting usage scenario

When you need to access existing code through web services, you can use Spring’s Hessian-, Rmi-
or HttpInvokerProxyFactoryBean classes. Enabling remote access to existing applications is not
difficult.

Figure 2.5. EJBs - Wrapping existing POJOs

The Spring Framework also provides an access and abstraction layer for Enterprise JavaBeans,
enabling you to reuse your existing POJOs and wrap them in stateless session beans for use in scalable,
fail-safe web applications that might need declarative security.

5.0.0.M1 Spring Framework 8


Spring Framework Reference Documentation

Dependency Management and Naming Conventions


Dependency management and dependency injection are different things. To get those nice features of
Spring into your application (like dependency injection) you need to assemble all the libraries needed (jar
files) and get them onto your classpath at runtime, and possibly at compile time. These dependencies
are not virtual components that are injected, but physical resources in a file system (typically). The
process of dependency management involves locating those resources, storing them and adding them
to classpaths. Dependencies can be direct (e.g. my application depends on Spring at runtime), or indirect
(e.g. my application depends on commons-dbcp which depends on commons-pool). The indirect
dependencies are also known as "transitive" and it is those dependencies that are hardest to identify
and manage.

If you are going to use Spring you need to get a copy of the jar libraries that comprise the pieces of
Spring that you need. To make this easier Spring is packaged as a set of modules that separate the
dependencies as much as possible, so for example if you don’t want to write a web application you
don’t need the spring-web modules. To refer to Spring library modules in this guide we use a shorthand
naming convention spring-* or spring-*.jar, where * represents the short name for the module
(e.g. spring-core, spring-webmvc, spring-jms, etc.). The actual jar file name that you use is
normally the module name concatenated with the version number (e.g. spring-core-5.0.0.M1.jar).

Each release of the Spring Framework will publish artifacts to the following places:

• Maven Central, which is the default repository that Maven queries, and does not require any special
configuration to use. Many of the common libraries that Spring depends on also are available
from Maven Central and a large section of the Spring community uses Maven for dependency
management, so this is convenient for them. The names of the jars here are in the form spring-*-
<version>.jar and the Maven groupId is org.springframework.

• In a public Maven repository hosted specifically for Spring. In addition to the final GA releases, this
repository also hosts development snapshots and milestones. The jar file names are in the same form
as Maven Central, so this is a useful place to get development versions of Spring to use with other
libraries deployed in Maven Central. This repository also contains a bundle distribution zip file that
contains all Spring jars bundled together for easy download.

So the first thing you need to decide is how to manage your dependencies: we generally recommend the
use of an automated system like Maven, Gradle or Ivy, but you can also do it manually by downloading
all the jars yourself.

You will find bellow the list of Spring artifacts. For a more complete description of each modules, see
Section 2.2, “Modules”.
Table 2.1. Spring Framework Artifacts

GroupId ArtifactId Description

org.springframework spring-aop Proxy-based AOP support

org.springframework spring-aspects AspectJ based aspects

org.springframework spring-beans Beans support, including


Groovy

org.springframework spring-context Application context runtime,


including scheduling and
remoting abstractions

5.0.0.M1 Spring Framework 9


Spring Framework Reference Documentation

GroupId ArtifactId Description

org.springframework spring-context-support Support classes for integrating


common third-party libraries
into a Spring application context

org.springframework spring-core Core utilities, used by many


other Spring modules

org.springframework spring-expression Spring Expression Language


(SpEL)

org.springframework spring-instrument Instrumentation agent for JVM


bootstrapping

org.springframework spring-instrument-tomcat Instrumentation agent for


Tomcat

org.springframework spring-jdbc JDBC support package,


including DataSource setup and
JDBC access support

org.springframework spring-jms JMS support package, including


helper classes to send and
receive JMS messages

org.springframework spring-messaging Support for messaging


architectures and protocols

org.springframework spring-orm Object/Relational Mapping,


including JPA and Hibernate
support

org.springframework spring-oxm Object/XML Mapping

org.springframework spring-test Support for unit testing and


integration testing Spring
components

org.springframework spring-tx Transaction infrastructure,


including DAO support and JCA
integration

org.springframework spring-web Web support packages,


including client and web
remoting

org.springframework spring-webmvc REST Web Services and


model-view-controller
implementation for web
applications

org.springframework spring-websocket WebSocket and SockJS


implementations, including
STOMP support

5.0.0.M1 Spring Framework 10


Spring Framework Reference Documentation

Spring Dependencies and Depending on Spring

Although Spring provides integration and support for a huge range of enterprise and other external tools,
it intentionally keeps its mandatory dependencies to an absolute minimum: you shouldn’t have to locate
and download (even automatically) a large number of jar libraries in order to use Spring for simple use
cases. For basic dependency injection there is only one mandatory external dependency, and that is
for logging (see below for a more detailed description of logging options).

Next we outline the basic steps needed to configure an application that depends on Spring, first with
Maven and then with Gradle and finally using Ivy. In all cases, if anything is unclear, refer to the
documentation of your dependency management system, or look at some sample code - Spring itself
uses Gradle to manage dependencies when it is building, and our samples mostly use Gradle or Maven.

Maven Dependency Management

If you are using Maven for dependency management you don’t even need to supply the logging
dependency explicitly. For example, to create an application context and use dependency injection to
configure an application, your Maven dependencies will look like this:

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.0.M1</version>
<scope>runtime</scope>
</dependency>
</dependencies>

That’s it. Note the scope can be declared as runtime if you don’t need to compile against Spring APIs,
which is typically the case for basic dependency injection use cases.

The example above works with the Maven Central repository. To use the Spring Maven repository
(e.g. for milestones or developer snapshots), you need to specify the repository location in your Maven
configuration. For full releases:

<repositories>
<repository>
<id>io.spring.repo.maven.release</id>
<url>http://repo.spring.io/release/</url>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>

For milestones:

<repositories>
<repository>
<id>io.spring.repo.maven.milestone</id>
<url>http://repo.spring.io/milestone/</url>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>

And for snapshots:

<repositories>
<repository>
<id>io.spring.repo.maven.snapshot</id>
<url>http://repo.spring.io/snapshot/</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>

5.0.0.M1 Spring Framework 11


Spring Framework Reference Documentation

Maven "Bill Of Materials" Dependency

It is possible to accidentally mix different versions of Spring JARs when using Maven. For example,
you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an
older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected
issues can arise.

To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency.
You can import the spring-framework-bom in your dependencyManagement section to ensure
that all spring dependencies (both direct and transitive) are at the same version.

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>5.0.0.M1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

An added benefit of using the BOM is that you no longer need to specify the <version> attribute when
depending on Spring Framework artifacts:

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependencies>

Gradle Dependency Management

To use the Spring repository with the Gradle build system, include the appropriate URL in the
repositories section:

repositories {
mavenCentral()
// and optionally...
maven { url "http://repo.spring.io/release" }
}

You can change the repositories URL from /release to /milestone or /snapshot as
appropriate. Once a repository has been configured, you can declare dependencies in the usual Gradle
way:

dependencies {
compile("org.springframework:spring-context:5.0.0.M1")
testCompile("org.springframework:spring-test:5.0.0.M1")
}

Ivy Dependency Management

If you prefer to use Ivy to manage dependencies then there are similar configuration options.

To configure Ivy to point to the Spring repository add the following resolver to your ivysettings.xml:

5.0.0.M1 Spring Framework 12


Spring Framework Reference Documentation

<resolvers>
<ibiblio name="io.spring.repo.maven.release"
m2compatible="true"
root="http://repo.spring.io/release/"/>
</resolvers>

You can change the root URL from /release/ to /milestone/ or /snapshot/ as appropriate.

Once configured, you can add dependencies in the usual way. For example (in ivy.xml):

<dependency org="org.springframework"
name="spring-core" rev="5.0.0.M1" conf="compile->runtime"/>

Distribution Zip Files

Although using a build system that supports dependency management is the recommended way to
obtain the Spring Framework, it is still possible to download a distribution zip file.

Distribution zips are published to the Spring Maven Repository (this is just for our convenience, you
don’t need Maven or any other build system in order to download them).

To download a distribution zip open a web browser to http://repo.spring.io/release/org/springframework/


spring and select the appropriate subfolder for the version that you want. Distribution files end -
dist.zip, for example spring-framework-{spring-version}-RELEASE-dist.zip. Distributions are also
published for milestones and snapshots.

Logging
Logging is a very important dependency for Spring because a) it is the only mandatory external
dependency, b) everyone likes to see some output from the tools they are using, and c) Spring integrates
with lots of other tools all of which have also made a choice of logging dependency. One of the goals
of an application developer is often to have unified logging configured in a central place for the whole
application, including all external components. This is more difficult than it might have been since there
are so many choices of logging framework.

The mandatory logging dependency in Spring is the Jakarta Commons Logging API (JCL). We compile
against JCL and we also make JCL Log objects visible for classes that extend the Spring Framework.
It’s important to users that all versions of Spring use the same logging library: migration is easy because
backwards compatibility is preserved even with applications that extend Spring. The way we do this
is to make one of the modules in Spring depend explicitly on commons-logging (the canonical
implementation of JCL), and then make all the other modules depend on that at compile time. If you are
using Maven for example, and wondering where you picked up the dependency on commons-logging,
then it is from Spring and specifically from the central module called spring-core.

The nice thing about commons-logging is that you don’t need anything else to make your application
work. It has a runtime discovery algorithm that looks for other logging frameworks in well known places
on the classpath and uses one that it thinks is appropriate (or you can tell it which one if you need to).
If nothing else is available you get pretty nice looking logs just from the JDK (java.util.logging or JUL
for short). You should find that your Spring application works and logs happily to the console out of the
box in most situations, and that’s important.

Not Using Commons Logging

Unfortunately, the runtime discovery algorithm in commons-logging, while convenient for the end-
user, is problematic. If we could turn back the clock and start Spring now as a new project it would use

5.0.0.M1 Spring Framework 13


Spring Framework Reference Documentation

a different logging dependency. The first choice would probably be the Simple Logging Facade for Java
( SLF4J), which is also used by a lot of other tools that people use with Spring inside their applications.

There are basically two ways to switch off commons-logging:

1. Exclude the dependency from the spring-core module (as it is the only module that explicitly
depends on commons-logging)

2. Depend on a special commons-logging dependency that replaces the library with an empty jar
(more details can be found in the SLF4J FAQ)

To exclude commons-logging, add the following to your dependencyManagement section:

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.0.M1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

Now this application is probably broken because there is no implementation of the JCL API on the
classpath, so to fix it a new one has to be provided. In the next section we show you how to provide an
alternative implementation of JCL using SLF4J as an example.

Using SLF4J

SLF4J is a cleaner dependency and more efficient at runtime than commons-logging because it uses
compile-time bindings instead of runtime discovery of the other logging frameworks it integrates. This
also means that you have to be more explicit about what you want to happen at runtime, and declare it
or configure it accordingly. SLF4J provides bindings to many common logging frameworks, so you can
usually choose one that you already use, and bind to that for configuration and management.

SLF4J provides bindings to many common logging frameworks, including JCL, and it also does the
reverse: bridges between other logging frameworks and itself. So to use SLF4J with Spring you need
to replace the commons-logging dependency with the SLF4J-JCL bridge. Once you have done that
then logging calls from within Spring will be translated into logging calls to the SLF4J API, so if other
libraries in your application use that API, then you have a single place to configure and manage logging.

A common choice might be to bridge Spring to SLF4J, and then provide explicit binding from SLF4J to
Log4J. You need to supply 4 dependencies (and exclude the existing commons-logging): the bridge,
the SLF4J API, the binding to Log4J, and the Log4J implementation itself. In Maven you would do that
like this

5.0.0.M1 Spring Framework 14


Spring Framework Reference Documentation

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.0.M1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
</dependencies>

That might seem like a lot of dependencies just to get some logging. Well it is, but it is optional, and it
should behave better than the vanilla commons-logging with respect to classloader issues, notably if
you are in a strict container like an OSGi platform. Allegedly there is also a performance benefit because
the bindings are at compile-time not runtime.

A more common choice amongst SLF4J users, which uses fewer steps and generates fewer
dependencies, is to bind directly to Logback. This removes the extra binding step because Logback
implements SLF4J directly, so you only need to depend on two libraries not four ( jcl-over-slf4j and
logback). If you do that you might also need to exclude the slf4j-api dependency from other external
dependencies (not Spring), because you only want one version of that API on the classpath.

Using Log4J

Many people use Log4j as a logging framework for configuration and management purposes. It’s efficient
and well-established, and in fact it’s what we use at runtime when we build and test Spring. Spring
also provides some utilities for configuring and initializing Log4j, so it has an optional compile-time
dependency on Log4j in some modules.

To make Log4j work with the default JCL dependency ( commons-logging) all you need to do is put
Log4j on the classpath, and provide it with a configuration file ( log4j.properties or log4j.xml in
the root of the classpath). So for Maven users this is your dependency declaration:

5.0.0.M1 Spring Framework 15


Spring Framework Reference Documentation

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.0.M1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
</dependencies>

And here’s a sample log4j.properties for logging to the console:

log4j.rootCategory=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n

log4j.category.org.springframework.beans.factory=DEBUG

Runtime Containers with Native JCL

Many people run their Spring applications in a container that itself provides an implementation
of JCL. IBM Websphere Application Server (WAS) is the archetype. This often causes problems,
and unfortunately there is no silver bullet solution; simply excluding commons-logging from your
application is not enough in most situations.

To be clear about this: the problems reported are usually not with JCL per se, or even with commons-
logging: rather they are to do with binding commons-logging to another framework (often Log4J).
This can fail because commons-logging changed the way they do the runtime discovery in between
the older versions (1.0) found in some containers and the modern versions that most people use now
(1.1). Spring does not use any unusual parts of the JCL API, so nothing breaks there, but as soon as
Spring or your application tries to do any logging you can find that the bindings to Log4J are not working.

In such cases with WAS the easiest thing to do is to invert the class loader hierarchy (IBM calls it "parent
last") so that the application controls the JCL dependency, not the container. That option isn’t always
open, but there are plenty of other suggestions in the public domain for alternative approaches, and
your mileage may vary depending on the exact version and feature set of the container.

5.0.0.M1 Spring Framework 16


Part II. Core Technologies
This part of the reference documentation covers all of those technologies that are absolutely integral
to the Spring Framework.

Foremost amongst these is the Spring Framework’s Inversion of Control (IoC) container. A thorough
treatment of the Spring Framework’s IoC container is closely followed by comprehensive coverage of
Spring’s Aspect-Oriented Programming (AOP) technologies. The Spring Framework has its own AOP
framework, which is conceptually easy to understand, and which successfully addresses the 80% sweet
spot of AOP requirements in Java enterprise programming.

Coverage of Spring’s integration with AspectJ (currently the richest - in terms of features - and certainly
most mature AOP implementation in the Java enterprise space) is also provided.

• Chapter 3, The IoC container

• Chapter 4, Resources

• Chapter 5, Validation, Data Binding, and Type Conversion

• Chapter 6, Spring Expression Language (SpEL)

• Chapter 7, Aspect Oriented Programming with Spring

• Chapter 8, Spring AOP APIs


Spring Framework Reference Documentation

3. The IoC container


3.1 Introduction to the Spring IoC container and beans
1
This chapter covers the Spring Framework implementation of the Inversion of Control (IoC) principle.
IoC is also known as dependency injection (DI). It is a process whereby objects define their
dependencies, that is, the other objects they work with, only through constructor arguments, arguments
to a factory method, or properties that are set on the object instance after it is constructed or returned
from a factory method. The container then injects those dependencies when it creates the bean. This
process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself
controlling the instantiation or location of its dependencies by using direct construction of classes, or a
mechanism such as the Service Locator pattern.

The org.springframework.beans and org.springframework.context packages are the


basis for Spring Framework’s IoC container. The BeanFactory interface provides an advanced
configuration mechanism capable of managing any type of object. ApplicationContext is a sub-
interface of BeanFactory. It adds easier integration with Spring’s AOP features; message resource
handling (for use in internationalization), event publication; and application-layer specific contexts such
as the WebApplicationContext for use in web applications.

In short, the BeanFactory provides the configuration framework and basic functionality, and the
ApplicationContext adds more enterprise-specific functionality. The ApplicationContext is
a complete superset of the BeanFactory, and is used exclusively in this chapter in descriptions
of Spring’s IoC container. For more information on using the BeanFactory instead of the
ApplicationContext, refer to Section 3.16, “The BeanFactory”.

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC
container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed
by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans,
and the dependencies among them, are reflected in the configuration metadata used by a container.

3.2 Container overview


The interface org.springframework.context.ApplicationContext represents the Spring IoC
container and is responsible for instantiating, configuring, and assembling the aforementioned beans.
The container gets its instructions on what objects to instantiate, configure, and assemble by reading
configuration metadata. The configuration metadata is represented in XML, Java annotations, or Java
code. It allows you to express the objects that compose your application and the rich interdependencies
between such objects.

Several implementations of the ApplicationContext interface are supplied out-of-the-


box with Spring. In standalone applications it is common to create an instance of
ClassPathXmlApplicationContext or FileSystemXmlApplicationContext. While XML has
been the traditional format for defining configuration metadata you can instruct the container to use
Java annotations or code as the metadata format by providing a small amount of XML configuration to
declaratively enable support for these additional metadata formats.

In most application scenarios, explicit user code is not required to instantiate one or more instances
of a Spring IoC container. For example, in a web application scenario, a simple eight (or so) lines

1
See Background

5.0.0.M1 Spring Framework 18


Spring Framework Reference Documentation

of boilerplate web descriptor XML in the web.xml file of the application will typically suffice (see the
section called “Convenient ApplicationContext instantiation for web applications”). If you are using the
Spring Tool Suite Eclipse-powered development environment this boilerplate configuration can be easily
created with few mouse clicks or keystrokes.

The following diagram is a high-level view of how Spring works. Your application classes are combined
with configuration metadata so that after the ApplicationContext is created and initialized, you have
a fully configured and executable system or application.

Figure 3.1. The Spring IoC container

Configuration metadata

As the preceding diagram shows, the Spring IoC container consumes a form of configuration metadata;
this configuration metadata represents how you as an application developer tell the Spring container to
instantiate, configure, and assemble the objects in your application.

Configuration metadata is traditionally supplied in a simple and intuitive XML format, which is what most
of this chapter uses to convey key concepts and features of the Spring IoC container.

Note

XML-based metadata is not the only allowed form of configuration metadata. The Spring IoC
container itself is totally decoupled from the format in which this configuration metadata is
actually written. These days many developers choose Java-based configuration for their Spring
applications.

For information about using other forms of metadata with the Spring container, see:

• Annotation-based configuration: Spring 2.5 introduced support for annotation-based configuration


metadata.

• Java-based configuration: Starting with Spring 3.0, many features provided by the Spring JavaConfig
project became part of the core Spring Framework. Thus you can define beans external to your
application classes by using Java rather than XML files. To use these new features, see the
@Configuration, @Bean, @Import and @DependsOn annotations.

Spring configuration consists of at least one and typically more than one bean definition that the
container must manage. XML-based configuration metadata shows these beans configured as <bean/
> elements inside a top-level <beans/> element. Java configuration typically uses @Bean annotated
methods within a @Configuration class.

5.0.0.M1 Spring Framework 19


Spring Framework Reference Documentation

These bean definitions correspond to the actual objects that make up your application. Typically you
define service layer objects, data access objects (DAOs), presentation objects such as Struts Action
instances, infrastructure objects such as Hibernate SessionFactories, JMS Queues, and so forth.
Typically one does not configure fine-grained domain objects in the container, because it is usually the
responsibility of DAOs and business logic to create and load domain objects. However, you can use
Spring’s integration with AspectJ to configure objects that have been created outside the control of an
IoC container. See Using AspectJ to dependency-inject domain objects with Spring.

The following example shows the basic structure of XML-based configuration metadata:

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="..." class="...">


<!-- collaborators and configuration for this bean go here -->
</bean>

<bean id="..." class="...">


<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- more bean definitions go here -->

</beans>

The id attribute is a string that you use to identify the individual bean definition. The class attribute
defines the type of the bean and uses the fully qualified classname. The value of the id attribute refers
to collaborating objects. The XML for referring to collaborating objects is not shown in this example; see
Dependencies for more information.

Instantiating a container

Instantiating a Spring IoC container is straightforward. The location path or paths supplied to an
ApplicationContext constructor are actually resource strings that allow the container to load
configuration metadata from a variety of external resources such as the local file system, from the Java
CLASSPATH, and so on.

ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

Note

After you learn about Spring’s IoC container, you may want to know more about Spring’s
Resource abstraction, as described in Chapter 4, Resources, which provides a convenient
mechanism for reading an InputStream from locations defined in a URI syntax. In particular,
Resource paths are used to construct applications contexts as described in Section 4.7,
“Application contexts and Resource paths”.

The following example shows the service layer objects (services.xml) configuration file:

5.0.0.M1 Spring Framework 20


Spring Framework Reference Documentation

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- services -->

<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">


<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>

<!-- more bean definitions for services go here -->

</beans>

The following example shows the data access objects daos.xml file:

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="accountDao"
class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>

<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">


<!-- additional collaborators and configuration for this bean go here -->
</bean>

<!-- more bean definitions for data access objects go here -->

</beans>

In the preceding example, the service layer consists of the class PetStoreServiceImpl, and two data
access objects of the type JpaAccountDao and JpaItemDao (based on the JPA Object/Relational
mapping standard). The property name element refers to the name of the JavaBean property,
and the ref element refers to the name of another bean definition. This linkage between id and
ref elements expresses the dependency between collaborating objects. For details of configuring an
object’s dependencies, see Dependencies.

Composing XML-based configuration metadata

It can be useful to have bean definitions span multiple XML files. Often each individual XML configuration
file represents a logical layer or module in your architecture.

You can use the application context constructor to load bean definitions from all these XML fragments.
This constructor takes multiple Resource locations, as was shown in the previous section. Alternatively,
use one or more occurrences of the <import/> element to load bean definitions from another file or
files. For example:

<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>

<bean id="bean1" class="..."/>


<bean id="bean2" class="..."/>
</beans>

5.0.0.M1 Spring Framework 21


Spring Framework Reference Documentation

In the preceding example, external bean definitions are loaded from three files: services.xml,
messageSource.xml, and themeSource.xml. All location paths are relative to the definition file
doing the importing, so services.xml must be in the same directory or classpath location as the file
doing the importing, while messageSource.xml and themeSource.xml must be in a resources
location below the location of the importing file. As you can see, a leading slash is ignored, but given
that these paths are relative, it is better form not to use the slash at all. The contents of the files being
imported, including the top level <beans/> element, must be valid XML bean definitions according to
the Spring Schema.

Note

It is possible, but not recommended, to reference files in parent directories using a relative
"../" path. Doing so creates a dependency on a file that is outside the current application. In
particular, this reference is not recommended for "classpath:" URLs (for example, "classpath:../
services.xml"), where the runtime resolution process chooses the "nearest" classpath root and
then looks into its parent directory. Classpath configuration changes may lead to the choice of a
different, incorrect directory.

You can always use fully qualified resource locations instead of relative paths: for example, "file:C:/
config/services.xml" or "classpath:/config/services.xml". However, be aware that you are coupling
your application’s configuration to specific absolute locations. It is generally preferable to keep an
indirection for such absolute locations, for example, through "${…}" placeholders that are resolved
against JVM system properties at runtime.

Using the container


The ApplicationContext is the interface for an advanced factory capable of maintaining a registry
of different beans and their dependencies. Using the method T getBean(String name, Class<T>
requiredType) you can retrieve instances of your beans.

The ApplicationContext enables you to read bean definitions and access them as follows:

// create and configure beans


ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

// retrieve configured instance


PetStoreService service = context.getBean("petStore", PetStoreService.class);

// use configured instance


List<String> userList = service.getUsernameList();

You use getBean() to retrieve instances of your beans. The ApplicationContext interface has a
few other methods for retrieving beans, but ideally your application code should never use them. Indeed,
your application code should have no calls to the getBean() method at all, and thus no dependency
on Spring APIs at all. For example, Spring’s integration with web frameworks provides for dependency
injection for various web framework classes such as controllers and JSF-managed beans.

3.3 Bean overview


A Spring IoC container manages one or more beans. These beans are created with the configuration
metadata that you supply to the container, for example, in the form of XML <bean/> definitions.

Within the container itself, these bean definitions are represented as BeanDefinition objects, which
contain (among other information) the following metadata:

5.0.0.M1 Spring Framework 22


Spring Framework Reference Documentation

• A package-qualified class name: typically the actual implementation class of the bean being defined.

• Bean behavioral configuration elements, which state how the bean should behave in the container
(scope, lifecycle callbacks, and so forth).

• References to other beans that are needed for the bean to do its work; these references are also
called collaborators or dependencies.

• Other configuration settings to set in the newly created object, for example, the number of connections
to use in a bean that manages a connection pool, or the size limit of the pool.

This metadata translates to a set of properties that make up each bean definition.
Table 3.1. The bean definition

Property Explained in…

class the section called “Instantiating beans”

name the section called “Naming beans”

scope Section 3.5, “Bean scopes”

constructor arguments the section called “Dependency Injection”

properties the section called “Dependency Injection”

autowiring mode the section called “Autowiring collaborators”

lazy-initialization mode the section called “Lazy-initialized beans”

initialization method the section called “Initialization callbacks”

destruction method the section called “Destruction callbacks”

In addition to bean definitions that contain information on how to create a specific bean, the
ApplicationContext implementations also permit the registration of existing objects that are
created outside the container, by users. This is done by accessing the ApplicationContext’s
BeanFactory via the method getBeanFactory() which returns the BeanFactory implementation
DefaultListableBeanFactory. DefaultListableBeanFactory supports this registration
through the methods registerSingleton(..) and registerBeanDefinition(..). However,
typical applications work solely with beans defined through metadata bean definitions.

Note

Bean metadata and manually supplied singleton instances need to be registered as early as
possible, in order for the container to properly reason about them during autowiring and other
introspection steps. While overriding of existing metadata and existing singleton instances is
supported to some degree, the registration of new beans at runtime (concurrently with live
access to factory) is not officially supported and may lead to concurrent access exceptions and/
or inconsistent state in the bean container.

Naming beans
Every bean has one or more identifiers. These identifiers must be unique within the container that hosts
the bean. A bean usually has only one identifier, but if it requires more than one, the extra ones can
be considered aliases.

5.0.0.M1 Spring Framework 23


Spring Framework Reference Documentation

In XML-based configuration metadata, you use the id and/or name attributes to specify the bean
identifier(s). The id attribute allows you to specify exactly one id. Conventionally these names are
alphanumeric ('myBean', 'fooService', etc.), but may contain special characters as well. If you want to
introduce other aliases to the bean, you can also specify them in the name attribute, separated by a
comma (,), semicolon (;), or white space. As a historical note, in versions prior to Spring 3.1, the id
attribute was defined as an xsd:ID type, which constrained possible characters. As of 3.1, it is defined
as an xsd:string type. Note that bean id uniqueness is still enforced by the container, though no
longer by XML parsers.

You are not required to supply a name or id for a bean. If no name or id is supplied explicitly, the container
generates a unique name for that bean. However, if you want to refer to that bean by name, through the
use of the ref element or Service Locator style lookup, you must provide a name. Motivations for not
supplying a name are related to using inner beans and autowiring collaborators.

Bean Naming Conventions

The convention is to use the standard Java convention for instance field names when naming
beans. That is, bean names start with a lowercase letter, and are camel-cased from then on.
Examples of such names would be (without quotes) 'accountManager', 'accountService',
'userDao', 'loginController', and so forth.

Naming beans consistently makes your configuration easier to read and understand, and if you
are using Spring AOP it helps a lot when applying advice to a set of beans related by name.

Note

With component scanning in the classpath, Spring generates bean names for unnamed
components, following the rules above: essentially, taking the simple class name and
turning its initial character to lower-case. However, in the (unusual) special case when
there is more than one character and both the first and second characters are upper
case, the original casing gets preserved. These are the same rules as defined by
java.beans.Introspector.decapitalize (which Spring is using here).

Aliasing a bean outside the bean definition

In a bean definition itself, you can supply more than one name for the bean, by using a combination
of up to one name specified by the id attribute, and any number of other names in the name attribute.
These names can be equivalent aliases to the same bean, and are useful for some situations, such as
allowing each component in an application to refer to a common dependency by using a bean name
that is specific to that component itself.

Specifying all aliases where the bean is actually defined is not always adequate, however. It is
sometimes desirable to introduce an alias for a bean that is defined elsewhere. This is commonly the
case in large systems where configuration is split amongst each subsystem, each subsystem having its
own set of object definitions. In XML-based configuration metadata, you can use the <alias/> element
to accomplish this.

<alias name="fromName" alias="toName"/>

In this case, a bean in the same container which is named fromName, may also, after the use of this
alias definition, be referred to as toName.

5.0.0.M1 Spring Framework 24


Spring Framework Reference Documentation

For example, the configuration metadata for subsystem A may refer to a DataSource via the name
subsystemA-dataSource. The configuration metadata for subsystem B may refer to a DataSource
via the name subsystemB-dataSource. When composing the main application that uses both these
subsystems the main application refers to the DataSource via the name myApp-dataSource. To have
all three names refer to the same object you add to the MyApp configuration metadata the following
aliases definitions:

<alias name="subsystemA-dataSource" alias="subsystemB-dataSource"/>


<alias name="subsystemA-dataSource" alias="myApp-dataSource" />

Now each component and the main application can refer to the dataSource through a name that is
unique and guaranteed not to clash with any other definition (effectively creating a namespace), yet
they refer to the same bean.

Java-configuration

If you are using Java-configuration, the @Bean annotation can be used to provide aliases see the
section called “Using the @Bean annotation” for details.

Instantiating beans

A bean definition essentially is a recipe for creating one or more objects. The container looks at the
recipe for a named bean when asked, and uses the configuration metadata encapsulated by that bean
definition to create (or acquire) an actual object.

If you use XML-based configuration metadata, you specify the type (or class) of object that is to be
instantiated in the class attribute of the <bean/> element. This class attribute, which internally is a
Class property on a BeanDefinition instance, is usually mandatory. (For exceptions, see the section
called “Instantiation using an instance factory method” and Section 3.7, “Bean definition inheritance”.)
You use the Class property in one of two ways:

• Typically, to specify the bean class to be constructed in the case where the container itself directly
creates the bean by calling its constructor reflectively, somewhat equivalent to Java code using the
new operator.

• To specify the actual class containing the static factory method that will be invoked to create the
object, in the less common case where the container invokes a static factory method on a class
to create the bean. The object type returned from the invocation of the static factory method may
be the same class or another class entirely.

Inner class names. If you want to configure a bean definition for a static nested class, you
have to use the binary name of the nested class.

For example, if you have a class called Foo in the com.example package, and this Foo class
has a static nested class called Bar, the value of the 'class' attribute on a bean definition
would be…

com.example.Foo$Bar

Notice the use of the $ character in the name to separate the nested class name from the outer
class name.

5.0.0.M1 Spring Framework 25


Spring Framework Reference Documentation

Instantiation with a constructor

When you create a bean by the constructor approach, all normal classes are usable by and compatible
with Spring. That is, the class being developed does not need to implement any specific interfaces or
to be coded in a specific fashion. Simply specifying the bean class should suffice. However, depending
on what type of IoC you use for that specific bean, you may need a default (empty) constructor.

The Spring IoC container can manage virtually any class you want it to manage; it is not limited to
managing true JavaBeans. Most Spring users prefer actual JavaBeans with only a default (no-argument)
constructor and appropriate setters and getters modeled after the properties in the container. You can
also have more exotic non-bean-style classes in your container. If, for example, you need to use a legacy
connection pool that absolutely does not adhere to the JavaBean specification, Spring can manage it
as well.

With XML-based configuration metadata you can specify your bean class as follows:

<bean id="exampleBean" class="examples.ExampleBean"/>

<bean name="anotherExample" class="examples.ExampleBeanTwo"/>

For details about the mechanism for supplying arguments to the constructor (if required) and setting
object instance properties after the object is constructed, see Injecting Dependencies.

Instantiation with a static factory method

When defining a bean that you create with a static factory method, you use the class attribute to specify
the class containing the static factory method and an attribute named factory-method to specify
the name of the factory method itself. You should be able to call this method (with optional arguments as
described later) and return a live object, which subsequently is treated as if it had been created through
a constructor. One use for such a bean definition is to call static factories in legacy code.

The following bean definition specifies that the bean will be created by calling a factory-method. The
definition does not specify the type (class) of the returned object, only the class containing the factory
method. In this example, the createInstance() method must be a static method.

<bean id="clientService"
class="examples.ClientService"
factory-method="createInstance"/>

public class ClientService {


private static ClientService clientService = new ClientService();
private ClientService() {}

public static ClientService createInstance() {


return clientService;
}
}

For details about the mechanism for supplying (optional) arguments to the factory method and
setting object instance properties after the object is returned from the factory, see Dependencies and
configuration in detail.

Instantiation using an instance factory method

Similar to instantiation through a static factory method, instantiation with an instance factory method
invokes a non-static method of an existing bean from the container to create a new bean. To use this
mechanism, leave the class attribute empty, and in the factory-bean attribute, specify the name of a

5.0.0.M1 Spring Framework 26


Spring Framework Reference Documentation

bean in the current (or parent/ancestor) container that contains the instance method that is to be invoked
to create the object. Set the name of the factory method itself with the factory-method attribute.

<!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
<!-- inject any dependencies required by this locator bean -->
</bean>

<!-- the bean to be created via the factory bean -->


<bean id="clientService"
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/>

public class DefaultServiceLocator {

private static ClientService clientService = new ClientServiceImpl();


private DefaultServiceLocator() {}

public ClientService createClientServiceInstance() {


return clientService;
}
}

One factory class can also hold more than one factory method as shown here:

<bean id="serviceLocator" class="examples.DefaultServiceLocator">


<!-- inject any dependencies required by this locator bean -->
</bean>

<bean id="clientService"
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/>

<bean id="accountService"
factory-bean="serviceLocator"
factory-method="createAccountServiceInstance"/>

public class DefaultServiceLocator {

private static ClientService clientService = new ClientServiceImpl();


private static AccountService accountService = new AccountServiceImpl();

private DefaultServiceLocator() {}

public ClientService createClientServiceInstance() {


return clientService;
}

public AccountService createAccountServiceInstance() {


return accountService;
}

This approach shows that the factory bean itself can be managed and configured through dependency
injection (DI). See Dependencies and configuration in detail.

Note

In Spring documentation, factory bean refers to a bean that is configured in the Spring container
that will create objects through an instance or static factory method. By contrast, FactoryBean
(notice the capitalization) refers to a Spring-specific FactoryBean.

5.0.0.M1 Spring Framework 27


Spring Framework Reference Documentation

3.4 Dependencies
A typical enterprise application does not consist of a single object (or bean in the Spring parlance). Even
the simplest application has a few objects that work together to present what the end-user sees as a
coherent application. This next section explains how you go from defining a number of bean definitions
that stand alone to a fully realized application where objects collaborate to achieve a goal.

Dependency Injection

Dependency injection (DI) is a process whereby objects define their dependencies, that is, the other
objects they work with, only through constructor arguments, arguments to a factory method, or properties
that are set on the object instance after it is constructed or returned from a factory method. The container
then injects those dependencies when it creates the bean. This process is fundamentally the inverse,
hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of
its dependencies on its own by using direct construction of classes, or the Service Locator pattern.

Code is cleaner with the DI principle and decoupling is more effective when objects are provided with
their dependencies. The object does not look up its dependencies, and does not know the location
or class of the dependencies. As such, your classes become easier to test, in particular when the
dependencies are on interfaces or abstract base classes, which allow for stub or mock implementations
to be used in unit tests.

DI exists in two major variants, Constructor-based dependency injection and Setter-based dependency
injection.

Constructor-based dependency injection

Constructor-based DI is accomplished by the container invoking a constructor with a number of


arguments, each representing a dependency. Calling a static factory method with specific arguments
to construct the bean is nearly equivalent, and this discussion treats arguments to a constructor and to
a static factory method similarly. The following example shows a class that can only be dependency-
injected with constructor injection. Notice that there is nothing special about this class, it is a POJO that
has no dependencies on container specific interfaces, base classes or annotations.

public class SimpleMovieLister {

// the SimpleMovieLister has a dependency on a MovieFinder


private MovieFinder movieFinder;

// a constructor so that the Spring container can inject a MovieFinder


public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}

// business logic that actually uses the injected MovieFinder is omitted...

Constructor argument resolution

Constructor argument resolution matching occurs using the argument’s type. If no potential ambiguity
exists in the constructor arguments of a bean definition, then the order in which the constructor
arguments are defined in a bean definition is the order in which those arguments are supplied to the
appropriate constructor when the bean is being instantiated. Consider the following class:

5.0.0.M1 Spring Framework 28


Spring Framework Reference Documentation

package x.y;

public class Foo {

public Foo(Bar bar, Baz baz) {


// ...
}

No potential ambiguity exists, assuming that Bar and Baz classes are not related by inheritance. Thus
the following configuration works fine, and you do not need to specify the constructor argument indexes
and/or types explicitly in the <constructor-arg/> element.

<beans>
<bean id="foo" class="x.y.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
</bean>

<bean id="bar" class="x.y.Bar"/>

<bean id="baz" class="x.y.Baz"/>


</beans>

When another bean is referenced, the type is known, and matching can occur (as was the case with
the preceding example). When a simple type is used, such as <value>true</value>, Spring cannot
determine the type of the value, and so cannot match by type without help. Consider the following class:

package examples;

public class ExampleBean {

// Number of years to calculate the Ultimate Answer


private int years;

// The Answer to Life, the Universe, and Everything


private String ultimateAnswer;

public ExampleBean(int years, String ultimateAnswer) {


this.years = years;
this.ultimateAnswer = ultimateAnswer;
}

In the preceding scenario, the container can use type matching with simple types if you explicitly specify
the type of the constructor argument using the type attribute. For example:

<bean id="exampleBean" class="examples.ExampleBean">


<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>

Use the index attribute to specify explicitly the index of constructor arguments. For example:

<bean id="exampleBean" class="examples.ExampleBean">


<constructor-arg index="0" value="7500000"/>
<constructor-arg index="1" value="42"/>
</bean>

In addition to resolving the ambiguity of multiple simple values, specifying an index resolves ambiguity
where a constructor has two arguments of the same type. Note that the index is 0 based.

5.0.0.M1 Spring Framework 29


Spring Framework Reference Documentation

You can also use the constructor parameter name for value disambiguation:

<bean id="exampleBean" class="examples.ExampleBean">


<constructor-arg name="years" value="7500000"/>
<constructor-arg name="ultimateAnswer" value="42"/>
</bean>

Keep in mind that to make this work out of the box your code must be compiled with the debug flag
enabled so that Spring can look up the parameter name from the constructor. If you can’t compile your
code with debug flag (or don’t want to) you can use @ConstructorProperties JDK annotation to explicitly
name your constructor arguments. The sample class would then have to look as follows:

package examples;

public class ExampleBean {

// Fields omitted

@ConstructorProperties({"years", "ultimateAnswer"})
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}

Setter-based dependency injection

Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a
no-argument constructor or no-argument static factory method to instantiate your bean.

The following example shows a class that can only be dependency-injected using pure setter injection.
This class is conventional Java. It is a POJO that has no dependencies on container specific interfaces,
base classes or annotations.

public class SimpleMovieLister {

// the SimpleMovieLister has a dependency on the MovieFinder


private MovieFinder movieFinder;

// a setter method so that the Spring container can inject a MovieFinder


public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}

// business logic that actually uses the injected MovieFinder is omitted...

The ApplicationContext supports constructor-based and setter-based DI for the beans it manages.
It also supports setter-based DI after some dependencies have already been injected through the
constructor approach. You configure the dependencies in the form of a BeanDefinition, which
you use in conjunction with PropertyEditor instances to convert properties from one format to
another. However, most Spring users do not work with these classes directly (i.e., programmatically) but
rather with XML bean definitions, annotated components (i.e., classes annotated with @Component,
@Controller, etc.), or @Bean methods in Java-based @Configuration classes. These sources are
then converted internally into instances of BeanDefinition and used to load an entire Spring IoC
container instance.

5.0.0.M1 Spring Framework 30


Spring Framework Reference Documentation

Constructor-based or setter-based DI?

Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use
constructors for mandatory dependencies and setter methods or configuration methods for
optional dependencies. Note that use of the @Required annotation on a setter method can be
used to make the property a required dependency.

The Spring team generally advocates constructor injection as it enables one to implement
application components as immutable objects and to ensure that required dependencies are not
null. Furthermore constructor-injected components are always returned to client (calling) code
in a fully initialized state. As a side note, a large number of constructor arguments is a bad code
smell, implying that the class likely has too many responsibilities and should be refactored to better
address proper separation of concerns.

Setter injection should primarily only be used for optional dependencies that can be assigned
reasonable default values within the class. Otherwise, not-null checks must be performed
everywhere the code uses the dependency. One benefit of setter injection is that setter methods
make objects of that class amenable to reconfiguration or re-injection later. Management through
JMX MBeans is therefore a compelling use case for setter injection.

Use the DI style that makes the most sense for a particular class. Sometimes, when dealing with
third-party classes for which you do not have the source, the choice is made for you. For example,
if a third-party class does not expose any setter methods, then constructor injection may be the
only available form of DI.

Dependency resolution process

The container performs bean dependency resolution as follows:

• The ApplicationContext is created and initialized with configuration metadata that describes all
the beans. Configuration metadata can be specified via XML, Java code, or annotations.

• For each bean, its dependencies are expressed in the form of properties, constructor arguments, or
arguments to the static-factory method if you are using that instead of a normal constructor. These
dependencies are provided to the bean, when the bean is actually created.

• Each property or constructor argument is an actual definition of the value to set, or a reference to
another bean in the container.

• Each property or constructor argument which is a value is converted from its specified format to the
actual type of that property or constructor argument. By default Spring can convert a value supplied
in string format to all built-in types, such as int, long, String, boolean, etc.

The Spring container validates the configuration of each bean as the container is created. However,
the bean properties themselves are not set until the bean is actually created. Beans that are singleton-
scoped and set to be pre-instantiated (the default) are created when the container is created. Scopes
are defined in Section 3.5, “Bean scopes”. Otherwise, the bean is created only when it is requested.
Creation of a bean potentially causes a graph of beans to be created, as the bean’s dependencies and
its dependencies' dependencies (and so on) are created and assigned. Note that resolution mismatches
among those dependencies may show up late, i.e. on first creation of the affected bean.

5.0.0.M1 Spring Framework 31


Spring Framework Reference Documentation

Circular dependencies

If you use predominantly constructor injection, it is possible to create an unresolvable circular


dependency scenario.

For example: Class A requires an instance of class B through constructor injection, and class B
requires an instance of class A through constructor injection. If you configure beans for classes
A and B to be injected into each other, the Spring IoC container detects this circular reference at
runtime, and throws a BeanCurrentlyInCreationException.

One possible solution is to edit the source code of some classes to be configured by setters
rather than constructors. Alternatively, avoid constructor injection and use setter injection only. In
other words, although it is not recommended, you can configure circular dependencies with setter
injection.

Unlike the typical case (with no circular dependencies), a circular dependency between bean A
and bean B forces one of the beans to be injected into the other prior to being fully initialized itself
(a classic chicken/egg scenario).

You can generally trust Spring to do the right thing. It detects configuration problems, such as references
to non-existent beans and circular dependencies, at container load-time. Spring sets properties and
resolves dependencies as late as possible, when the bean is actually created. This means that a Spring
container which has loaded correctly can later generate an exception when you request an object if there
is a problem creating that object or one of its dependencies. For example, the bean throws an exception
as a result of a missing or invalid property. This potentially delayed visibility of some configuration issues
is why ApplicationContext implementations by default pre-instantiate singleton beans. At the cost
of some upfront time and memory to create these beans before they are actually needed, you discover
configuration issues when the ApplicationContext is created, not later. You can still override this
default behavior so that singleton beans will lazy-initialize, rather than be pre-instantiated.

If no circular dependencies exist, when one or more collaborating beans are being injected into a
dependent bean, each collaborating bean is totally configured prior to being injected into the dependent
bean. This means that if bean A has a dependency on bean B, the Spring IoC container completely
configures bean B prior to invoking the setter method on bean A. In other words, the bean is instantiated
(if not a pre-instantiated singleton), its dependencies are set, and the relevant lifecycle methods (such
as a configured init method or the InitializingBean callback method) are invoked.

Examples of dependency injection

The following example uses XML-based configuration metadata for setter-based DI. A small part of a
Spring XML configuration file specifies some bean definitions:

<bean id="exampleBean" class="examples.ExampleBean">


<!-- setter injection using the nested ref element -->
<property name="beanOne">
<ref bean="anotherExampleBean"/>
</property>

<!-- setter injection using the neater ref attribute -->


<property name="beanTwo" ref="yetAnotherBean"/>
<property name="integerProperty" value="1"/>
</bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/>


<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>

5.0.0.M1 Spring Framework 32


Spring Framework Reference Documentation

public class ExampleBean {

private AnotherBean beanOne;


private YetAnotherBean beanTwo;
private int i;

public void setBeanOne(AnotherBean beanOne) {


this.beanOne = beanOne;
}

public void setBeanTwo(YetAnotherBean beanTwo) {


this.beanTwo = beanTwo;
}

public void setIntegerProperty(int i) {


this.i = i;
}

In the preceding example, setters are declared to match against the properties specified in the XML file.
The following example uses constructor-based DI:

<bean id="exampleBean" class="examples.ExampleBean">


<!-- constructor injection using the nested ref element -->
<constructor-arg>
<ref bean="anotherExampleBean"/>
</constructor-arg>

<!-- constructor injection using the neater ref attribute -->


<constructor-arg ref="yetAnotherBean"/>

<constructor-arg type="int" value="1"/>


</bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/>


<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>

public class ExampleBean {

private AnotherBean beanOne;


private YetAnotherBean beanTwo;
private int i;

public ExampleBean(
AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {
this.beanOne = anotherBean;
this.beanTwo = yetAnotherBean;
this.i = i;
}

The constructor arguments specified in the bean definition will be used as arguments to the constructor
of the ExampleBean.

Now consider a variant of this example, where instead of using a constructor, Spring is told to call a
static factory method to return an instance of the object:

<bean id="exampleBean" class="examples.ExampleBean" factory-method="createInstance">


<constructor-arg ref="anotherExampleBean"/>
<constructor-arg ref="yetAnotherBean"/>
<constructor-arg value="1"/>
</bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/>


<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>

5.0.0.M1 Spring Framework 33


Spring Framework Reference Documentation

public class ExampleBean {

// a private constructor
private ExampleBean(...) {
...
}

// a static factory method; the arguments to this method can be


// considered the dependencies of the bean that is returned,
// regardless of how those arguments are actually used.
public static ExampleBean createInstance (
AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {

ExampleBean eb = new ExampleBean (...);


// some other operations...
return eb;
}

Arguments to the static factory method are supplied via <constructor-arg/> elements, exactly
the same as if a constructor had actually been used. The type of the class being returned by the factory
method does not have to be of the same type as the class that contains the static factory method,
although in this example it is. An instance (non-static) factory method would be used in an essentially
identical fashion (aside from the use of the factory-bean attribute instead of the class attribute),
so details will not be discussed here.

Dependencies and configuration in detail

As mentioned in the previous section, you can define bean properties and constructor arguments as
references to other managed beans (collaborators), or as values defined inline. Spring’s XML-based
configuration metadata supports sub-element types within its <property/> and <constructor-
arg/> elements for this purpose.

Straight values (primitives, Strings, and so on)

The value attribute of the <property/> element specifies a property or constructor argument as a
human-readable string representation. Spring’s conversion service is used to convert these values from
a String to the actual type of the property or argument.

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">


<!-- results in a setDriverClassName(String) call -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="masterkaoli"/>
</bean>

The following example uses the p-namespace for even more succinct XML configuration.

5.0.0.M1 Spring Framework 34


Spring Framework Reference Documentation

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"


destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/mydb"
p:username="root"
p:password="masterkaoli"/>

</beans>

The preceding XML is more succinct; however, typos are discovered at runtime rather than design time,
unless you use an IDE such as IntelliJ IDEA or the Spring Tool Suite (STS) that support automatic
property completion when you create bean definitions. Such IDE assistance is highly recommended.

You can also configure a java.util.Properties instance as:

<bean id="mappings"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<!-- typed as a java.util.Properties -->


<property name="properties">
<value>
jdbc.driver.className=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
</value>
</property>
</bean>

The Spring container converts the text inside the <value/> element into a java.util.Properties
instance by using the JavaBeans PropertyEditor mechanism. This is a nice shortcut, and is one of
a few places where the Spring team do favor the use of the nested <value/> element over the value
attribute style.

The idref element

The idref element is simply an error-proof way to pass the id (string value - not a reference) of another
bean in the container to a <constructor-arg/> or <property/> element.

<bean id="theTargetBean" class="..."/>

<bean id="theClientBean" class="...">


<property name="targetName">
<idref bean="theTargetBean" />
</property>
</bean>

The above bean definition snippet is exactly equivalent (at runtime) to the following snippet:

<bean id="theTargetBean" class="..." />

<bean id="client" class="...">


<property name="targetName" value="theTargetBean" />
</bean>

The first form is preferable to the second, because using the idref tag allows the container to validate at
deployment time that the referenced, named bean actually exists. In the second variation, no validation
is performed on the value that is passed to the targetName property of the client bean. Typos are
only discovered (with most likely fatal results) when the client bean is actually instantiated. If the

5.0.0.M1 Spring Framework 35


Spring Framework Reference Documentation

client bean is a prototype bean, this typo and the resulting exception may only be discovered long
after the container is deployed.

Note

The local attribute on the idref element is no longer supported in the 4.0 beans xsd since
it does not provide value over a regular bean reference anymore. Simply change your existing
idref local references to idref bean when upgrading to the 4.0 schema.

A common place (at least in versions earlier than Spring 2.0) where the <idref/> element brings value
is in the configuration of AOP interceptors in a ProxyFactoryBean bean definition. Using <idref/>
elements when you specify the interceptor names prevents you from misspelling an interceptor id.

References to other beans (collaborators)

The ref element is the final element inside a <constructor-arg/> or <property/> definition
element. Here you set the value of the specified property of a bean to be a reference to another
bean (a collaborator) managed by the container. The referenced bean is a dependency of the bean
whose property will be set, and it is initialized on demand as needed before the property is set. (If
the collaborator is a singleton bean, it may be initialized already by the container.) All references are
ultimately a reference to another object. Scoping and validation depend on whether you specify the id/
name of the other object through the bean, local, or parent attributes.

Specifying the target bean through the bean attribute of the <ref/> tag is the most general form, and
allows creation of a reference to any bean in the same container or parent container, regardless of
whether it is in the same XML file. The value of the bean attribute may be the same as the id attribute
of the target bean, or as one of the values in the name attribute of the target bean.

<ref bean="someBean"/>

Specifying the target bean through the parent attribute creates a reference to a bean that is in a parent
container of the current container. The value of the parent attribute may be the same as either the id
attribute of the target bean, or one of the values in the name attribute of the target bean, and the target
bean must be in a parent container of the current one. You use this bean reference variant mainly when
you have a hierarchy of containers and you want to wrap an existing bean in a parent container with a
proxy that will have the same name as the parent bean.

<!-- in the parent context -->


<bean id="accountService" class="com.foo.SimpleAccountService">
<!-- insert dependencies as required as here -->
</bean>

<!-- in the child (descendant) context -->


<bean id="accountService" <!-- bean name is the same as the parent bean -->
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref parent="accountService"/> <!-- notice how we refer to the parent bean -->
</property>
<!-- insert other configuration and dependencies as required here -->
</bean>

Note

The local attribute on the ref element is no longer supported in the 4.0 beans xsd since it
does not provide value over a regular bean reference anymore. Simply change your existing ref
local references to ref bean when upgrading to the 4.0 schema.

5.0.0.M1 Spring Framework 36


Spring Framework Reference Documentation

Inner beans

A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called


inner bean.

<bean id="outer" class="...">


<!-- instead of using a reference to a target bean, simply define the target bean inline -->
<property name="target">
<bean class="com.example.Person"> <!-- this is the inner bean -->
<property name="name" value="Fiona Apple"/>
<property name="age" value="25"/>
</bean>
</property>
</bean>

An inner bean definition does not require a defined id or name; if specified, the container does not use
such a value as an identifier. The container also ignores the scope flag on creation: Inner beans are
always anonymous and they are always created with the outer bean. It is not possible to inject inner
beans into collaborating beans other than into the enclosing bean or to access them independently.

As a corner case, it is possible to receive destruction callbacks from a custom scope, e.g. for a request-
scoped inner bean contained within a singleton bean: The creation of the inner bean instance will be tied
to its containing bean, but destruction callbacks allow it to participate in the request scope’s lifecycle.
This is not a common scenario; inner beans typically simply share their containing bean’s scope.

Collections

In the <list/>, <set/>, <map/>, and <props/> elements, you set the properties and arguments of
the Java Collection types List, Set, Map, and Properties, respectively.

<bean id="moreComplexObject" class="example.ComplexObject">


<!-- results in a setAdminEmails(java.util.Properties) call -->
<property name="adminEmails">
<props>
<prop key="administrator">[email protected]</prop>
<prop key="support">[email protected]</prop>
<prop key="development">[email protected]</prop>
</props>
</property>
<!-- results in a setSomeList(java.util.List) call -->
<property name="someList">
<list>
<value>a list element followed by a reference</value>
<ref bean="myDataSource" />
</list>
</property>
<!-- results in a setSomeMap(java.util.Map) call -->
<property name="someMap">
<map>
<entry key="an entry" value="just some string"/>
<entry key ="a ref" value-ref="myDataSource"/>
</map>
</property>
<!-- results in a setSomeSet(java.util.Set) call -->
<property name="someSet">
<set>
<value>just some string</value>
<ref bean="myDataSource" />
</set>
</property>
</bean>

The value of a map key or value, or a set value, can also again be any of the following elements:

5.0.0.M1 Spring Framework 37


Spring Framework Reference Documentation

bean | ref | idref | list | set | map | props | value | null

Collection merging

The Spring container also supports the merging of collections. An application developer can define a
parent-style <list/>, <map/>, <set/> or <props/> element, and have child-style <list/>, <map/
>, <set/> or <props/> elements inherit and override values from the parent collection. That is, the
child collection’s values are the result of merging the elements of the parent and child collections, with
the child’s collection elements overriding values specified in the parent collection.

This section on merging discusses the parent-child bean mechanism. Readers unfamiliar with parent
and child bean definitions may wish to read the relevant section before continuing.

The following example demonstrates collection merging:

<beans>
<bean id="parent" abstract="true" class="example.ComplexObject">
<property name="adminEmails">
<props>
<prop key="administrator">[email protected]</prop>
<prop key="support">[email protected]</prop>
</props>
</property>
</bean>
<bean id="child" parent="parent">
<property name="adminEmails">
<!-- the merge is specified on the child collection definition -->
<props merge="true">
<prop key="sales">[email protected]</prop>
<prop key="support">[email protected]</prop>
</props>
</property>
</bean>
<beans>

Notice the use of the merge=true attribute on the <props/> element of the adminEmails property
of the child bean definition. When the child bean is resolved and instantiated by the container, the
resulting instance has an adminEmails Properties collection that contains the result of the merging
of the child’s adminEmails collection with the parent’s adminEmails collection.

[email protected]
[email protected]
[email protected]

The child Properties collection’s value set inherits all property elements from the parent <props/>,
and the child’s value for the support value overrides the value in the parent collection.

This merging behavior applies similarly to the <list/>, <map/>, and <set/> collection types. In the
specific case of the <list/> element, the semantics associated with the List collection type, that is,
the notion of an ordered collection of values, is maintained; the parent’s values precede all of the child
list’s values. In the case of the Map, Set, and Properties collection types, no ordering exists. Hence
no ordering semantics are in effect for the collection types that underlie the associated Map, Set, and
Properties implementation types that the container uses internally.

Limitations of collection merging

You cannot merge different collection types (such as a Map and a List), and if you do attempt to do
so an appropriate Exception is thrown. The merge attribute must be specified on the lower, inherited,

5.0.0.M1 Spring Framework 38


Spring Framework Reference Documentation

child definition; specifying the merge attribute on a parent collection definition is redundant and will not
result in the desired merging.

Strongly-typed collection

With the introduction of generic types in Java 5, you can use strongly typed collections. That is, it is
possible to declare a Collection type such that it can only contain String elements (for example).
If you are using Spring to dependency-inject a strongly-typed Collection into a bean, you can
take advantage of Spring’s type-conversion support such that the elements of your strongly-typed
Collection instances are converted to the appropriate type prior to being added to the Collection.

public class Foo {

private Map<String, Float> accounts;

public void setAccounts(Map<String, Float> accounts) {


this.accounts = accounts;
}
}

<beans>
<bean id="foo" class="x.y.Foo">
<property name="accounts">
<map>
<entry key="one" value="9.99"/>
<entry key="two" value="2.75"/>
<entry key="six" value="3.99"/>
</map>
</property>
</bean>
</beans>

When the accounts property of the foo bean is prepared for injection, the generics information about
the element type of the strongly-typed Map<String, Float> is available by reflection. Thus Spring’s
type conversion infrastructure recognizes the various value elements as being of type Float, and the
string values 9.99, 2.75, and 3.99 are converted into an actual Float type.

Null and empty string values

Spring treats empty arguments for properties and the like as empty Strings. The following XML-based
configuration metadata snippet sets the email property to the empty String value ("").

<bean class="ExampleBean">
<property name="email" value=""/>
</bean>

The preceding example is equivalent to the following Java code:

exampleBean.setEmail("")

The <null/> element handles null values. For example:

<bean class="ExampleBean">
<property name="email">
<null/>
</property>
</bean>

The above configuration is equivalent to the following Java code:

exampleBean.setEmail(null)

5.0.0.M1 Spring Framework 39


Spring Framework Reference Documentation

XML shortcut with the p-namespace

The p-namespace enables you to use the bean element’s attributes, instead of nested <property/>
elements, to describe your property values and/or collaborating beans.

Spring supports extensible configuration formats with namespaces, which are based on an XML Schema
definition. The beans configuration format discussed in this chapter is defined in an XML Schema
document. However, the p-namespace is not defined in an XSD file and exists only in the core of Spring.

The following example shows two XML snippets that resolve to the same result: The first uses standard
XML format and the second uses the p-namespace.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean name="classic" class="com.example.ExampleBean">


<property name="email" value="[email protected]"/>
</bean>

<bean name="p-namespace" class="com.example.ExampleBean"


p:email="[email protected]"/>
</beans>

The example shows an attribute in the p-namespace called email in the bean definition. This tells Spring
to include a property declaration. As previously mentioned, the p-namespace does not have a schema
definition, so you can set the name of the attribute to the property name.

This next example includes two more bean definitions that both have a reference to another bean:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean name="john-classic" class="com.example.Person">


<property name="name" value="John Doe"/>
<property name="spouse" ref="jane"/>
</bean>

<bean name="john-modern"
class="com.example.Person"
p:name="John Doe"
p:spouse-ref="jane"/>

<bean name="jane" class="com.example.Person">


<property name="name" value="Jane Doe"/>
</bean>
</beans>

As you can see, this example includes not only a property value using the p-namespace, but also uses
a special format to declare property references. Whereas the first bean definition uses <property
name="spouse" ref="jane"/> to create a reference from bean john to bean jane, the second
bean definition uses p:spouse-ref="jane" as an attribute to do the exact same thing. In this case
spouse is the property name, whereas the -ref part indicates that this is not a straight value but rather
a reference to another bean.

5.0.0.M1 Spring Framework 40


Spring Framework Reference Documentation

Note

The p-namespace is not as flexible as the standard XML format. For example, the format for
declaring property references clashes with properties that end in Ref, whereas the standard XML
format does not. We recommend that you choose your approach carefully and communicate this
to your team members, to avoid producing XML documents that use all three approaches at the
same time.

XML shortcut with the c-namespace

Similar to the the section called “XML shortcut with the p-namespace”, the c-namespace, newly
introduced in Spring 3.1, allows usage of inlined attributes for configuring the constructor arguments
rather then nested constructor-arg elements.

Let’s review the examples from the section called “Constructor-based dependency injection” with the
c: namespace:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="bar" class="x.y.Bar"/>


<bean id="baz" class="x.y.Baz"/>

<!-- traditional declaration -->


<bean id="foo" class="x.y.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
<constructor-arg value="[email protected]"/>
</bean>

<!-- c-namespace declaration -->


<bean id="foo" class="x.y.Foo" c:bar-ref="bar" c:baz-ref="baz" c:email="[email protected]"/>

</beans>

The c: namespace uses the same conventions as the p: one (trailing -ref for bean references) for
setting the constructor arguments by their names. And just as well, it needs to be declared even though
it is not defined in an XSD schema (but it exists inside the Spring core).

For the rare cases where the constructor argument names are not available (usually if the bytecode was
compiled without debugging information), one can use fallback to the argument indexes:

<!-- c-namespace index declaration -->


<bean id="foo" class="x.y.Foo" c:_0-ref="bar" c:_1-ref="baz"/>

Note

Due to the XML grammar, the index notation requires the presence of the leading _ as XML
attribute names cannot start with a number (even though some IDE allow it).

In practice, the constructor resolution mechanism is quite efficient in matching arguments so unless one
really needs to, we recommend using the name notation through-out your configuration.

5.0.0.M1 Spring Framework 41


Spring Framework Reference Documentation

Compound property names

You can use compound or nested property names when you set bean properties, as long as all
components of the path except the final property name are not null. Consider the following bean
definition.

<bean id="foo" class="foo.Bar">


<property name="fred.bob.sammy" value="123" />
</bean>

The foo bean has a fred property, which has a bob property, which has a sammy property, and that final
sammy property is being set to the value 123. In order for this to work, the fred property of foo, and the
bob property of fred must not be null after the bean is constructed, or a NullPointerException
is thrown.

Using depends-on

If a bean is a dependency of another that usually means that one bean is set as a property of another.
Typically you accomplish this with the <ref/> element in XML-based configuration metadata. However,
sometimes dependencies between beans are less direct; for example, a static initializer in a class needs
to be triggered, such as database driver registration. The depends-on attribute can explicitly force one
or more beans to be initialized before the bean using this element is initialized. The following example
uses the depends-on attribute to express a dependency on a single bean:

<bean id="beanOne" class="ExampleBean" depends-on="manager"/>


<bean id="manager" class="ManagerBean" />

To express a dependency on multiple beans, supply a list of bean names as the value of the depends-
on attribute, with commas, whitespace and semicolons, used as valid delimiters:

<bean id="beanOne" class="ExampleBean" depends-on="manager,accountDao">


<property name="manager" ref="manager" />
</bean>

<bean id="manager" class="ManagerBean" />


<bean id="accountDao" class="x.y.jdbc.JdbcAccountDao" />

Note

The depends-on attribute in the bean definition can specify both an initialization time dependency
and, in the case of singleton beans only, a corresponding destroy time dependency. Dependent
beans that define a depends-on relationship with a given bean are destroyed first, prior to the
given bean itself being destroyed. Thus depends-on can also control shutdown order.

Lazy-initialized beans

By default, ApplicationContext implementations eagerly create and configure all singleton beans
as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the
configuration or surrounding environment are discovered immediately, as opposed to hours or even
days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by
marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a
bean instance when it is first requested, rather than at startup.

In XML, this behavior is controlled by the lazy-init attribute on the <bean/> element; for example:

5.0.0.M1 Spring Framework 42


Spring Framework Reference Documentation

<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>


<bean name="not.lazy" class="com.foo.AnotherBean"/>

When the preceding configuration is consumed by an ApplicationContext, the bean named lazy
is not eagerly pre-instantiated when the ApplicationContext is starting up, whereas the not.lazy
bean is eagerly pre-instantiated.

However, when a lazy-initialized bean is a dependency of a singleton bean that is not lazy-initialized,
the ApplicationContext creates the lazy-initialized bean at startup, because it must satisfy the
singleton’s dependencies. The lazy-initialized bean is injected into a singleton bean elsewhere that is
not lazy-initialized.

You can also control lazy-initialization at the container level by using the default-lazy-init attribute
on the <beans/> element; for example:

<beans default-lazy-init="true">
<!-- no beans will be pre-instantiated... -->
</beans>

Autowiring collaborators

The Spring container can autowire relationships between collaborating beans. You can allow Spring
to resolve collaborators (other beans) automatically for your bean by inspecting the contents of the
ApplicationContext. Autowiring has the following advantages:

• Autowiring can significantly reduce the need to specify properties or constructor arguments. (Other
mechanisms such as a bean template discussed elsewhere in this chapter are also valuable in this
regard.)

• Autowiring can update a configuration as your objects evolve. For example, if you need to add a
dependency to a class, that dependency can be satisfied automatically without you needing to modify
the configuration. Thus autowiring can be especially useful during development, without negating the
option of switching to explicit wiring when the code base becomes more stable.
10
When using XML-based configuration metadata , you specify autowire mode for a bean definition
with the autowire attribute of the <bean/> element. The autowiring functionality has four modes. You
specify autowiring per bean and thus can choose which ones to autowire.

Table 3.2. Autowiring modes

Mode Explanation

no (Default) No autowiring. Bean references must


be defined via a ref element. Changing the
default setting is not recommended for larger
deployments, because specifying collaborators
explicitly gives greater control and clarity. To
some extent, it documents the structure of a
system.

byName Autowiring by property name. Spring looks for


a bean with the same name as the property

10
See the section called “Dependency Injection”

5.0.0.M1 Spring Framework 43


Spring Framework Reference Documentation

Mode Explanation
that needs to be autowired. For example, if a
bean definition is set to autowire by name, and
it contains a master property (that is, it has a
setMaster(..) method), Spring looks for a bean
definition named master, and uses it to set the
property.

byType Allows a property to be autowired if exactly one


bean of the property type exists in the container.
If more than one exists, a fatal exception is
thrown, which indicates that you may not use
byType autowiring for that bean. If there are no
matching beans, nothing happens; the property
is not set.

constructor Analogous to byType, but applies to constructor


arguments. If there is not exactly one bean of
the constructor argument type in the container, a
fatal error is raised.

With byType or constructor autowiring mode, you can wire arrays and typed-collections. In such cases
all autowire candidates within the container that match the expected type are provided to satisfy the
dependency. You can autowire strongly-typed Maps if the expected key type is String. An autowired
Maps values will consist of all bean instances that match the expected type, and the Maps keys will
contain the corresponding bean names.

You can combine autowire behavior with dependency checking, which is performed after autowiring
completes.

Limitations and disadvantages of autowiring

Autowiring works best when it is used consistently across a project. If autowiring is not used in general,
it might be confusing to developers to use it to wire only one or two bean definitions.

Consider the limitations and disadvantages of autowiring:

• Explicit dependencies in property and constructor-arg settings always override autowiring.


You cannot autowire so-called simple properties such as primitives, Strings, and Classes (and
arrays of such simple properties). This limitation is by-design.

• Autowiring is less exact than explicit wiring. Although, as noted in the above table, Spring is careful
to avoid guessing in case of ambiguity that might have unexpected results, the relationships between
your Spring-managed objects are no longer documented explicitly.

• Wiring information may not be available to tools that may generate documentation from a Spring
container.

• Multiple bean definitions within the container may match the type specified by the setter method
or constructor argument to be autowired. For arrays, collections, or Maps, this is not necessarily
a problem. However for dependencies that expect a single value, this ambiguity is not arbitrarily
resolved. If no unique bean definition is available, an exception is thrown.

5.0.0.M1 Spring Framework 44


Spring Framework Reference Documentation

In the latter scenario, you have several options:

• Abandon autowiring in favor of explicit wiring.

• Avoid autowiring for a bean definition by setting its autowire-candidate attributes to false as
described in the next section.

• Designate a single bean definition as the primary candidate by setting the primary attribute of its
<bean/> element to true.

• Implement the more fine-grained control available with annotation-based configuration, as described
in Section 3.9, “Annotation-based container configuration”.

Excluding a bean from autowiring

On a per-bean basis, you can exclude a bean from autowiring. In Spring’s XML format, set the
autowire-candidate attribute of the <bean/> element to false; the container makes that specific
bean definition unavailable to the autowiring infrastructure (including annotation style configurations
such as @Autowired).

You can also limit autowire candidates based on pattern-matching against bean names. The top-
level <beans/> element accepts one or more patterns within its default-autowire-candidates
attribute. For example, to limit autowire candidate status to any bean whose name ends with Repository,
provide a value of *Repository. To provide multiple patterns, define them in a comma-separated list. An
explicit value of true or false for a bean definitions autowire-candidate attribute always takes
precedence, and for such beans, the pattern matching rules do not apply.

These techniques are useful for beans that you never want to be injected into other beans by autowiring.
It does not mean that an excluded bean cannot itself be configured using autowiring. Rather, the bean
itself is not a candidate for autowiring other beans.

Method injection

In most application scenarios, most beans in the container are singletons. When a singleton bean needs
to collaborate with another singleton bean, or a non-singleton bean needs to collaborate with another
non-singleton bean, you typically handle the dependency by defining one bean as a property of the
other. A problem arises when the bean lifecycles are different. Suppose singleton bean A needs to use
non-singleton (prototype) bean B, perhaps on each method invocation on A. The container only creates
the singleton bean A once, and thus only gets one opportunity to set the properties. The container cannot
provide bean A with a new instance of bean B every time one is needed.

A solution is to forego some inversion of control. You can make bean A aware of the container by
implementing the ApplicationContextAware interface, and by making a getBean("B") call to the
container ask for (a typically new) bean B instance every time bean A needs it. The following is an
example of this approach:

5.0.0.M1 Spring Framework 45


Spring Framework Reference Documentation

// a class that uses a stateful Command-style class to perform some processing


package fiona.apple;

// Spring-API imports
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class CommandManager implements ApplicationContextAware {

private ApplicationContext applicationContext;

public Object process(Map commandState) {


// grab a new instance of the appropriate Command
Command command = createCommand();
// set the state on the (hopefully brand new) Command instance
command.setState(commandState);
return command.execute();
}

protected Command createCommand() {


// notice the Spring API dependency!
return this.applicationContext.getBean("command", Command.class);
}

public void setApplicationContext(


ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}

The preceding is not desirable, because the business code is aware of and coupled to the Spring
Framework. Method Injection, a somewhat advanced feature of the Spring IoC container, allows this
use case to be handled in a clean fashion.

You can read more about the motivation for Method Injection in this blog entry.

Lookup method injection

Lookup method injection is the ability of the container to override methods on container managed beans,
to return the lookup result for another named bean in the container. The lookup typically involves a
prototype bean as in the scenario described in the preceding section. The Spring Framework implements
this method injection by using bytecode generation from the CGLIB library to generate dynamically a
subclass that overrides the method.

Note

• For this dynamic subclassing to work, the class that the Spring bean container will subclass
cannot be final, and the method to be overridden cannot be final either.

• Unit-testing a class that has an abstract method requires you to subclass the class yourself
and to supply a stub implementation of the abstract method.

• Concrete methods are also necessary for component scanning which requires concrete classes
to pick up.

• A further key limitation is that lookup methods won’t work with factory methods and in particular
not with @Bean methods in configuration classes, since the container is not in charge of creating
the instance in that case and therefore cannot create a runtime-generated subclass on the fly.

5.0.0.M1 Spring Framework 46


Spring Framework Reference Documentation

• Finally, objects that have been the target of method injection cannot be serialized.

Looking at the CommandManager class in the previous code snippet, you see that the Spring
container will dynamically override the implementation of the createCommand() method. Your
CommandManager class will not have any Spring dependencies, as can be seen in the reworked
example:

package fiona.apple;

// no more Spring imports!

public abstract class CommandManager {

public Object process(Object commandState) {


// grab a new instance of the appropriate Command interface
Command command = createCommand();
// set the state on the (hopefully brand new) Command instance
command.setState(commandState);
return command.execute();
}

// okay... but where is the implementation of this method?


protected abstract Command createCommand();
}

In the client class containing the method to be injected (the CommandManager in this case), the method
to be injected requires a signature of the following form:

<public|protected> [abstract] <return-type> theMethodName(no-arguments);

If the method is abstract, the dynamically-generated subclass implements the method. Otherwise,
the dynamically-generated subclass overrides the concrete method defined in the original class. For
example:

<!-- a stateful bean deployed as a prototype (non-singleton) -->


<bean id="command" class="fiona.apple.AsyncCommand" scope="prototype">
<!-- inject dependencies here as required -->
</bean>

<!-- commandProcessor uses statefulCommandHelper -->


<bean id="commandManager" class="fiona.apple.CommandManager">
<lookup-method name="createCommand" bean="command"/>
</bean>

The bean identified as commandManager calls its own method createCommand() whenever it needs
a new instance of the command bean. You must be careful to deploy the command bean as a prototype,
if that is actually what is needed. If it is deployed as a singleton, the same instance of the command
bean is returned each time.

Tip

The interested reader may also find the ServiceLocatorFactoryBean (in the
org.springframework.beans.factory.config package) to be of use. The approach
used in ServiceLocatorFactoryBean is similar to that of another utility class,
ObjectFactoryCreatingFactoryBean, but it allows you to specify your own lookup interface
as opposed to a Spring-specific lookup interface. Consult the javadocs of these classes for
additional information.

5.0.0.M1 Spring Framework 47


Spring Framework Reference Documentation

Arbitrary method replacement

A less useful form of method injection than lookup method injection is the ability to replace arbitrary
methods in a managed bean with another method implementation. Users may safely skip the rest of
this section until the functionality is actually needed.

With XML-based configuration metadata, you can use the replaced-method element to replace an
existing method implementation with another, for a deployed bean. Consider the following class, with
a method computeValue, which we want to override:

public class MyValueCalculator {

public String computeValue(String input) {


// some real code...
}

// some other methods...

A class implementing the org.springframework.beans.factory.support.MethodReplacer


interface provides the new method definition.

/**
* meant to be used to override the existing computeValue(String)
* implementation in MyValueCalculator
*/
public class ReplacementComputeValue implements MethodReplacer {

public Object reimplement(Object o, Method m, Object[] args) throws Throwable {


// get the input value, work with it, and return a computed result
String input = (String) args[0];
...
return ...;
}
}

The bean definition to deploy the original class and specify the method override would look like this:

<bean id="myValueCalculator" class="x.y.z.MyValueCalculator">


<!-- arbitrary method replacement -->
<replaced-method name="computeValue" replacer="replacementComputeValue">
<arg-type>String</arg-type>
</replaced-method>
</bean>

<bean id="replacementComputeValue" class="a.b.c.ReplacementComputeValue"/>

You can use one or more contained <arg-type/> elements within the <replaced-method/>
element to indicate the method signature of the method being overridden. The signature for the
arguments is necessary only if the method is overloaded and multiple variants exist within the class.
For convenience, the type string for an argument may be a substring of the fully qualified type name.
For example, the following all match java.lang.String:

java.lang.String
String
Str

Because the number of arguments is often enough to distinguish between each possible choice, this
shortcut can save a lot of typing, by allowing you to type only the shortest string that will match an
argument type.

5.0.0.M1 Spring Framework 48


Spring Framework Reference Documentation

3.5 Bean scopes


When you create a bean definition, you create a recipe for creating actual instances of the class defined
by that bean definition. The idea that a bean definition is a recipe is important, because it means that,
as with a class, you can create many object instances from a single recipe.

You can control not only the various dependencies and configuration values that are to be plugged into
an object that is created from a particular bean definition, but also the scope of the objects created from
a particular bean definition. This approach is powerful and flexible in that you can choose the scope
of the objects you create through configuration instead of having to bake in the scope of an object at
the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of the
box, the Spring Framework supports six scopes, five of which are available only if you use a web-aware
ApplicationContext.

The following scopes are supported out of the box. You can also create a custom scope.

Table 3.3. Bean scopes

Scope Description

singleton (Default) Scopes a single bean definition to a


single object instance per Spring IoC container.

prototype Scopes a single bean definition to any number of


object instances.

request Scopes a single bean definition to the lifecycle


of a single HTTP request; that is, each HTTP
request has its own instance of a bean created
off the back of a single bean definition. Only
valid in the context of a web-aware Spring
ApplicationContext.

session Scopes a single bean definition to the lifecycle of


an HTTP Session. Only valid in the context of a
web-aware Spring ApplicationContext.

application Scopes a single bean definition to the lifecycle of


a ServletContext. Only valid in the context of
a web-aware Spring ApplicationContext.

websocket Scopes a single bean definition to the lifecycle


of a WebSocket. Only valid in the context of a
web-aware Spring ApplicationContext.

Note

As of Spring 3.0, a thread scope is available, but is not registered by default. For more information,
see the documentation for SimpleThreadScope. For instructions on how to register this or any
other custom scope, see the section called “Using a custom scope”.

5.0.0.M1 Spring Framework 49


Spring Framework Reference Documentation

The singleton scope

Only one shared instance of a singleton bean is managed, and all requests for beans with an id or
ids matching that bean definition result in that one specific bean instance being returned by the Spring
container.

To put it another way, when you define a bean definition and it is scoped as a singleton, the Spring IoC
container creates exactly one instance of the object defined by that bean definition. This single instance
is stored in a cache of such singleton beans, and all subsequent requests and references for that named
bean return the cached object.

Spring’s concept of a singleton bean differs from the Singleton pattern as defined in the Gang of Four
(GoF) patterns book. The GoF Singleton hard-codes the scope of an object such that one and only
one instance of a particular class is created per ClassLoader. The scope of the Spring singleton is best
described as per container and per bean. This means that if you define one bean for a particular class
in a single Spring container, then the Spring container creates one and only one instance of the class
defined by that bean definition. The singleton scope is the default scope in Spring. To define a bean as
a singleton in XML, you would write, for example:

<bean id="accountService" class="com.foo.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>

The prototype scope

The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance
every time a request for that specific bean is made. That is, the bean is injected into another bean or
you request it through a getBean() method call on the container. As a rule, use the prototype scope
for all stateful beans and the singleton scope for stateless beans.

The following diagram illustrates the Spring prototype scope. A data access object (DAO) is not typically
configured as a prototype, because a typical DAO does not hold any conversational state; it was just
easier for this author to reuse the core of the singleton diagram.

5.0.0.M1 Spring Framework 50


Spring Framework Reference Documentation

The following example defines a bean as a prototype in XML:

<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>

In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the
container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client,
with no further record of that prototype instance. Thus, although initialization lifecycle callback methods
are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle
callbacks are not called. The client code must clean up prototype-scoped objects and release expensive
resources that the prototype bean(s) are holding. To get the Spring container to release resources held
by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans
that need to be cleaned up.

In some respects, the Spring container’s role in regard to a prototype-scoped bean is a replacement
for the Java new operator. All lifecycle management past that point must be handled by the client. (For
details on the lifecycle of a bean in the Spring container, see the section called “Lifecycle callbacks”.)

Singleton beans with prototype-bean dependencies

When you use singleton-scoped beans with dependencies on prototype beans, be aware that
dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean
into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into
the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-
scoped bean.

However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-
scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your
singleton bean, because that injection occurs only once, when the Spring container is instantiating the
singleton bean and resolving and injecting its dependencies. If you need a new instance of a prototype
bean at runtime more than once, see the section called “Method injection”

Request, session, application, and WebSocket scopes

The request, session, application, and websocket scopes are only available
if you use a web-aware Spring ApplicationContext implementation (such as
XmlWebApplicationContext). If you use these scopes with regular Spring IoC containers

5.0.0.M1 Spring Framework 51


Spring Framework Reference Documentation

such as the ClassPathXmlApplicationContext, an IllegalStateException will be thrown


complaining about an unknown bean scope.

Initial web configuration

To support the scoping of beans at the request, session, application, and websocket levels
(web-scoped beans), some minor initial configuration is required before you define your beans. (This
initial setup is not required for the standard scopes, singleton and prototype.)

How you accomplish this initial setup depends on your particular Servlet environment.

If you access scoped beans within Spring Web MVC, in effect, within a request that is processed by
the Spring DispatcherServlet, then no special setup is necessary: DispatcherServlet already
exposes all relevant state.

If you use a Servlet 2.5 web container, with requests processed outside of
Spring’s DispatcherServlet (for example, when using JSF or Struts), you need
to register the org.springframework.web.context.request.RequestContextListener
ServletRequestListener. For Servlet 3.0+, this can be done programmatically via the
WebApplicationInitializer interface. Alternatively, or for older containers, add the following
declaration to your web application’s web.xml file:

<web-app>
...
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
...
</web-app>

Alternatively, if there are issues with your listener setup, consider using Spring’s
RequestContextFilter. The filter mapping depends on the surrounding web application
configuration, so you have to change it as appropriate.

<web-app>
...
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>

DispatcherServlet, RequestContextListener, and RequestContextFilter all do exactly


the same thing, namely bind the HTTP request object to the Thread that is servicing that request. This
makes beans that are request- and session-scoped available further down the call chain.

Request scope

Consider the following XML configuration for a bean definition:

<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>

5.0.0.M1 Spring Framework 52


Spring Framework Reference Documentation

The Spring container creates a new instance of the LoginAction bean by using the loginAction
bean definition for each and every HTTP request. That is, the loginAction bean is scoped at the
HTTP request level. You can change the internal state of the instance that is created as much as you
want, because other instances created from the same loginAction bean definition will not see these
changes in state; they are particular to an individual request. When the request completes processing,
the bean that is scoped to the request is discarded.

When using annotation-driven components or Java Config, the @RequestScope annotation can be
used to assign a component to the request scope.

@RequestScope
@Component
public class LoginAction {
// ...
}

Session scope

Consider the following XML configuration for a bean definition:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

The Spring container creates a new instance of the UserPreferences bean by using the
userPreferences bean definition for the lifetime of a single HTTP Session. In other words, the
userPreferences bean is effectively scoped at the HTTP Session level. As with request-scoped
beans, you can change the internal state of the instance that is created as much as you want,
knowing that other HTTP Session instances that are also using instances created from the same
userPreferences bean definition do not see these changes in state, because they are particular to an
individual HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped
to that particular HTTP Session is also discarded.

When using annotation-driven components or Java Config, the @SessionScope annotation can be
used to assign a component to the session scope.

@SessionScope
@Component
public class UserPreferences {
// ...
}

Application scope

Consider the following XML configuration for a bean definition:

<bean id="appPreferences" class="com.foo.AppPreferences" scope="application"/>

The Spring container creates a new instance of the AppPreferences bean by using the
appPreferences bean definition once for the entire web application. That is, the appPreferences
bean is scoped at the ServletContext level, stored as a regular ServletContext attribute. This
is somewhat similar to a Spring singleton bean but differs in two important ways: It is a singleton per
ServletContext, not per Spring 'ApplicationContext' (for which there may be several in any given
web application), and it is actually exposed and therefore visible as a ServletContext attribute.

When using annotation-driven components or Java Config, the @ApplicationScope annotation can
be used to assign a component to the application scope.

5.0.0.M1 Spring Framework 53


Spring Framework Reference Documentation

@ApplicationScope
@Component
public class AppPreferences {
// ...
}

Scoped beans as dependencies

The Spring IoC container manages not only the instantiation of your objects (beans), but also the wiring
up of collaborators (or dependencies). If you want to inject (for example) an HTTP request scoped bean
into another bean of a longer-lived scope, you may choose to inject an AOP proxy in place of the scoped
bean. That is, you need to inject a proxy object that exposes the same public interface as the scoped
object but that can also retrieve the real target object from the relevant scope (such as an HTTP request)
and delegate method calls onto the real object.

Note

You may also use <aop:scoped-proxy/> between beans that are scoped as singleton, with
the reference then going through an intermediate proxy that is serializable and therefore able to
re-obtain the target singleton bean on deserialization.

When declaring <aop:scoped-proxy/> against a bean of scope prototype, every method


call on the shared proxy will lead to the creation of a new target instance which the call is then
being forwarded to.

Also, scoped proxies are not the only way to access beans from shorter scopes in a lifecycle-safe
fashion. You may also simply declare your injection point (i.e. the constructor/setter argument
or autowired field) as ObjectFactory<MyTargetBean>, allowing for a getObject() call to
retrieve the current instance on demand every time it is needed - without holding on to the instance
or storing it separately.

The JSR-330 variant of this is called Provider, used with a Provider<MyTargetBean>


declaration and a corresponding get() call for every retrieval attempt. See here for more details
on JSR-330 overall.

The configuration in the following example is only one line, but it is important to understand the "why"
as well as the "how" behind it.

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- an HTTP Session-scoped bean exposed as a proxy -->


<bean id="userPreferences" class="com.foo.UserPreferences" scope="session">
<!-- instructs the container to proxy the surrounding bean -->
<aop:scoped-proxy/>
</bean>

<!-- a singleton-scoped bean injected with a proxy to the above bean -->
<bean id="userService" class="com.foo.SimpleUserService">
<!-- a reference to the proxied userPreferences bean -->
<property name="userPreferences" ref="userPreferences"/>
</bean>
</beans>

5.0.0.M1 Spring Framework 54


Spring Framework Reference Documentation

To create such a proxy, you insert a child <aop:scoped-proxy/> element into a scoped bean
definition (see the section called “Choosing the type of proxy to create” and Chapter 38, XML Schema-
based configuration). Why do definitions of beans scoped at the request, session and custom-
scope levels require the <aop:scoped-proxy/> element? Let’s examine the following singleton bean
definition and contrast it with what you need to define for the aforementioned scopes (note that the
following userPreferences bean definition as it stands is incomplete).

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

<bean id="userManager" class="com.foo.UserManager">


<property name="userPreferences" ref="userPreferences"/>
</bean>

In the preceding example, the singleton bean userManager is injected with a reference to the HTTP
Session-scoped bean userPreferences. The salient point here is that the userManager bean is a
singleton: it will be instantiated exactly once per container, and its dependencies (in this case only one,
the userPreferences bean) are also injected only once. This means that the userManager bean
will only operate on the exact same userPreferences object, that is, the one that it was originally
injected with.

This is not the behavior you want when injecting a shorter-lived scoped bean into a longer-
lived scoped bean, for example injecting an HTTP Session-scoped collaborating bean as a
dependency into singleton bean. Rather, you need a single userManager object, and for the
lifetime of an HTTP Session, you need a userPreferences object that is specific to said HTTP
Session. Thus the container creates an object that exposes the exact same public interface as
the UserPreferences class (ideally an object that is a UserPreferences instance) which can
fetch the real UserPreferences object from the scoping mechanism (HTTP request, Session,
etc.). The container injects this proxy object into the userManager bean, which is unaware that this
UserPreferences reference is a proxy. In this example, when a UserManager instance invokes
a method on the dependency-injected UserPreferences object, it actually is invoking a method on
the proxy. The proxy then fetches the real UserPreferences object from (in this case) the HTTP
Session, and delegates the method invocation onto the retrieved real UserPreferences object.

Thus you need the following, correct and complete, configuration when injecting request- and
session-scoped beans into collaborating objects:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session">


<aop:scoped-proxy/>
</bean>

<bean id="userManager" class="com.foo.UserManager">


<property name="userPreferences" ref="userPreferences"/>
</bean>

Choosing the type of proxy to create

By default, when the Spring container creates a proxy for a bean that is marked up with the
<aop:scoped-proxy/> element, a CGLIB-based class proxy is created.

Note

CGLIB proxies only intercept public method calls! Do not call non-public methods on such a proxy;
they will not be delegated to the actual scoped target object.

Alternatively, you can configure the Spring container to create standard JDK interface-based proxies
for such scoped beans, by specifying false for the value of the proxy-target-class attribute of

5.0.0.M1 Spring Framework 55


Spring Framework Reference Documentation

the <aop:scoped-proxy/> element. Using JDK interface-based proxies means that you do not need
additional libraries in your application classpath to effect such proxying. However, it also means that the
class of the scoped bean must implement at least one interface, and that all collaborators into which the
scoped bean is injected must reference the bean through one of its interfaces.

<!-- DefaultUserPreferences implements the UserPreferences interface -->


<bean id="userPreferences" class="com.foo.DefaultUserPreferences" scope="session">
<aop:scoped-proxy proxy-target-class="false"/>
</bean>

<bean id="userManager" class="com.foo.UserManager">


<property name="userPreferences" ref="userPreferences"/>
</bean>

For more detailed information about choosing class-based or interface-based proxying, see Section 7.6,
“Proxying mechanisms”.

Custom scopes

The bean scoping mechanism is extensible; You can define your own scopes, or even redefine existing
scopes, although the latter is considered bad practice and you cannot override the built-in singleton
and prototype scopes.

Creating a custom scope

To integrate your custom scope(s) into the Spring container, you need to implement the
org.springframework.beans.factory.config.Scope interface, which is described in this
section. For an idea of how to implement your own scopes, see the Scope implementations that are
supplied with the Spring Framework itself and the Scope javadocs, which explains the methods you
need to implement in more detail.

The Scope interface has four methods to get objects from the scope, remove them from the scope,
and allow them to be destroyed.

The following method returns the object from the underlying scope. The session scope implementation,
for example, returns the session-scoped bean (and if it does not exist, the method returns a new instance
of the bean, after having bound it to the session for future reference).

Object get(String name, ObjectFactory objectFactory)

The following method removes the object from the underlying scope. The session scope implementation
for example, removes the session-scoped bean from the underlying session. The object should be
returned, but you can return null if the object with the specified name is not found.

Object remove(String name)

The following method registers the callbacks the scope should execute when it is destroyed or when
the specified object in the scope is destroyed. Refer to the javadocs or a Spring scope implementation
for more information on destruction callbacks.

void registerDestructionCallback(String name, Runnable destructionCallback)

The following method obtains the conversation identifier for the underlying scope. This identifier is
different for each scope. For a session scoped implementation, this identifier can be the session
identifier.

5.0.0.M1 Spring Framework 56


Spring Framework Reference Documentation

String getConversationId()

Using a custom scope

After you write and test one or more custom Scope implementations, you need to make the Spring
container aware of your new scope(s). The following method is the central method to register a new
Scope with the Spring container:

void registerScope(String scopeName, Scope scope);

This method is declared on the ConfigurableBeanFactory interface, which is available on most


of the concrete ApplicationContext implementations that ship with Spring via the BeanFactory
property.

The first argument to the registerScope(..) method is the unique name associated with a
scope; examples of such names in the Spring container itself are singleton and prototype. The
second argument to the registerScope(..) method is an actual instance of the custom Scope
implementation that you wish to register and use.

Suppose that you write your custom Scope implementation, and then register it as below.

Note

The example below uses SimpleThreadScope which is included with Spring, but not registered
by default. The instructions would be the same for your own custom Scope implementations.

Scope threadScope = new SimpleThreadScope();


beanFactory.registerScope("thread", threadScope);

You then create bean definitions that adhere to the scoping rules of your custom Scope:

<bean id="..." class="..." scope="thread">

With a custom Scope implementation, you are not limited to programmatic registration of the scope.
You can also do the Scope registration declaratively, using the CustomScopeConfigurer class:

5.0.0.M1 Spring Framework 57


Spring Framework Reference Documentation

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="thread">
<bean class="org.springframework.context.support.SimpleThreadScope"/>
</entry>
</map>
</property>
</bean>

<bean id="bar" class="x.y.Bar" scope="thread">


<property name="name" value="Rick"/>
<aop:scoped-proxy/>
</bean>

<bean id="foo" class="x.y.Foo">


<property name="bar" ref="bar"/>
</bean>

</beans>

Note

When you place <aop:scoped-proxy/> in a FactoryBean implementation, it is the factory


bean itself that is scoped, not the object returned from getObject().

3.6 Customizing the nature of a bean

Lifecycle callbacks

To interact with the container’s management of the bean lifecycle, you can implement
the Spring InitializingBean and DisposableBean interfaces. The container calls
afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform
certain actions upon initialization and destruction of your beans.

Tip

The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best
practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations
means that your beans are not coupled to Spring specific interfaces. For details see the section
called “@PostConstruct and @PreDestroy”.

If you don’t want to use the JSR-250 annotations but you are still looking to remove coupling
consider the use of init-method and destroy-method object definition metadata.

Internally, the Spring Framework uses BeanPostProcessor implementations to process any callback
interfaces it can find and call the appropriate methods. If you need custom features or other lifecycle
behavior Spring does not offer out-of-the-box, you can implement a BeanPostProcessor yourself.
For more information, see Section 3.8, “Container Extension Points”.

5.0.0.M1 Spring Framework 58


Spring Framework Reference Documentation

In addition to the initialization and destruction callbacks, Spring-managed objects may also implement
the Lifecycle interface so that those objects can participate in the startup and shutdown process as
driven by the container’s own lifecycle.

The lifecycle callback interfaces are described in this section.

Initialization callbacks

The org.springframework.beans.factory.InitializingBean interface allows a bean to


perform initialization work after all necessary properties on the bean have been set by the container.
The InitializingBean interface specifies a single method:

void afterPropertiesSet() throws Exception;

It is recommended that you do not use the InitializingBean interface because it unnecessarily
couples the code to Spring. Alternatively, use the @PostConstruct annotation or specify a POJO
initialization method. In the case of XML-based configuration metadata, you use the init-method
attribute to specify the name of the method that has a void no-argument signature. With Java config,
you use the initMethod attribute of @Bean, see the section called “Receiving lifecycle callbacks”. For
example, the following:

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

public class ExampleBean {

public void init() {


// do some initialization work
}

…is exactly the same as…

<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>

public class AnotherExampleBean implements InitializingBean {

public void afterPropertiesSet() {


// do some initialization work
}

but does not couple the code to Spring.

Destruction callbacks

Implementing the org.springframework.beans.factory.DisposableBean interface allows a


bean to get a callback when the container containing it is destroyed. The DisposableBean interface
specifies a single method:

void destroy() throws Exception;

It is recommended that you do not use the DisposableBean callback interface because it
unnecessarily couples the code to Spring. Alternatively, use the @PreDestroy annotation or specify
a generic method that is supported by bean definitions. With XML-based configuration metadata, you
use the destroy-method attribute on the <bean/>. With Java config, you use the destroyMethod

5.0.0.M1 Spring Framework 59


Spring Framework Reference Documentation

attribute of @Bean, see the section called “Receiving lifecycle callbacks”. For example, the following
definition:

<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>

public class ExampleBean {

public void cleanup() {


// do some destruction work (like releasing pooled connections)
}

is exactly the same as:

<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>

public class AnotherExampleBean implements DisposableBean {

public void destroy() {


// do some destruction work (like releasing pooled connections)
}

but does not couple the code to Spring.

Tip

The destroy-method attribute of a <bean> element can be assigned a special (inferred)


value which instructs Spring to automatically detect a public close or shutdown method
on the specific bean class (any class that implements java.lang.AutoCloseable or
java.io.Closeable would therefore match). This special (inferred) value can also be set
on the default-destroy-method attribute of a <beans> element to apply this behavior to an
entire set of beans (see the section called “Default initialization and destroy methods”). Note that
this is the default behavior with Java config.

Default initialization and destroy methods

When you write initialization and destroy method callbacks that do not use the Spring-specific
InitializingBean and DisposableBean callback interfaces, you typically write methods with
names such as init(), initialize(), dispose(), and so on. Ideally, the names of such lifecycle
callback methods are standardized across a project so that all developers use the same method names
and ensure consistency.

You can configure the Spring container to look for named initialization and destroy callback method
names on every bean. This means that you, as an application developer, can write your application
classes and use an initialization callback called init(), without having to configure an init-
method="init" attribute with each bean definition. The Spring IoC container calls that method
when the bean is created (and in accordance with the standard lifecycle callback contract described
previously). This feature also enforces a consistent naming convention for initialization and destroy
method callbacks.

Suppose that your initialization callback methods are named init() and destroy callback methods are
named destroy(). Your class will resemble the class in the following example.

5.0.0.M1 Spring Framework 60


Spring Framework Reference Documentation

public class DefaultBlogService implements BlogService {

private BlogDao blogDao;

public void setBlogDao(BlogDao blogDao) {


this.blogDao = blogDao;
}

// this is (unsurprisingly) the initialization callback method


public void init() {
if (this.blogDao == null) {
throw new IllegalStateException("The [blogDao] property must be set.");
}
}

<beans default-init-method="init">

<bean id="blogService" class="com.foo.DefaultBlogService">


<property name="blogDao" ref="blogDao" />
</bean>

</beans>

The presence of the default-init-method attribute on the top-level <beans/> element attribute
causes the Spring IoC container to recognize a method called init on beans as the initialization method
callback. When a bean is created and assembled, if the bean class has such a method, it is invoked
at the appropriate time.

You configure destroy method callbacks similarly (in XML, that is) by using the default-destroy-
method attribute on the top-level <beans/> element.

Where existing bean classes already have callback methods that are named at variance with the
convention, you can override the default by specifying (in XML, that is) the method name using the
init-method and destroy-method attributes of the <bean/> itself.

The Spring container guarantees that a configured initialization callback is called immediately after
a bean is supplied with all dependencies. Thus the initialization callback is called on the raw bean
reference, which means that AOP interceptors and so forth are not yet applied to the bean. A target
bean is fully created first, then an AOP proxy (for example) with its interceptor chain is applied. If the
target bean and the proxy are defined separately, your code can even interact with the raw target bean,
bypassing the proxy. Hence, it would be inconsistent to apply the interceptors to the init method, because
doing so would couple the lifecycle of the target bean with its proxy/interceptors and leave strange
semantics when your code interacts directly to the raw target bean.

Combining lifecycle mechanisms

As of Spring 2.5, you have three options for controlling bean lifecycle behavior: the InitializingBean
and DisposableBean callback interfaces; custom init() and destroy() methods; and the
@PostConstruct and @PreDestroy annotations. You can combine these mechanisms to control a
given bean.

Note

If multiple lifecycle mechanisms are configured for a bean, and each mechanism is configured
with a different method name, then each configured method is executed in the order listed below.
However, if the same method name is configured - for example, init() for an initialization

5.0.0.M1 Spring Framework 61


Spring Framework Reference Documentation

method - for more than one of these lifecycle mechanisms, that method is executed once, as
explained in the preceding section.

Multiple lifecycle mechanisms configured for the same bean, with different initialization methods, are
called as follows:

• Methods annotated with @PostConstruct

• afterPropertiesSet() as defined by the InitializingBean callback interface

• A custom configured init() method

Destroy methods are called in the same order:

• Methods annotated with @PreDestroy

• destroy() as defined by the DisposableBean callback interface

• A custom configured destroy() method

Startup and shutdown callbacks

The Lifecycle interface defines the essential methods for any object that has its own lifecycle
requirements (e.g. starts and stops some background process):

public interface Lifecycle {

void start();

void stop();

boolean isRunning();

Any Spring-managed object may implement that interface. Then, when the ApplicationContext
itself receives start and stop signals, e.g. for a stop/restart scenario at runtime, it will cascade those
calls to all Lifecycle implementations defined within that context. It does this by delegating to a
LifecycleProcessor:

public interface LifecycleProcessor extends Lifecycle {

void onRefresh();

void onClose();

Notice that the LifecycleProcessor is itself an extension of the Lifecycle interface. It also adds
two other methods for reacting to the context being refreshed and closed.

Tip

Note that the regular org.springframework.context.Lifecycle interface is just a plain


contract for explicit start/stop notifications and does NOT imply auto-startup at context refresh
time. Consider implementing org.springframework.context.SmartLifecycle instead
for fine-grained control over auto-startup of a specific bean (including startup phases). Also, please
note that stop notifications are not guaranteed to come before destruction: On regular shutdown,

5.0.0.M1 Spring Framework 62


Spring Framework Reference Documentation

all Lifecycle beans will first receive a stop notification before the general destruction callbacks
are being propagated; however, on hot refresh during a context’s lifetime or on aborted refresh
attempts, only destroy methods will be called.

The order of startup and shutdown invocations can be important. If a "depends-on" relationship exists
between any two objects, the dependent side will start after its dependency, and it will stop before its
dependency. However, at times the direct dependencies are unknown. You may only know that objects
of a certain type should start prior to objects of another type. In those cases, the SmartLifecycle
interface defines another option, namely the getPhase() method as defined on its super-interface,
Phased.

public interface Phased {

int getPhase();

public interface SmartLifecycle extends Lifecycle, Phased {

boolean isAutoStartup();

void stop(Runnable callback);

When starting, the objects with the lowest phase start first, and when stopping, the reverse order is
followed. Therefore, an object that implements SmartLifecycle and whose getPhase() method
returns Integer.MIN_VALUE would be among the first to start and the last to stop. At the other end of
the spectrum, a phase value of Integer.MAX_VALUE would indicate that the object should be started
last and stopped first (likely because it depends on other processes to be running). When considering
the phase value, it’s also important to know that the default phase for any "normal" Lifecycle object
that does not implement SmartLifecycle would be 0. Therefore, any negative phase value would
indicate that an object should start before those standard components (and stop after them), and vice
versa for any positive phase value.

As you can see the stop method defined by SmartLifecycle accepts a callback. Any implementation
must invoke that callback’s run() method after that implementation’s shutdown process is complete.
That enables asynchronous shutdown where necessary since the default implementation of the
LifecycleProcessor interface, DefaultLifecycleProcessor, will wait up to its timeout value
for the group of objects within each phase to invoke that callback. The default per-phase timeout
is 30 seconds. You can override the default lifecycle processor instance by defining a bean named
"lifecycleProcessor" within the context. If you only want to modify the timeout, then defining the following
would be sufficient:

<bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">


<!-- timeout value in milliseconds -->
<property name="timeoutPerShutdownPhase" value="10000"/>
</bean>

As mentioned, the LifecycleProcessor interface defines callback methods for the refreshing and
closing of the context as well. The latter will simply drive the shutdown process as if stop() had
been called explicitly, but it will happen when the context is closing. The 'refresh' callback on the
other hand enables another feature of SmartLifecycle beans. When the context is refreshed (after
all objects have been instantiated and initialized), that callback will be invoked, and at that point the
default lifecycle processor will check the boolean value returned by each SmartLifecycle object’s

5.0.0.M1 Spring Framework 63


Spring Framework Reference Documentation

isAutoStartup() method. If "true", then that object will be started at that point rather than waiting for
an explicit invocation of the context’s or its own start() method (unlike the context refresh, the context
start does not happen automatically for a standard context implementation). The "phase" value as well
as any "depends-on" relationships will determine the startup order in the same way as described above.

Shutting down the Spring IoC container gracefully in non-web applications

Note

This section applies only to non-web applications. Spring’s web-based ApplicationContext


implementations already have code in place to shut down the Spring IoC container gracefully
when the relevant web application is shut down.

If you are using Spring’s IoC container in a non-web application environment; for example, in a rich
client desktop environment; you register a shutdown hook with the JVM. Doing so ensures a graceful
shutdown and calls the relevant destroy methods on your singleton beans so that all resources are
released. Of course, you must still configure and implement these destroy callbacks correctly.

To register a shutdown hook, you call the registerShutdownHook() method that is declared on the
ConfigurableApplicationContext interface:

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public final class Boot {

public static void main(final String[] args) throws Exception {

ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(


new String []{"beans.xml"});

// add a shutdown hook for the above context...


ctx.registerShutdownHook();

// app runs here...

// main method exits, hook is called prior to the app shutting down...

}
}

ApplicationContextAware and BeanNameAware


When an ApplicationContext creates an object instance that implements the
org.springframework.context.ApplicationContextAware interface, the instance is
provided with a reference to that ApplicationContext.

public interface ApplicationContextAware {

void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

Thus beans can manipulate programmatically the ApplicationContext that created them, through
the ApplicationContext interface, or by casting the reference to a known subclass of this interface,
such as ConfigurableApplicationContext, which exposes additional functionality. One use
would be the programmatic retrieval of other beans. Sometimes this capability is useful; however, in
general you should avoid it, because it couples the code to Spring and does not follow the Inversion
of Control style, where collaborators are provided to beans as properties. Other methods of the

5.0.0.M1 Spring Framework 64


Spring Framework Reference Documentation

ApplicationContext provide access to file resources, publishing application events, and accessing
a MessageSource. These additional features are described in Section 3.15, “Additional Capabilities
of the ApplicationContext”

As of Spring 2.5, autowiring is another alternative to obtain reference to the ApplicationContext.


The "traditional" constructor and byType autowiring modes (as described in the section called
“Autowiring collaborators”) can provide a dependency of type ApplicationContext for a constructor
argument or setter method parameter, respectively. For more flexibility, including the ability to autowire
fields and multiple parameter methods, use the new annotation-based autowiring features. If you do,
the ApplicationContext is autowired into a field, constructor argument, or method parameter that
is expecting the ApplicationContext type if the field, constructor, or method in question carries the
@Autowired annotation. For more information, see the section called “@Autowired”.

When an ApplicationContext creates a class that implements the


org.springframework.beans.factory.BeanNameAware interface, the class is provided with a
reference to the name defined in its associated object definition.

public interface BeanNameAware {

void setBeanName(String name) throws BeansException;

The callback is invoked after population of normal bean properties but before an initialization callback
such as InitializingBean afterPropertiesSet or a custom init-method.

Other Aware interfaces

Besides ApplicationContextAware and BeanNameAware discussed above, Spring offers a range


of Aware interfaces that allow beans to indicate to the container that they require a certain infrastructure
dependency. The most important Aware interfaces are summarized below - as a general rule, the name
is a good indication of the dependency type:

Table 3.4. Aware interfaces

Name Injected Dependency Explained in…

ApplicationContextAware Declaring the section called


ApplicationContext “ApplicationContextAware and
BeanNameAware”

Event publisher of the enclosing Section 3.15, “Additional


ApplicationEventPublisherAware
ApplicationContext Capabilities of the
ApplicationContext”

BeanClassLoaderAware Class loader used to load the the section called “Instantiating
bean classes. beans”

BeanFactoryAware Declaring BeanFactory the section called


“ApplicationContextAware and
BeanNameAware”

BeanNameAware Name of the declaring bean the section called


“ApplicationContextAware and
BeanNameAware”

5.0.0.M1 Spring Framework 65


Spring Framework Reference Documentation

Name Injected Dependency Explained in…

BootstrapContextAware Resource adapter Chapter 28, JCA CCI


BootstrapContext the
container runs in. Typically
available only in JCA aware
ApplicationContexts

LoadTimeWeaverAware Defined weaver for processing the section called “Load-time


class definition at load time weaving with AspectJ in the
Spring Framework”

MessageSourceAware Configured strategy for Section 3.15, “Additional


resolving messages (with Capabilities of the
support for parametrization and ApplicationContext”
internationalization)

Spring JMX notification


NotificationPublisherAware Section 27.7, “Notifications”
publisher

ResourceLoaderAware Configured loader for low-level Chapter 4, Resources


access to resources

ServletConfigAware Current ServletConfig Chapter 18, Web MVC


the container runs in. Valid framework
only in a web-aware Spring
ApplicationContext

ServletContextAware Current ServletContext Chapter 18, Web MVC


the container runs in. Valid framework
only in a web-aware Spring
ApplicationContext

Note again that usage of these interfaces ties your code to the Spring API and does not follow
the Inversion of Control style. As such, they are recommended for infrastructure beans that require
programmatic access to the container.

3.7 Bean definition inheritance


A bean definition can contain a lot of configuration information, including constructor arguments, property
values, and container-specific information such as initialization method, static factory method name,
and so on. A child bean definition inherits configuration data from a parent definition. The child definition
can override some values, or add others, as needed. Using parent and child bean definitions can save
a lot of typing. Effectively, this is a form of templating.

If you work with an ApplicationContext interface programmatically, child bean definitions


are represented by the ChildBeanDefinition class. Most users do not work with
them on this level, instead configuring bean definitions declaratively in something like the
ClassPathXmlApplicationContext. When you use XML-based configuration metadata, you
indicate a child bean definition by using the parent attribute, specifying the parent bean as the value
of this attribute.

5.0.0.M1 Spring Framework 66


Spring Framework Reference Documentation

<bean id="inheritedTestBean" abstract="true"


class="org.springframework.beans.TestBean">
<property name="name" value="parent"/>
<property name="age" value="1"/>
</bean>

<bean id="inheritsWithDifferentClass"
class="org.springframework.beans.DerivedTestBean"
parent="inheritedTestBean" init-method="initialize">
<property name="name" value="override"/>
<!-- the age property value of 1 will be inherited from parent -->
</bean>

A child bean definition uses the bean class from the parent definition if none is specified, but can also
override it. In the latter case, the child bean class must be compatible with the parent, that is, it must
accept the parent’s property values.

A child bean definition inherits scope, constructor argument values, property values, and method
overrides from the parent, with the option to add new values. Any scope, initialization method, destroy
method, and/or static factory method settings that you specify will override the corresponding parent
settings.

The remaining settings are always taken from the child definition: depends on, autowire mode,
dependency check, singleton, lazy init.

The preceding example explicitly marks the parent bean definition as abstract by using the abstract
attribute. If the parent definition does not specify a class, explicitly marking the parent bean definition
as abstract is required, as follows:

<bean id="inheritedTestBeanWithoutClass" abstract="true">


<property name="name" value="parent"/>
<property name="age" value="1"/>
</bean>

<bean id="inheritsWithClass" class="org.springframework.beans.DerivedTestBean"


parent="inheritedTestBeanWithoutClass" init-method="initialize">
<property name="name" value="override"/>
<!-- age will inherit the value of 1 from the parent bean definition-->
</bean>

The parent bean cannot be instantiated on its own because it is incomplete, and it is also explicitly
marked as abstract. When a definition is abstract like this, it is usable only as a pure template
bean definition that serves as a parent definition for child definitions. Trying to use such an
abstract parent bean on its own, by referring to it as a ref property of another bean or doing an
explicit getBean() call with the parent bean id, returns an error. Similarly, the container’s internal
preInstantiateSingletons() method ignores bean definitions that are defined as abstract.

Note

ApplicationContext pre-instantiates all singletons by default. Therefore, it is important (at


least for singleton beans) that if you have a (parent) bean definition which you intend to use only
as a template, and this definition specifies a class, you must make sure to set the abstract attribute
to true, otherwise the application context will actually (attempt to) pre-instantiate the abstract
bean.

5.0.0.M1 Spring Framework 67


Spring Framework Reference Documentation

3.8 Container Extension Points


Typically, an application developer does not need to subclass ApplicationContext implementation
classes. Instead, the Spring IoC container can be extended by plugging in implementations of special
integration interfaces. The next few sections describe these integration interfaces.

Customizing beans using a BeanPostProcessor


The BeanPostProcessor interface defines callback methods that you can implement to provide your
own (or override the container’s default) instantiation logic, dependency-resolution logic, and so forth. If
you want to implement some custom logic after the Spring container finishes instantiating, configuring,
and initializing a bean, you can plug in one or more BeanPostProcessor implementations.

You can configure multiple BeanPostProcessor instances, and you can control the order in
which these BeanPostProcessors execute by setting the order property. You can set this
property only if the BeanPostProcessor implements the Ordered interface; if you write your own
BeanPostProcessor you should consider implementing the Ordered interface too. For further
details, consult the javadocs of the BeanPostProcessor and Ordered interfaces. See also the note
below on programmatic registration of BeanPostProcessors.

Note

BeanPostProcessors operate on bean (or object) instances; that is to say, the Spring IoC
container instantiates a bean instance and then BeanPostProcessors do their work.

BeanPostProcessors are scoped per-container. This is only relevant if you are using container
hierarchies. If you define a BeanPostProcessor in one container, it will only post-process the
beans in that container. In other words, beans that are defined in one container are not post-
processed by a BeanPostProcessor defined in another container, even if both containers are
part of the same hierarchy.

To change the actual bean definition (i.e., the blueprint that defines the bean), you instead
need to use a BeanFactoryPostProcessor as described in the section called “Customizing
configuration metadata with a BeanFactoryPostProcessor”.

The org.springframework.beans.factory.config.BeanPostProcessor interface consists


of exactly two callback methods. When such a class is registered as a post-processor with the container,
for each bean instance that is created by the container, the post-processor gets a callback from the
container both before container initialization methods (such as InitializingBean’s afterPropertiesSet()
and any declared init method) are called as well as after any bean initialization callbacks. The post-
processor can take any action with the bean instance, including ignoring the callback completely. A
bean post-processor typically checks for callback interfaces or may wrap a bean with a proxy. Some
Spring AOP infrastructure classes are implemented as bean post-processors in order to provide proxy-
wrapping logic.

An ApplicationContext automatically detects any beans that are defined in the configuration
metadata which implement the BeanPostProcessor interface. The ApplicationContext registers
these beans as post-processors so that they can be called later upon bean creation. Bean post-
processors can be deployed in the container just like any other beans.

Note that when declaring a BeanPostProcessor using an @Bean factory method on a configuration
class, the return type of the factory method should be the implementation class itself or at least

5.0.0.M1 Spring Framework 68


Spring Framework Reference Documentation

the org.springframework.beans.factory.config.BeanPostProcessor interface, clearly


indicating the post-processor nature of that bean. Otherwise, the ApplicationContext won’t be able
to autodetect it by type before fully creating it. Since a BeanPostProcessor needs to be instantiated
early in order to apply to the initialization of other beans in the context, this early type detection is critical.

Programmatically registering BeanPostProcessors

While the recommended approach for BeanPostProcessor registration is through


ApplicationContext auto-detection (as described above), it is also possible to register them
programmatically against a ConfigurableBeanFactory using the addBeanPostProcessor
method. This can be useful when needing to evaluate conditional logic before registration,
or even for copying bean post processors across contexts in a hierarchy. Note however
that BeanPostProcessors added programmatically do not respect the Ordered interface.
Here it is the order of registration that dictates the order of execution. Note also that
BeanPostProcessors registered programmatically are always processed before those
registered through auto-detection, regardless of any explicit ordering.

BeanPostProcessors and AOP auto-proxying

Classes that implement the BeanPostProcessor interface are special and are treated differently
by the container. All BeanPostProcessors and beans that they reference directly are
instantiated on startup, as part of the special startup phase of the ApplicationContext. Next,
all BeanPostProcessors are registered in a sorted fashion and applied to all further beans in the
container. Because AOP auto-proxying is implemented as a BeanPostProcessor itself, neither
BeanPostProcessors nor the beans they reference directly are eligible for auto-proxying, and
thus do not have aspects woven into them.

For any such bean, you should see an informational log message: "Bean foo is not eligible
for getting processed by all BeanPostProcessor interfaces (for example: not eligible for auto-
proxying)".

Note that if you have beans wired into your BeanPostProcessor using autowiring or
@Resource (which may fall back to autowiring), Spring might access unexpected beans when
searching for type-matching dependency candidates, and therefore make them ineligible for
auto-proxying or other kinds of bean post-processing. For example, if you have a dependency
annotated with @Resource where the field/setter name does not directly correspond to the
declared name of a bean and no name attribute is used, then Spring will access other beans for
matching them by type.

The following examples show how to write, register, and use BeanPostProcessors in an
ApplicationContext.

Example: Hello World, BeanPostProcessor-style

This first example illustrates basic usage. The example shows a custom BeanPostProcessor
implementation that invokes the toString() method of each bean as it is created by the container
and prints the resulting string to the system console.

Find below the custom BeanPostProcessor implementation class definition:

5.0.0.M1 Spring Framework 69


Spring Framework Reference Documentation

package scripting;

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.BeansException;

public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor {

// simply return the instantiated bean as-is


public Object postProcessBeforeInitialization(Object bean,
String beanName) throws BeansException {
return bean; // we could potentially return any object reference here...
}

public Object postProcessAfterInitialization(Object bean,


String beanName) throws BeansException {
System.out.println("Bean '" + beanName + "' created : " + bean.toString());
return bean;
}

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang.xsd">

<lang:groovy id="messenger"
script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy">
<lang:property name="message" value="Fiona Apple Is Just So Dreamy."/>
</lang:groovy>

<!--
when the above bean (messenger) is instantiated, this custom
BeanPostProcessor implementation will output the fact to the system console
-->
<bean class="scripting.InstantiationTracingBeanPostProcessor"/>

</beans>

Notice how the InstantiationTracingBeanPostProcessor is simply defined. It does not even


have a name, and because it is a bean it can be dependency-injected just like any other bean. (The
preceding configuration also defines a bean that is backed by a Groovy script. The Spring dynamic
language support is detailed in the chapter entitled Chapter 31, Dynamic language support.)

The following simple Java application executes the preceding code and configuration:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scripting.Messenger;

public final class Boot {

public static void main(final String[] args) throws Exception {


ApplicationContext ctx = new ClassPathXmlApplicationContext("scripting/beans.xml");
Messenger messenger = (Messenger) ctx.getBean("messenger");
System.out.println(messenger);
}

The output of the preceding application resembles the following:

5.0.0.M1 Spring Framework 70


Spring Framework Reference Documentation

Bean 'messenger' created : org.springframework.scripting.groovy.GroovyMessenger@272961


org.springframework.scripting.groovy.GroovyMessenger@272961

Example: The RequiredAnnotationBeanPostProcessor

Using callback interfaces or annotations in conjunction with a custom BeanPostProcessor


implementation is a common means of extending the Spring IoC container. An example is Spring’s
RequiredAnnotationBeanPostProcessor - a BeanPostProcessor implementation that ships
with the Spring distribution which ensures that JavaBean properties on beans that are marked with an
(arbitrary) annotation are actually (configured to be) dependency-injected with a value.

Customizing configuration metadata with a BeanFactoryPostProcessor

The next extension point that we will look at is


the org.springframework.beans.factory.config.BeanFactoryPostProcessor. The
semantics of this interface are similar to those of the BeanPostProcessor, with one major difference:
BeanFactoryPostProcessor operates on the bean configuration metadata; that is, the Spring IoC
container allows a BeanFactoryPostProcessor to read the configuration metadata and potentially
change it before the container instantiates any beans other than BeanFactoryPostProcessors.

You can configure multiple BeanFactoryPostProcessors, and you can control the order in which
these BeanFactoryPostProcessors execute by setting the order property. However, you can only
set this property if the BeanFactoryPostProcessor implements the Ordered interface. If you write
your own BeanFactoryPostProcessor, you should consider implementing the Ordered interface
too. Consult the javadocs of the BeanFactoryPostProcessor and Ordered interfaces for more
details.

Note

If you want to change the actual bean instances (i.e., the objects that are created from the
configuration metadata), then you instead need to use a BeanPostProcessor (described
above in the section called “Customizing beans using a BeanPostProcessor”). While it is
technically possible to work with bean instances within a BeanFactoryPostProcessor (e.g.,
using BeanFactory.getBean()), doing so causes premature bean instantiation, violating the
standard container lifecycle. This may cause negative side effects such as bypassing bean post
processing.

Also, BeanFactoryPostProcessors are scoped per-container. This is only relevant if you are
using container hierarchies. If you define a BeanFactoryPostProcessor in one container, it
will only be applied to the bean definitions in that container. Bean definitions in one container
will not be post-processed by BeanFactoryPostProcessors in another container, even if both
containers are part of the same hierarchy.

A bean factory post-processor is executed automatically when it is declared inside an


ApplicationContext, in order to apply changes to the configuration metadata that
define the container. Spring includes a number of predefined bean factory post-processors,
such as PropertyOverrideConfigurer and PropertyPlaceholderConfigurer. A custom
BeanFactoryPostProcessor can also be used, for example, to register custom property editors.

An ApplicationContext automatically detects any beans that are deployed into it that implement
the BeanFactoryPostProcessor interface. It uses these beans as bean factory post-processors, at
the appropriate time. You can deploy these post-processor beans as you would any other bean.

5.0.0.M1 Spring Framework 71


Spring Framework Reference Documentation

Note

As with BeanPostProcessors , you typically do not want to configure


BeanFactoryPostProcessors for lazy initialization. If no other bean references a
Bean(Factory)PostProcessor, that post-processor will not get instantiated at all. Thus,
marking it for lazy initialization will be ignored, and the Bean(Factory)PostProcessor will be
instantiated eagerly even if you set the default-lazy-init attribute to true on the declaration
of your <beans /> element.

Example: the Class name substitution PropertyPlaceholderConfigurer

You use the PropertyPlaceholderConfigurer to externalize property values from a bean


definition in a separate file using the standard Java Properties format. Doing so enables the person
deploying an application to customize environment-specific properties such as database URLs and
passwords, without the complexity or risk of modifying the main XML definition file or files for the
container.

Consider the following XML-based configuration metadata fragment, where a DataSource with
placeholder values is defined. The example shows properties configured from an external Properties
file. At runtime, a PropertyPlaceholderConfigurer is applied to the metadata that will replace
some properties of the DataSource. The values to replace are specified as placeholders of the form
${property-name} which follows the Ant / log4j / JSP EL style.

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:com/foo/jdbc.properties"/>
</bean>

<bean id="dataSource" destroy-method="close"


class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

The actual values come from another file in the standard Java Properties format:

jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root

Therefore, the string ${jdbc.username} is replaced at runtime with the value 'sa', and
the same applies for other placeholder values that match keys in the properties file. The
PropertyPlaceholderConfigurer checks for placeholders in most properties and attributes of a
bean definition. Furthermore, the placeholder prefix and suffix can be customized.

With the context namespace introduced in Spring 2.5, it is possible to configure property placeholders
with a dedicated configuration element. One or more locations can be provided as a comma-separated
list in the location attribute.

<context:property-placeholder location="classpath:com/foo/jdbc.properties"/>

The PropertyPlaceholderConfigurer not only looks for properties in the Properties file you
specify. By default it also checks against the Java System properties if it cannot find a property in the
specified properties files. You can customize this behavior by setting the systemPropertiesMode
property of the configurer with one of the following three supported integer values:

5.0.0.M1 Spring Framework 72


Spring Framework Reference Documentation

• never (0): Never check system properties

• fallback (1): Check system properties if not resolvable in the specified properties files. This is the
default.

• override (2): Check system properties first, before trying the specified properties files. This allows
system properties to override any other property source.

Consult the PropertyPlaceholderConfigurer javadocs for more information.

Tip

You can use the PropertyPlaceholderConfigurer to substitute class names, which is


sometimes useful when you have to pick a particular implementation class at runtime. For
example:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:com/foo/strategy.properties</value>
</property>
<property name="properties">
<value>custom.strategy.class=com.foo.DefaultStrategy</value>
</property>
</bean>

<bean id="serviceStrategy" class="${custom.strategy.class}"/>

If the class cannot be resolved at runtime to a valid class, resolution of the bean fails when
it is about to be created, which is during the preInstantiateSingletons() phase of an
ApplicationContext for a non-lazy-init bean.

Example: the PropertyOverrideConfigurer

The PropertyOverrideConfigurer, another bean factory post-processor, resembles the


PropertyPlaceholderConfigurer, but unlike the latter, the original definitions can have default
values or no values at all for bean properties. If an overriding Properties file does not have an entry
for a certain bean property, the default context definition is used.

Note that the bean definition is not aware of being overridden, so it is not immediately obvious
from the XML definition file that the override configurer is being used. In case of multiple
PropertyOverrideConfigurer instances that define different values for the same bean property,
the last one wins, due to the overriding mechanism.

Properties file configuration lines take this format:

beanName.property=value

For example:

dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql:mydb

This example file can be used with a container definition that contains a bean called dataSource, which
has driver and url properties.

Compound property names are also supported, as long as every component of the path except the
final property being overridden is already non-null (presumably initialized by the constructors). In this
example…

5.0.0.M1 Spring Framework 73


Spring Framework Reference Documentation

foo.fred.bob.sammy=123

i. the sammy property of the bob property of the fred property of the foo bean is set to the scalar
value 123.

Note

Specified override values are always literal values; they are not translated into bean references.
This convention also applies when the original value in the XML bean definition specifies a bean
reference.

With the context namespace introduced in Spring 2.5, it is possible to configure property overriding
with a dedicated configuration element:

<context:property-override location="classpath:override.properties"/>

Customizing instantiation logic with a FactoryBean


Implement the org.springframework.beans.factory.FactoryBean interface for objects that
are themselves factories.

The FactoryBean interface is a point of pluggability into the Spring IoC container’s instantiation logic.
If you have complex initialization code that is better expressed in Java as opposed to a (potentially)
verbose amount of XML, you can create your own FactoryBean, write the complex initialization inside
that class, and then plug your custom FactoryBean into the container.

The FactoryBean interface provides three methods:

• Object getObject(): returns an instance of the object this factory creates. The instance can
possibly be shared, depending on whether this factory returns singletons or prototypes.

• boolean isSingleton(): returns true if this FactoryBean returns singletons, false otherwise.

• Class getObjectType(): returns the object type returned by the getObject() method or null
if the type is not known in advance.

The FactoryBean concept and interface is used in a number of places within the Spring Framework;
more than 50 implementations of the FactoryBean interface ship with Spring itself.

When you need to ask a container for an actual FactoryBean instance itself instead of the bean
it produces, preface the bean’s id with the ampersand symbol ( &) when calling the getBean()
method of the ApplicationContext. So for a given FactoryBean with an id of myBean, invoking
getBean("myBean") on the container returns the product of the FactoryBean; whereas, invoking
getBean("&myBean") returns the FactoryBean instance itself.

3.9 Annotation-based container configuration


Are annotations better than XML for configuring Spring?

The introduction of annotation-based configurations raised the question of whether this approach
is 'better' than XML. The short answer is it depends. The long answer is that each approach has
its pros and cons, and usually it is up to the developer to decide which strategy suits them better.
Due to the way they are defined, annotations provide a lot of context in their declaration, leading
to shorter and more concise configuration. However, XML excels at wiring up components without

5.0.0.M1 Spring Framework 74


Spring Framework Reference Documentation

touching their source code or recompiling them. Some developers prefer having the wiring close
to the source while others argue that annotated classes are no longer POJOs and, furthermore,
that the configuration becomes decentralized and harder to control.

No matter the choice, Spring can accommodate both styles and even mix them together. It’s worth
pointing out that through its JavaConfig option, Spring allows annotations to be used in a non-
invasive way, without touching the target components source code and that in terms of tooling, all
configuration styles are supported by the Spring Tool Suite.

An alternative to XML setups is provided by annotation-based configuration which rely on the bytecode
metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to
describe a bean wiring, the developer moves the configuration into the component class itself by using
annotations on the relevant class, method, or field declaration. As mentioned in the section called
“Example: The RequiredAnnotationBeanPostProcessor”, using a BeanPostProcessor in conjunction
with annotations is a common means of extending the Spring IoC container. For example, Spring
2.0 introduced the possibility of enforcing required properties with the @Required annotation. Spring
2.5 made it possible to follow that same general approach to drive Spring’s dependency injection.
Essentially, the @Autowired annotation provides the same capabilities as described in the section
called “Autowiring collaborators” but with more fine-grained control and wider applicability. Spring 2.5
also added support for JSR-250 annotations such as @PostConstruct, and @PreDestroy. Spring
3.0 added support for JSR-330 (Dependency Injection for Java) annotations contained in the javax.inject
package such as @Inject and @Named. Details about those annotations can be found in the relevant
section.

Note

Annotation injection is performed before XML injection, thus the latter configuration will override
the former for properties wired through both approaches.

As always, you can register them as individual bean definitions, but they can also be implicitly registered
by including the following tag in an XML-based Spring configuration (notice the inclusion of the context
namespace):

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<context:annotation-config/>

</beans>

(The implicitly registered post-processors include AutowiredAnnotationBeanPostProcessor,


CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor, as
well as the aforementioned RequiredAnnotationBeanPostProcessor.)

Note

<context:annotation-config/> only looks for annotations on beans in the same application


context in which it is defined. This means that, if you put <context:annotation-config/>

5.0.0.M1 Spring Framework 75


Spring Framework Reference Documentation

in a WebApplicationContext for a DispatcherServlet, it only checks for @Autowired


beans in your controllers, and not your services. See Section 18.2, “The DispatcherServlet” for
more information.

@Required

The @Required annotation applies to bean property setter methods, as in the following example:

public class SimpleMovieLister {

private MovieFinder movieFinder;

@Required
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}

// ...

This annotation simply indicates that the affected bean property must be populated at configuration time,
through an explicit property value in a bean definition or through autowiring. The container throws an
exception if the affected bean property has not been populated; this allows for eager and explicit failure,
avoiding NullPointerExceptions or the like later on. It is still recommended that you put assertions
into the bean class itself, for example, into an init method. Doing so enforces those required references
and values even when you use the class outside of a container.

@Autowired

Note

JSR 330’s @Inject annotation can be used in place of Spring’s @Autowired annotation in the
examples below. See here for more details.

You can apply the @Autowired annotation to constructors:

public class MovieRecommender {

private final CustomerPreferenceDao customerPreferenceDao;

@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}

// ...

Note

As of Spring Framework 4.3, the @Autowired constructor is no longer necessary if the target
bean only defines one constructor. If several constructors are available, at least one must be
annotated to teach the container which one it has to use.

As expected, you can also apply the @Autowired annotation to "traditional" setter methods:

5.0.0.M1 Spring Framework 76


Spring Framework Reference Documentation

public class SimpleMovieLister {

private MovieFinder movieFinder;

@Autowired
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}

// ...

You can also apply the annotation to methods with arbitrary names and/or multiple arguments:

public class MovieRecommender {

private MovieCatalog movieCatalog;

private CustomerPreferenceDao customerPreferenceDao;

@Autowired
public void prepare(MovieCatalog movieCatalog,
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
}

// ...

You can apply @Autowired to fields as well and even mix it with constructors:

public class MovieRecommender {

private final CustomerPreferenceDao customerPreferenceDao;

@Autowired
private MovieCatalog movieCatalog;

@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}

// ...

It is also possible to provide all beans of a particular type from the ApplicationContext by adding
the annotation to a field or method that expects an array of that type:

public class MovieRecommender {

@Autowired
private MovieCatalog[] movieCatalogs;

// ...

The same applies for typed collections:

5.0.0.M1 Spring Framework 77