81
11/29/13 Reference Documentation docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 1/81 Spring Framework Reference Documentation 3.1 Copyright © 2004-2012 Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, Rob Harrop, Alef Arendsen, Thomas Risberg, Darren Davison, Dmitriy Kopylenko, Mark Pollack, Thierry Templier, Erwin Vervaet, Portia Tung, Ben Hale, Adrian Colyer, John Lewis, Costin Leau, Mark Fisher, Sam Brannen, Ramnivas Laddad, Arjen Poutsma, Chris Beams, Tareq Abedrabbo, Andy Clement, Dave Syer, Oliver Gierke, Rossen Stoyanchev Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically. Table of Contents I. Overview of Spring Framework 1. Introduction to Spring Framework 1.1. Dependency Injection and Inversion of Control 1.2. Modules 1.2.1. Core Container 1.2.2. Data Access/Integration 1.2.3. Web 1.2.4. AOP and Instrumentation 1.2.5. Test 1.3. Usage scenarios 1.3.1. Dependency Management and Naming Conventions 1.3.1.1. Spring Dependencies and Depending on Spring 1.3.1.2. Maven Dependency Management 1.3.1.3. Ivy Dependency Management 1.3.2. Logging 1.3.2.1. Not Using Commons Logging 1.3.2.2. Using SLF4J 1.3.2.3. Using Log4J II. What's New in Spring 3 2. New Features and Enhancements in Spring 3.0 2.1. Java 5 2.2. Improved documentation 2.3. New articles and tutorials 2.4. New module organization and build system 2.5. Overview of new features 2.5.1. Core APIs updated for Java 5 2.5.2. Spring Expression Language

Reference Documentation

Embed Size (px)

DESCRIPTION

ref

Citation preview

Page 1: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 1/81

Spring Framework

Reference Documentation

3.1

Copyright © 2004-2012 Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, RobHarrop, Alef Arendsen, Thomas Risberg, Darren Davison, Dmitriy Kopylenko, Mark Pollack,Thierry Templier, Erwin Vervaet, Portia Tung, Ben Hale, Adrian Colyer, John Lewis, Costin Leau,Mark Fisher, Sam Brannen, Ramnivas Laddad, Arjen Poutsma, Chris Beams, Tareq Abedrabbo,Andy Clement, Dave Syer, Oliver Gierke, Rossen Stoyanchev

Copies of this document may be made for your own use and for distribution to others, provided that you donot charge any fee for such copies and further provided that each copy contains this Copyright Notice, whetherdistributed in print or electronically.

Table of Contents

I. Overview of Spring Framework

1. Introduction to Spring Framework

1.1. Dependency Injection and Inversion of Control1.2. Modules

1.2.1. Core Container1.2.2. Data Access/Integration1.2.3. Web1.2.4. AOP and Instrumentation1.2.5. Test

1.3. Usage scenarios

1.3.1. Dependency Management and Naming Conventions

1.3.1.1. Spring Dependencies and Depending on Spring1.3.1.2. Maven Dependency Management1.3.1.3. Ivy Dependency Management

1.3.2. Logging

1.3.2.1. Not Using Commons Logging1.3.2.2. Using SLF4J1.3.2.3. Using Log4J

II. What's New in Spring 3

2. New Features and Enhancements in Spring 3.0

2.1. Java 52.2. Improved documentation2.3. New articles and tutorials2.4. New module organization and build system2.5. Overview of new features

2.5.1. Core APIs updated for Java 52.5.2. Spring Expression Language

Page 2: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 2/81

2.5.3. The Inversion of Control (IoC) container

2.5.3.1. Java based bean metadata2.5.3.2. Defining bean metadata within components

2.5.4. General purpose type conversion system and field formatting system2.5.5. The Data Tier2.5.6. The Web Tier

2.5.6.1. Comprehensive REST support2.5.6.2. @MVC additions

2.5.7. Declarative model validation2.5.8. Early support for Java EE 62.5.9. Support for embedded databases

3. New Features and Enhancements in Spring 3.1

3.1. Overview of new features

3.1.1. Cache Abstraction3.1.2. Bean Definition Profiles3.1.3. Environment Abstraction3.1.4. PropertySource Abstraction3.1.5. Code equivalents for Spring's XML namespaces3.1.6. Support for Hibernate 4.x3.1.7. TestContext framework support for @Configuration classes and beandefinition profiles3.1.8. c: namespace for more concise constructor injection3.1.9. Support for injection against non-standard JavaBeans setters3.1.10. Support for Servlet 3 code-based configuration of Servlet Container3.1.11. Support for Servlet 3 MultipartResolver3.1.12. JPA EntityManagerFactory bootstrapping without persistence.xml3.1.13. New HandlerMethod-based Support Classes For Annotated ControllerProcessing3.1.14. "consumes" and "produces" conditions in @RequestMapping3.1.15. Flash Attributes and RedirectAttributes3.1.16. URI Template Variable Enhancements3.1.17. @Valid On @RequestBody Controller Method Arguments3.1.18. @RequestPart Annotation On Controller Method Arguments3.1.19. UriComponentsBuilder and UriComponents

III. Core Technologies

4. The IoC container

4.1. Introduction to the Spring IoC container and beans4.2. Container overview

4.2.1. Configuration metadata4.2.2. Instantiating a container

4.2.2.1. Composing XML-based configuration metadata

4.2.3. Using the container

4.3. Bean overview

4.3.1. Naming beans

Page 3: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 3/81

4.3.1.1. Aliasing a bean outside the bean definition

4.3.2. Instantiating beans

4.3.2.1. Instantiation with a constructor4.3.2.2. Instantiation with a static factory method4.3.2.3. Instantiation using an instance factory method

4.4. Dependencies

4.4.1. Dependency injection

4.4.1.1. Constructor-based dependency injection4.4.1.2. Setter-based dependency injection4.4.1.3. Dependency resolution process4.4.1.4. Examples of dependency injection

4.4.2. Dependencies and configuration in detail

4.4.2.1. Straight values (primitives, Strings, and so on)4.4.2.2. References to other beans (collaborators)4.4.2.3. Inner beans4.4.2.4. Collections4.4.2.5. Null and empty string values4.4.2.6. XML shortcut with the p-namespace4.4.2.7. XML shortcut with the c-namespace4.4.2.8. Compound property names

4.4.3. Using depends-on4.4.4. Lazy-initialized beans4.4.5. Autowiring collaborators

4.4.5.1. Limitations and disadvantages of autowiring4.4.5.2. Excluding a bean from autowiring

4.4.6. Method injection

4.4.6.1. Lookup method injection4.4.6.2. Arbitrary method replacement

4.5. Bean scopes

4.5.1. The singleton scope4.5.2. The prototype scope4.5.3. Singleton beans with prototype-bean dependencies4.5.4. Request, session, and global session scopes

4.5.4.1. Initial web configuration4.5.4.2. Request scope4.5.4.3. Session scope4.5.4.4. Global session scope4.5.4.5. Scoped beans as dependencies

4.5.5. Custom scopes

4.5.5.1. Creating a custom scope4.5.5.2. Using a custom scope

4.6. Customizing the nature of a bean

Page 4: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 4/81

4.6.1. Lifecycle callbacks

4.6.1.1. Initialization callbacks4.6.1.2. Destruction callbacks4.6.1.3. Default initialization and destroy methods4.6.1.4. Combining lifecycle mechanisms4.6.1.5. Startup and shutdown callbacks4.6.1.6. Shutting down the Spring IoC container gracefully in non-webapplications

4.6.2. ApplicationContextAware and BeanNameAware4.6.3. Other Aware interfaces

4.7. Bean definition inheritance4.8. Container Extension Points

4.8.1. Customizing beans using a BeanPostProcessor

4.8.1.1. Example: Hello World, BeanPostProcessor-style4.8.1.2. Example: The RequiredAnnotationBeanPostProcessor

4.8.2. Customizing configuration metadata with a BeanFactoryPostProcessor

4.8.2.1. Example: the PropertyPlaceholderConfigurer4.8.2.2. Example: the PropertyOverrideConfigurer

4.8.3. Customizing instantiation logic with a FactoryBean

4.9. Annotation-based container configuration

4.9.1. @Required4.9.2. @Autowired4.9.3. Fine-tuning annotation-based autowiring with qualifiers4.9.4. CustomAutowireConfigurer4.9.5. @Resource4.9.6. @PostConstruct and @PreDestroy

4.10. Classpath scanning and managed components

4.10.1. @Component and further stereotype annotations4.10.2. Automatically detecting classes and registering bean definitions4.10.3. Using filters to customize scanning4.10.4. Defining bean metadata within components4.10.5. Naming autodetected components4.10.6. Providing a scope for autodetected components4.10.7. Providing qualifier metadata with annotations

4.11. Using JSR 330 Standard Annotations

4.11.1. Dependency Injection with @Inject and @Named4.11.2. @Named: a standard equivalent to the @Component annotation4.11.3. Limitations of the standard approach

4.12. Java-based container configuration

4.12.1. Basic concepts: @Configuration and @Bean4.12.2. Instantiating the Spring container usingAnnotationConfigApplicationContext

4.12.2.1. Simple construction

Page 5: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 5/81

4.12.2.2. Building the container programmatically using register(Class<?>...)4.12.2.3. Enabling component scanning with scan(String...)4.12.2.4. Support for web applications withAnnotationConfigWebApplicationContext

4.12.3. Composing Java-based configurations

4.12.3.1. Using the @Import annotation4.12.3.2. Combining Java and XML configuration

4.12.4. Using the @Bean annotation

4.12.4.1. Declaring a bean4.12.4.2. Injecting dependencies4.12.4.3. Receiving lifecycle callbacks4.12.4.4. Specifying bean scope4.12.4.5. Customizing bean naming4.12.4.6. Bean aliasing

4.12.5. Further information about how Java-based configuration works internally

4.13. Registering a LoadTimeWeaver4.14. Additional Capabilities of the ApplicationContext

4.14.1. Internationalization using MessageSource4.14.2. Standard and Custom Events4.14.3. Convenient access to low-level resources4.14.4. Convenient ApplicationContext instantiation for web applications4.14.5. Deploying a Spring ApplicationContext as a J2EE RAR file

4.15. The BeanFactory

4.15.1. BeanFactory or ApplicationContext?4.15.2. Glue code and the evil singleton

5. Resources

5.1. Introduction5.2. The Resource interface5.3. Built-in Resource implementations

5.3.1. UrlResource5.3.2. ClassPathResource5.3.3. FileSystemResource5.3.4. ServletContextResource5.3.5. InputStreamResource5.3.6. ByteArrayResource

5.4. The ResourceLoader5.5. The ResourceLoaderAware interface5.6. Resources as dependencies5.7. Application contexts and Resource paths

5.7.1. Constructing application contexts

5.7.1.1. Constructing ClassPathXmlApplicationContext instances -shortcuts

5.7.2. Wildcards in application context constructor resource paths

Page 6: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 6/81

5.7.2.1. Ant-style Patterns5.7.2.2. The classpath*: prefix5.7.2.3. Other notes relating to wildcards

5.7.3. FileSystemResource caveats

6. Validation, Data Binding, and Type Conversion

6.1. Introduction6.2. Validation using Spring's Validator interface6.3. Resolving codes to error messages6.4. Bean manipulation and the BeanWrapper

6.4.1. Setting and getting basic and nested properties6.4.2. Built-in PropertyEditor implementations

6.4.2.1. Registering additional custom PropertyEditors

6.5. Spring 3 Type Conversion

6.5.1. Converter SPI6.5.2. ConverterFactory6.5.3. GenericConverter

6.5.3.1. ConditionalGenericConverter

6.5.4. ConversionService API6.5.5. Configuring a ConversionService6.5.6. Using a ConversionService programatically

6.6. Spring 3 Field Formatting

6.6.1. Formatter SPI6.6.2. Annotation-driven Formatting

6.6.2.1. Format Annotation API

6.6.3. FormatterRegistry SPI6.6.4. FormatterRegistrar SPI6.6.5. Configuring Formatting in Spring MVC

6.7. Spring 3 Validation

6.7.1. Overview of the JSR-303 Bean Validation API6.7.2. Configuring a Bean Validation Implementation

6.7.2.1. Injecting a Validator6.7.2.2. Configuring Custom Constraints6.7.2.3. Additional Configuration Options

6.7.3. Configuring a DataBinder6.7.4. Spring MVC 3 Validation

6.7.4.1. Triggering @Controller Input Validation6.7.4.2. Configuring a Validator for use by Spring MVC6.7.4.3. Configuring a JSR-303 Validator for use by Spring MVC

7. Spring Expression Language (SpEL)

7.1. Introduction7.2. Feature Overview

Page 7: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 7/81

7.3. Expression Evaluation using Spring's Expression Interface

7.3.1. The EvaluationContext interface

7.3.1.1. Type Conversion

7.4. Expression support for defining bean definitions

7.4.1. XML based configuration7.4.2. Annotation-based configuration

7.5. Language Reference

7.5.1. Literal expressions7.5.2. Properties, Arrays, Lists, Maps, Indexers7.5.3. Inline lists7.5.4. Array construction7.5.5. Methods7.5.6. Operators

7.5.6.1. Relational operators7.5.6.2. Logical operators7.5.6.3. Mathematical operators

7.5.7. Assignment7.5.8. Types7.5.9. Constructors7.5.10. Variables

7.5.10.1. The #this and #root variables

7.5.11. Functions7.5.12. Bean references7.5.13. Ternary Operator (If-Then-Else)7.5.14. The Elvis Operator7.5.15. Safe Navigation operator7.5.16. Collection Selection7.5.17. Collection Projection7.5.18. Expression templating

7.6. Classes used in the examples

8. Aspect Oriented Programming with Spring

8.1. Introduction

8.1.1. AOP concepts8.1.2. Spring AOP capabilities and goals8.1.3. AOP Proxies

8.2. @AspectJ support

8.2.1. Enabling @AspectJ Support8.2.2. Declaring an aspect8.2.3. Declaring a pointcut

8.2.3.1. Supported Pointcut Designators8.2.3.2. Combining pointcut expressions8.2.3.3. Sharing common pointcut definitions8.2.3.4. Examples

Page 8: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 8/81

8.2.3.5. Writing good pointcuts

8.2.4. Declaring advice

8.2.4.1. Before advice8.2.4.2. After returning advice8.2.4.3. After throwing advice8.2.4.4. After (finally) advice8.2.4.5. Around advice8.2.4.6. Advice parameters8.2.4.7. Advice ordering

8.2.5. Introductions8.2.6. Aspect instantiation models8.2.7. Example

8.3. Schema-based AOP support

8.3.1. Declaring an aspect8.3.2. Declaring a pointcut8.3.3. Declaring advice

8.3.3.1. Before advice8.3.3.2. After returning advice8.3.3.3. After throwing advice8.3.3.4. After (finally) advice8.3.3.5. Around advice8.3.3.6. Advice parameters8.3.3.7. Advice ordering

8.3.4. Introductions8.3.5. Aspect instantiation models8.3.6. Advisors8.3.7. Example

8.4. Choosing which AOP declaration style to use

8.4.1. Spring AOP or full AspectJ?8.4.2. @AspectJ or XML for Spring AOP?

8.5. Mixing aspect types8.6. Proxying mechanisms

8.6.1. Understanding AOP proxies

8.7. Programmatic creation of @AspectJ Proxies8.8. Using AspectJ with Spring applications

8.8.1. Using AspectJ to dependency inject domain objects with Spring

8.8.1.1. Unit testing @Configurable objects8.8.1.2. Working with multiple application contexts

8.8.2. Other Spring aspects for AspectJ8.8.3. Configuring AspectJ aspects using Spring IoC8.8.4. Load-time weaving with AspectJ in the Spring Framework

8.8.4.1. A first example8.8.4.2. Aspects8.8.4.3. 'META-INF/aop.xml'

Page 9: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 9/81

8.8.4.4. Required libraries (JARS)8.8.4.5. Spring configuration8.8.4.6. Environment-specific configuration

8.9. Further Resources

9. Spring AOP APIs

9.1. Introduction9.2. Pointcut API in Spring

9.2.1. Concepts9.2.2. Operations on pointcuts9.2.3. AspectJ expression pointcuts9.2.4. Convenience pointcut implementations

9.2.4.1. Static pointcuts9.2.4.2. Dynamic pointcuts

9.2.5. Pointcut superclasses9.2.6. Custom pointcuts

9.3. Advice API in Spring

9.3.1. Advice lifecycles9.3.2. Advice types in Spring

9.3.2.1. Interception around advice9.3.2.2. Before advice9.3.2.3. Throws advice9.3.2.4. After Returning advice9.3.2.5. Introduction advice

9.4. Advisor API in Spring9.5. Using the ProxyFactoryBean to create AOP proxies

9.5.1. Basics9.5.2. JavaBean properties9.5.3. JDK- and CGLIB-based proxies9.5.4. Proxying interfaces9.5.5. Proxying classes9.5.6. Using 'global' advisors

9.6. Concise proxy definitions9.7. Creating AOP proxies programmatically with the ProxyFactory9.8. Manipulating advised objects9.9. Using the "autoproxy" facility

9.9.1. Autoproxy bean definitions

9.9.1.1. BeanNameAutoProxyCreator9.9.1.2. DefaultAdvisorAutoProxyCreator9.9.1.3. AbstractAdvisorAutoProxyCreator

9.9.2. Using metadata-driven auto-proxying

9.10. Using TargetSources

9.10.1. Hot swappable target sources9.10.2. Pooling target sources

Page 10: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 10/81

9.10.3. Prototype target sources9.10.4. ThreadLocal target sources

9.11. Defining new Advice types9.12. Further resources

10. Testing

10.1. Introduction to Spring Testing10.2. Unit Testing

10.2.1. Mock Objects

10.2.1.1. JNDI10.2.1.2. Servlet API10.2.1.3. Portlet API

10.2.2. Unit Testing support Classes

10.2.2.1. General utilities10.2.2.2. Spring MVC

10.3. Integration Testing

10.3.1. Overview10.3.2. Goals of Integration Testing

10.3.2.1. Context management and caching10.3.2.2. Dependency Injection of test fixtures10.3.2.3. Transaction management10.3.2.4. Support classes for integration testing

10.3.3. JDBC Testing Support10.3.4. Annotations

10.3.4.1. Spring Testing Annotations10.3.4.2. Standard Annotation Support10.3.4.3. Spring JUnit Testing Annotations

10.3.5. Spring TestContext Framework

10.3.5.1. Key abstractions10.3.5.2. Context management10.3.5.3. Dependency injection of test fixtures10.3.5.4. Transaction management10.3.5.5. TestContext support classes

10.3.6. PetClinic Example

10.4. Further Resources

IV. Data Access

11. Transaction Management

11.1. Introduction to Spring Framework transaction management11.2. Advantages of the Spring Framework's transaction support model

11.2.1. Global transactions11.2.2. Local transactions11.2.3. Spring Framework's consistent programming model

Page 11: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 11/81

11.3. Understanding the Spring Framework transaction abstraction11.4. Synchronizing resources with transactions

11.4.1. High-level synchronization approach11.4.2. Low-level synchronization approach11.4.3. TransactionAwareDataSourceProxy

11.5. Declarative transaction management

11.5.1. Understanding the Spring Framework's declarative transactionimplementation11.5.2. Example of declarative transaction implementation11.5.3. Rolling back a declarative transaction11.5.4. Configuring different transactional semantics for different beans11.5.5. <tx:advice/> settings11.5.6. Using @Transactional

11.5.6.1. @Transactional settings11.5.6.2. Multiple Transaction Managers with @Transactional11.5.6.3. Custom shortcut annotations

11.5.7. Transaction propagation

11.5.7.1. Required11.5.7.2. RequiresNew11.5.7.3. Nested

11.5.8. Advising transactional operations11.5.9. Using @Transactional with AspectJ

11.6. Programmatic transaction management

11.6.1. Using the TransactionTemplate

11.6.1.1. Specifying transaction settings

11.6.2. Using the PlatformTransactionManager

11.7. Choosing between programmatic and declarative transaction management11.8. Application server-specific integration

11.8.1. IBM WebSphere11.8.2. BEA WebLogic Server11.8.3. Oracle OC4J

11.9. Solutions to common problems

11.9.1. Use of the wrong transaction manager for a specific DataSource

11.10. Further Resources

12. DAO support

12.1. Introduction12.2. Consistent exception hierarchy12.3. Annotations used for configuring DAO or Repository classes

13. Data access with JDBC

13.1. Introduction to Spring Framework JDBC

Page 12: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 12/81

13.1.1. Choosing an approach for JDBC database access13.1.2. Package hierarchy

13.2. Using the JDBC core classes to control basic JDBC processing and errorhandling

13.2.1. JdbcTemplate

13.2.1.1. Examples of JdbcTemplate class usage13.2.1.2. JdbcTemplate best practices

13.2.2. NamedParameterJdbcTemplate13.2.3. SimpleJdbcTemplate13.2.4. SQLExceptionTranslator13.2.5. Executing statements13.2.6. Running queries13.2.7. Updating the database13.2.8. Retrieving auto-generated keys

13.3. Controlling database connections

13.3.1. DataSource13.3.2. DataSourceUtils13.3.3. SmartDataSource13.3.4. AbstractDataSource13.3.5. SingleConnectionDataSource13.3.6. DriverManagerDataSource13.3.7. TransactionAwareDataSourceProxy13.3.8. DataSourceTransactionManager13.3.9. NativeJdbcExtractor

13.4. JDBC batch operations

13.4.1. Basic batch operations with the JdbcTemplate13.4.2. Batch operations with a List of objects13.4.3. Batch operations with multiple batches

13.5. Simplifying JDBC operations with the SimpleJdbc classes

13.5.1. Inserting data using SimpleJdbcInsert13.5.2. Retrieving auto-generated keys using SimpleJdbcInsert13.5.3. Specifying columns for a SimpleJdbcInsert13.5.4. Using SqlParameterSource to provide parameter values13.5.5. Calling a stored procedure with SimpleJdbcCall13.5.6. Explicitly declaring parameters to use for a SimpleJdbcCall13.5.7. How to define SqlParameters13.5.8. Calling a stored function using SimpleJdbcCall13.5.9. Returning ResultSet/REF Cursor from a SimpleJdbcCall

13.6. Modeling JDBC operations as Java objects

13.6.1. SqlQuery13.6.2. MappingSqlQuery13.6.3. SqlUpdate13.6.4. StoredProcedure

13.7. Common problems with parameter and data value handling

13.7.1. Providing SQL type information for parameters13.7.2. Handling BLOB and CLOB objects

Page 13: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 13/81

13.7.3. Passing in lists of values for IN clause13.7.4. Handling complex types for stored procedure calls

13.8. Embedded database support

13.8.1. Why use an embedded database?13.8.2. Creating an embedded database instance using Spring XML13.8.3. Creating an embedded database instance programmatically13.8.4. Extending the embedded database support13.8.5. Using HSQL13.8.6. Using H213.8.7. Using Derby13.8.8. Testing data access logic with an embedded database

13.9. Initializing a DataSource

13.9.1. Initializing a database instance using Spring XML

13.9.1.1. Initialization of Other Components that Depend on the Database

14. Object Relational Mapping (ORM) Data Access

14.1. Introduction to ORM with Spring14.2. General ORM integration considerations

14.2.1. Resource and transaction management14.2.2. Exception translation

14.3. Hibernate

14.3.1. SessionFactory setup in a Spring container14.3.2. Implementing DAOs based on plain Hibernate 3 API14.3.3. Declarative transaction demarcation14.3.4. Programmatic transaction demarcation14.3.5. Transaction management strategies14.3.6. Comparing container-managed and locally defined resources14.3.7. Spurious application server warnings with Hibernate

14.4. JDO

14.4.1. PersistenceManagerFactory setup14.4.2. Implementing DAOs based on the plain JDO API14.4.3. Transaction management14.4.4. JdoDialect

14.5. JPA

14.5.1. Three options for JPA setup in a Spring environment

14.5.1.1. LocalEntityManagerFactoryBean14.5.1.2. Obtaining an EntityManagerFactory from JNDI14.5.1.3. LocalContainerEntityManagerFactoryBean14.5.1.4. Dealing with multiple persistence units

14.5.2. Implementing DAOs based on plain JPA14.5.3. Transaction Management14.5.4. JpaDialect

14.6. iBATIS SQL Maps

Page 14: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 14/81

14.6.1. Setting up the SqlMapClient14.6.2. Using SqlMapClientTemplate and SqlMapClientDaoSupport14.6.3. Implementing DAOs based on plain iBATIS API

15. Marshalling XML using O/X Mappers

15.1. Introduction15.2. Marshaller and Unmarshaller

15.2.1. Marshaller15.2.2. Unmarshaller15.2.3. XmlMappingException

15.3. Using Marshaller and Unmarshaller15.4. XML Schema-based Configuration15.5. JAXB

15.5.1. Jaxb2Marshaller

15.5.1.1. XML Schema-based Configuration

15.6. Castor

15.6.1. CastorMarshaller15.6.2. Mapping

15.7. XMLBeans

15.7.1. XmlBeansMarshaller

15.7.1.1. XML Schema-based Configuration

15.8. JiBX

15.8.1. JibxMarshaller

15.8.1.1. XML Schema-based Configuration

15.9. XStream

15.9.1. XStreamMarshaller

V. The Web

16. Web MVC framework

16.1. Introduction to Spring Web MVC framework

16.1.1. Features of Spring Web MVC16.1.2. Pluggability of other MVC implementations

16.2. The DispatcherServlet

16.2.1. Special Bean Types In the WebApplicationContext16.2.2. Default DispatcherServlet Configuration16.2.3. DispatcherServlet Processing Sequence

16.3. Implementing Controllers

16.3.1. Defining a controller with @Controller16.3.2. Mapping Requests With @RequestMapping

Page 15: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 15/81

16.3.2.1. New Support Classes for @RequestMapping methods in SpringMVC 3.116.3.2.2. URI Template Patterns16.3.2.3. URI Template Patterns with Regular Expressions16.3.2.4. Path Patterns16.3.2.5. Consumable Media Types16.3.2.6. Producible Media Types16.3.2.7. Request Parameters and Header Values

16.3.3. Defining @RequestMapping handler methods

16.3.3.1. Supported method argument types16.3.3.2. Supported method return types16.3.3.3. Binding request parameters to method parameters [email protected]. Mapping the request body with the @RequestBody annotation16.3.3.5. Mapping the response body with the @ResponseBodyannotation16.3.3.6. Using HttpEntity<?>16.3.3.7. Using @ModelAttribute on a method16.3.3.8. Using @ModelAttribute on a method argument16.3.3.9. Using @SessionAttributes to store model attributes in the HTTPsession between requests16.3.3.10. Specifying redirect and flash attributes16.3.3.11. Working with "application/x-www-form-urlencoded" data16.3.3.12. Mapping cookie values with the @CookieValue annotation16.3.3.13. Mapping request header attributes with the @RequestHeaderannotation16.3.3.14. Method Parameters And Type Conversion16.3.3.15. Customizing WebDataBinder initialization16.3.3.16. Support for the 'Last-Modified' Response Header To FacilitateContent Caching

16.4. Handler mappings

16.4.1. Intercepting requests with a HandlerInterceptor

16.5. Resolving views

16.5.1. Resolving views with the ViewResolver interface16.5.2. Chaining ViewResolvers16.5.3. Redirecting to views

16.5.3.1. RedirectView16.5.3.2. The redirect: prefix16.5.3.3. The forward: prefix

16.5.4. ContentNegotiatingViewResolver

16.6. Using flash attributes16.7. Building URIs16.8. Using locales

16.8.1. AcceptHeaderLocaleResolver16.8.2. CookieLocaleResolver16.8.3. SessionLocaleResolver16.8.4. LocaleChangeInterceptor

16.9. Using themes

Page 16: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 16/81

16.9.1. Overview of themes16.9.2. Defining themes16.9.3. Theme resolvers

16.10. Spring's multipart (file upload) support

16.10.1. Introduction16.10.2. Using a MultipartResolver with Commons FileUpload16.10.3. Using a MultipartResolver with Servlet 3.016.10.4. Handling a file upload in a form16.10.5. Handling a file upload request from programmatic clients

16.11. Handling exceptions

16.11.1. HandlerExceptionResolver16.11.2. @ExceptionHandler

16.12. Convention over configuration support

16.12.1. The Controller ControllerClassNameHandlerMapping16.12.2. The Model ModelMap (ModelAndView)16.12.3. The View - RequestToViewNameTranslator

16.13. ETag support16.14. Configuring Spring MVC

16.14.1. Enabling MVC Java Config or the MVC XML Namespace16.14.2. Customizing the Provided Configuration16.14.3. Configuring Interceptors16.14.4. Configuring View Controllers16.14.5. Configuring Serving of Resources16.14.6. mvc:default-servlet-handler16.14.7. More Spring Web MVC Resources16.14.8. Advanced Customizations with MVC Java Config16.14.9. Advanced Customizations with the MVC Namespace

17. View technologies

17.1. Introduction17.2. JSP & JSTL

17.2.1. View resolvers17.2.2. 'Plain-old' JSPs versus JSTL17.2.3. Additional tags facilitating development17.2.4. Using Spring's form tag library

17.2.4.1. Configuration17.2.4.2. The form tag17.2.4.3. The input tag17.2.4.4. The checkbox tag17.2.4.5. The checkboxes tag17.2.4.6. The radiobutton tag17.2.4.7. The radiobuttons tag17.2.4.8. The password tag17.2.4.9. The select tag17.2.4.10. The option tag17.2.4.11. The options tag17.2.4.12. The textarea tag17.2.4.13. The hidden tag17.2.4.14. The errors tag

Page 17: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 17/81

17.2.4.15. HTTP Method Conversion17.2.4.16. HTML5 Tags

17.3. Tiles

17.3.1. Dependencies17.3.2. How to integrate Tiles

17.3.2.1. UrlBasedViewResolver17.3.2.2. ResourceBundleViewResolver17.3.2.3. SimpleSpringPreparerFactory and SpringBeanPreparerFactory

17.4. Velocity & FreeMarker

17.4.1. Dependencies17.4.2. Context configuration17.4.3. Creating templates17.4.4. Advanced configuration

17.4.4.1. velocity.properties17.4.4.2. FreeMarker

17.4.5. Bind support and form handling

17.4.5.1. The bind macros17.4.5.2. Simple binding17.4.5.3. Form input generation macros17.4.5.4. HTML escaping and XHTML compliance

17.5. XSLT

17.5.1. My First Words

17.5.1.1. Bean definitions17.5.1.2. Standard MVC controller code17.5.1.3. Convert the model data to XML17.5.1.4. Defining the view properties17.5.1.5. Document transformation

17.5.2. Summary

17.6. Document views (PDF/Excel)

17.6.1. Introduction17.6.2. Configuration and setup

17.6.2.1. Document view definitions17.6.2.2. Controller code17.6.2.3. Subclassing for Excel views17.6.2.4. Subclassing for PDF views

17.7. JasperReports

17.7.1. Dependencies17.7.2. Configuration

17.7.2.1. Configuring the ViewResolver17.7.2.2. Configuring the Views17.7.2.3. About Report Files17.7.2.4. Using JasperReportsMultiFormatView

Page 18: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 18/81

17.7.3. Populating the ModelAndView17.7.4. Working with Sub-Reports

17.7.4.1. Configuring Sub-Report Files17.7.4.2. Configuring Sub-Report Data Sources

17.7.5. Configuring Exporter Parameters

17.8. Feed Views17.9. XML Marshalling View17.10. JSON Mapping View

18. Integrating with other web frameworks

18.1. Introduction18.2. Common configuration18.3. JavaServer Faces 1.1 and 1.2

18.3.1. DelegatingVariableResolver (JSF 1.1/1.2)18.3.2. SpringBeanVariableResolver (JSF 1.1/1.2)18.3.3. SpringBeanFacesELResolver (JSF 1.2+)18.3.4. FacesContextUtils

18.4. Apache Struts 1.x and 2.x

18.4.1. ContextLoaderPlugin

18.4.1.1. DelegatingRequestProcessor18.4.1.2. DelegatingActionProxy

18.4.2. ActionSupport Classes

18.5. WebWork 2.x18.6. Tapestry 3.x and 4.x

18.6.1. Injecting Spring-managed beans

18.6.1.1. Dependency Injecting Spring Beans into Tapestry pages18.6.1.2. Component definition files18.6.1.3. Adding abstract accessors18.6.1.4. Dependency Injecting Spring Beans into Tapestry pages -Tapestry 4.x style

18.7. Further Resources

19. Portlet MVC Framework

19.1. Introduction

19.1.1. Controllers - The C in MVC19.1.2. Views - The V in MVC19.1.3. Web-scoped beans

19.2. The DispatcherPortlet19.3. The ViewRendererServlet19.4. Controllers

19.4.1. AbstractController and PortletContentGenerator19.4.2. Other simple controllers19.4.3. Command Controllers19.4.4. PortletWrappingController

Page 19: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 19/81

19.5. Handler mappings

19.5.1. PortletModeHandlerMapping19.5.2. ParameterHandlerMapping19.5.3. PortletModeParameterHandlerMapping19.5.4. Adding HandlerInterceptors19.5.5. HandlerInterceptorAdapter19.5.6. ParameterMappingInterceptor

19.6. Views and resolving them19.7. Multipart (file upload) support

19.7.1. Using the PortletMultipartResolver19.7.2. Handling a file upload in a form

19.8. Handling exceptions19.9. Annotation-based controller configuration

19.9.1. Setting up the dispatcher for annotation support19.9.2. Defining a controller with @Controller19.9.3. Mapping requests with @RequestMapping19.9.4. Supported handler method arguments19.9.5. Binding request parameters to method parameters [email protected]. Providing a link to data from the model with @ModelAttribute19.9.7. Specifying attributes to store in a Session with @SessionAttributes19.9.8. Customizing WebDataBinder initialization

19.9.8.1. Customizing data binding with @InitBinder19.9.8.2. Configuring a custom WebBindingInitializer

19.10. Portlet application deployment

VI. Integration

20. Remoting and web services using Spring

20.1. Introduction20.2. Exposing services using RMI

20.2.1. Exporting the service using the RmiServiceExporter20.2.2. Linking in the service at the client

20.3. Using Hessian or Burlap to remotely call services via HTTP

20.3.1. Wiring up the DispatcherServlet for Hessian and co.20.3.2. Exposing your beans by using the HessianServiceExporter20.3.3. Linking in the service on the client20.3.4. Using Burlap20.3.5. Applying HTTP basic authentication to a service exposed throughHessian or Burlap

20.4. Exposing services using HTTP invokers

20.4.1. Exposing the service object20.4.2. Linking in the service at the client

20.5. Web services

20.5.1. Exposing servlet-based web services using JAX-RPC

Page 20: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 20/81

20.5.2. Accessing web services using JAX-RPC20.5.3. Registering JAX-RPC Bean Mappings20.5.4. Registering your own JAX-RPC Handler20.5.5. Exposing servlet-based web services using JAX-WS20.5.6. Exporting standalone web services using JAX-WS20.5.7. Exporting web services using the JAX-WS RI's Spring support20.5.8. Accessing web services using JAX-WS

20.6. JMS

20.6.1. Server-side configuration20.6.2. Client-side configuration

20.7. Auto-detection is not implemented for remote interfaces20.8. Considerations when choosing a technology20.9. Accessing RESTful services on the Client

20.9.1. RestTemplate

20.9.1.1. Working with the URI20.9.1.2. Dealing with request and response headers

20.9.2. HTTP Message Conversion

20.9.2.1. StringHttpMessageConverter20.9.2.2. FormHttpMessageConverter20.9.2.3. ByteArrayHttpMessageConverter20.9.2.4. MarshallingHttpMessageConverter20.9.2.5. MappingJacksonHttpMessageConverter20.9.2.6. SourceHttpMessageConverter20.9.2.7. BufferedImageHttpMessageConverter

21. Enterprise JavaBeans (EJB) integration

21.1. Introduction21.2. Accessing EJBs

21.2.1. Concepts21.2.2. Accessing local SLSBs21.2.3. Accessing remote SLSBs21.2.4. Accessing EJB 2.x SLSBs versus EJB 3 SLSBs

21.3. Using Spring's EJB implementation support classes

21.3.1. EJB 2.x base classes21.3.2. EJB 3 injection interceptor

22. JMS (Java Message Service)

22.1. Introduction22.2. Using Spring JMS

22.2.1. JmsTemplate22.2.2. Connections

22.2.2.1. Caching Messaging Resources22.2.2.2. SingleConnectionFactory22.2.2.3. CachingConnectionFactory

22.2.3. Destination Management

Page 21: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 21/81

22.2.4. Message Listener Containers

22.2.4.1. SimpleMessageListenerContainer22.2.4.2. DefaultMessageListenerContainer

22.2.5. Transaction management

22.3. Sending a Message

22.3.1. Using Message Converters22.3.2. SessionCallback and ProducerCallback

22.4. Receiving a message

22.4.1. Synchronous Reception22.4.2. Asynchronous Reception - Message-Driven POJOs22.4.3. The SessionAwareMessageListener interface22.4.4. The MessageListenerAdapter22.4.5. Processing messages within transactions

22.5. Support for JCA Message Endpoints22.6. JMS Namespace Support

23. JMX

23.1. Introduction23.2. Exporting your beans to JMX

23.2.1. Creating an MBeanServer23.2.2. Reusing an existing MBeanServer23.2.3. Lazy-initialized MBeans23.2.4. Automatic registration of MBeans23.2.5. Controlling the registration behavior

23.3. Controlling the management interface of your beans

23.3.1. The MBeanInfoAssembler Interface23.3.2. Using Source-Level Metadata (JDK 5.0 annotations)23.3.3. Source-Level Metadata Types23.3.4. The AutodetectCapableMBeanInfoAssembler interface23.3.5. Defining management interfaces using Java interfaces23.3.6. Using MethodNameBasedMBeanInfoAssembler

23.4. Controlling the ObjectNames for your beans

23.4.1. Reading ObjectNames from Properties23.4.2. Using the MetadataNamingStrategy23.4.3. The <context:mbean-export/> element

23.5. JSR-160 Connectors

23.5.1. Server-side Connectors23.5.2. Client-side Connectors23.5.3. JMX over Burlap/Hessian/SOAP

23.6. Accessing MBeans via Proxies23.7. Notifications

23.7.1. Registering Listeners for Notifications23.7.2. Publishing Notifications

Page 22: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 22/81

23.8. Further Resources

24. JCA CCI

24.1. Introduction24.2. Configuring CCI

24.2.1. Connector configuration24.2.2. ConnectionFactory configuration in Spring24.2.3. Configuring CCI connections24.2.4. Using a single CCI connection

24.3. Using Spring's CCI access support

24.3.1. Record conversion24.3.2. The CciTemplate24.3.3. DAO support24.3.4. Automatic output record generation24.3.5. Summary24.3.6. Using a CCI Connection and Interaction directly24.3.7. Example for CciTemplate usage

24.4. Modeling CCI access as operation objects

24.4.1. MappingRecordOperation24.4.2. MappingCommAreaOperation24.4.3. Automatic output record generation24.4.4. Summary24.4.5. Example for MappingRecordOperation usage24.4.6. Example for MappingCommAreaOperation usage

24.5. Transactions

25. Email

25.1. Introduction25.2. Usage

25.2.1. Basic MailSender and SimpleMailMessage usage25.2.2. Using the JavaMailSender and the MimeMessagePreparator

25.3. Using the JavaMail MimeMessageHelper

25.3.1. Sending attachments and inline resources

25.3.1.1. Attachments25.3.1.2. Inline resources

25.3.2. Creating email content using a templating library

25.3.2.1. A Velocity-based example

26. Task Execution and Scheduling

26.1. Introduction26.2. The Spring TaskExecutor abstraction

26.2.1. TaskExecutor types26.2.2. Using a TaskExecutor

26.3. The Spring TaskScheduler abstraction

Page 23: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 23/81

26.3.1. The Trigger interface26.3.2. Trigger implementations26.3.3. TaskScheduler implementations

26.4. The Task Namespace

26.4.1. The 'scheduler' element26.4.2. The 'executor' element26.4.3. The 'scheduled-tasks' element

26.5. Annotation Support for Scheduling and Asynchronous Execution

26.5.1. The @Scheduled Annotation26.5.2. The @Async Annotation26.5.3. The <annotation-driven> Element26.5.4. Executor qualification with @Async

26.6. Using the Quartz Scheduler

26.6.1. Using the JobDetailBean26.6.2. Using the MethodInvokingJobDetailFactoryBean26.6.3. Wiring up jobs using triggers and the SchedulerFactoryBean

27. Dynamic language support

27.1. Introduction27.2. A first example27.3. Defining beans that are backed by dynamic languages

27.3.1. Common concepts

27.3.1.1. The <lang:language/> element27.3.1.2. Refreshable beans27.3.1.3. Inline dynamic language source files27.3.1.4. Understanding Constructor Injection in the context of dynamic-language-backed beans

27.3.2. JRuby beans27.3.3. Groovy beans

27.3.3.1. Customising Groovy objects via a callback

27.3.4. BeanShell beans

27.4. Scenarios

27.4.1. Scripted Spring MVC Controllers27.4.2. Scripted Validators

27.5. Bits and bobs

27.5.1. AOP - advising scripted beans27.5.2. Scoping

27.6. Further Resources

28. Cache Abstraction

28.1. Introduction28.2. Understanding the cache abstraction28.3. Declarative annotation-based caching

Page 24: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 24/81

28.3.1. @Cacheable annotation

28.3.1.1. Default Key Generation28.3.1.2. Custom Key Generation Declaration28.3.1.3. Conditional caching28.3.1.4. Available caching SpEL evaluation context

28.3.2. @CachePut annotation28.3.3. @CacheEvict annotation28.3.4. @Caching annotation28.3.5. Enable caching annotations28.3.6. Using custom annotations

28.4. Declarative XML-based caching28.5. Configuring the cache storage

28.5.1. JDK ConcurrentMap-based Cache28.5.2. Ehcache-based Cache28.5.3. Dealing with caches without a backing store

28.6. Plugging-in different back-end caches28.7. How can I set the TTL/TTI/Eviction policy/XXX feature?

VII. Appendices

A. Classic Spring Usage

A.1. Classic ORM usage

A.1.1. Hibernate

A.1.1.1. The HibernateTemplateA.1.1.2. Implementing Spring-based DAOs without callbacks

A.1.2. JDO

A.1.2.1. JdoTemplate and JdoDaoSupport

A.1.3. JPA

A.1.3.1. JpaTemplate and JpaDaoSupport

A.2. Classic Spring MVCA.3. JMS Usage

A.3.1. JmsTemplateA.3.2. Asynchronous Message ReceptionA.3.3. ConnectionsA.3.4. Transaction Management

B. Migrating to Spring Framework 3.1

B.1. Component scanning against the "org" base package

C. Classic Spring AOP Usage

C.1. Pointcut API in Spring

C.1.1. ConceptsC.1.2. Operations on pointcutsC.1.3. AspectJ expression pointcuts

Page 25: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 25/81

C.1.4. Convenience pointcut implementations

C.1.4.1. Static pointcutsC.1.4.2. Dynamic pointcuts

C.1.5. Pointcut superclassesC.1.6. Custom pointcuts

C.2. Advice API in Spring

C.2.1. Advice lifecyclesC.2.2. Advice types in Spring

C.2.2.1. Interception around adviceC.2.2.2. Before adviceC.2.2.3. Throws adviceC.2.2.4. After Returning adviceC.2.2.5. Introduction advice

C.3. Advisor API in SpringC.4. Using the ProxyFactoryBean to create AOP proxies

C.4.1. BasicsC.4.2. JavaBean propertiesC.4.3. JDK- and CGLIB-based proxiesC.4.4. Proxying interfacesC.4.5. Proxying classesC.4.6. Using 'global' advisors

C.5. Concise proxy definitionsC.6. Creating AOP proxies programmatically with the ProxyFactoryC.7. Manipulating advised objectsC.8. Using the "autoproxy" facility

C.8.1. Autoproxy bean definitions

C.8.1.1. BeanNameAutoProxyCreatorC.8.1.2. DefaultAdvisorAutoProxyCreatorC.8.1.3. AbstractAdvisorAutoProxyCreator

C.8.2. Using metadata-driven auto-proxying

C.9. Using TargetSources

C.9.1. Hot swappable target sourcesC.9.2. Pooling target sourcesC.9.3. Prototype target sourcesC.9.4. ThreadLocal target sources

C.10. Defining new Advice typesC.11. Further resources

D. XML Schema-based configuration

D.1. IntroductionD.2. XML Schema-based configuration

D.2.1. Referencing the schemasD.2.2. The util schema

Page 26: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 26/81

D.2.2.1. <util:constant/>D.2.2.2. <util:property-path/>D.2.2.3. <util:properties/>D.2.2.4. <util:list/>D.2.2.5. <util:map/>D.2.2.6. <util:set/>

D.2.3. The jee schema

D.2.3.1. <jee:jndi-lookup/> (simple)D.2.3.2. <jee:jndi-lookup/> (with single JNDI environment setting)D.2.3.3. <jee:jndi-lookup/> (with multiple JNDI environment settings)D.2.3.4. <jee:jndi-lookup/> (complex)D.2.3.5. <jee:local-slsb/> (simple)D.2.3.6. <jee:local-slsb/> (complex)D.2.3.7. <jee:remote-slsb/>

D.2.4. The lang schemaD.2.5. The jms schemaD.2.6. The tx (transaction) schemaD.2.7. The aop schemaD.2.8. The context schema

D.2.8.1. <property-placeholder/>D.2.8.2. <annotation-config/>D.2.8.3. <component-scan/>D.2.8.4. <load-time-weaver/>D.2.8.5. <spring-configured/>D.2.8.6. <mbean-export/>

D.2.9. The tool schemaD.2.10. The beans schema

E. Extensible XML authoring

E.1. IntroductionE.2. Authoring the schemaE.3. Coding a NamespaceHandlerE.4. Coding a BeanDefinitionParserE.5. Registering the handler and the schema

E.5.1. 'META-INF/spring.handlers'E.5.2. 'META-INF/spring.schemas'

E.6. Using a custom extension in your Spring XML configurationE.7. Meatier examples

E.7.1. Nesting custom tags within custom tagsE.7.2. Custom attributes on 'normal' elements

E.8. Further Resources

F. spring-beans-2.0.dtdG. spring.tld

G.1. IntroductionG.2. The bind tagG.3. The escapeBody tagG.4. The hasBindErrors tagG.5. The htmlEscape tag

Page 27: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 27/81

G.6. The message tagG.7. The nestedPath tagG.8. The theme tagG.9. The transform tagG.10. The url tagG.11. The eval tag

H. spring-form.tld

H.1. IntroductionH.2. The checkbox tagH.3. The checkboxes tagH.4. The errors tagH.5. The form tagH.6. The hidden tagH.7. The input tagH.8. The label tagH.9. The option tagH.10. The options tagH.11. The password tagH.12. The radiobutton tagH.13. The radiobuttons tagH.14. The select tagH.15. The textarea tag

Part I. Overview of Spring Framework

The Spring Framework is a lightweight solution and a potential one-stop-shop for building yourenterprise-ready applications. However, Spring is modular, allowing you to use only those partsthat you need, without having to bring in the rest. You can use the IoC container, with Struts on top,but you can also use only the Hibernate integration code or the JDBC abstraction layer. TheSpring Framework supports declarative transaction management, remote access to your logicthrough RMI or web services, and various options for persisting your data. It offers a full-featuredMVC 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 nodependencies 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, itshould 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 or on thesupport forums at http://forum.springsource.org/.

1. Introduction to Spring Framework

Spring Framework is a Java platform that provides comprehensive infrastructure support fordeveloping Java applications. Spring handles the infrastructure so you can focus on yourapplication.

Spring enables you to build applications from “plain old Java objects” (POJOs) and to applyenterprise services non-invasively to POJOs. This capability applies to the Java SEprogramming model and to full and partial Java EE.

Examples of how you, as an application developer, can use the Spring platform advantage:

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

Page 28: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 28/81

Background

“The question is, what aspect ofcontrol are [they] inverting?” MartinFowler posed this question aboutInversion of Control (IoC) on hissite in 2004. Fowler suggestedrenaming the principle to make itmore self-explanatory and cameup with Dependency Injection.

For insight into IoC and DI, refer toFowler's article athttp://martinfowler.com/articles/injection.html.

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.

1.1 Dependency Injection and Inversion of Control

Java applications -- a loose term that runs the gamutfrom constrained applets to n-tier server-sideenterprise applications -- typically consist of objectsthat collaborate to form the application proper. Thus

the objects in an application have dependencies oneach other.

Although the Java platform provides a wealth ofapplication development functionality, it lacks themeans to organize the basic building blocks into acoherent whole, leaving that task to architects anddevelopers. True, you can use design patterns such asFactory, Abstract Factory, Builder, Decorator, and

Service Locator to compose the various classes andobject instances that make up an application.However, these patterns are simply that: bestpractices 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 mustimplement yourself in your application.

The Spring Framework Inversion of Control (IoC) component addresses this concern byproviding a formalized means of composing disparate components into a fully workingapplication 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, maintainableapplications.

1.2 Modules

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

Page 29: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 29/81

Overview of the Spring Framework

1.2.1 Core Container

The Core Container consists of the Core, Beans, Context, and Expression Language modules.

The Core and Beans modules provide the fundamental parts of the framework, including the IoCand Dependency Injection features. The BeanFactory is a sophisticated implementation of thefactory pattern. It removes the need for programmatic singletons and allows you to decouple theconfiguration and specification of dependencies from your actual program logic.

The Context module builds on the solid base provided by the Core and Beans modules: it is ameans to access objects in a framework-style manner that is similar to a JNDI registry. TheContext module inherits its features from the Beans module and adds support forinternationalization (using, for example, resource bundles), event-propagation, resource-loading,and the transparent creation of contexts by, for example, a servlet container. The Context modulealso supports Java EE features such as EJB, JMX ,and basic remoting. TheApplicationContext interface is the focal point of the Context module.

The Expression Language module provides a powerful expression language for querying andmanipulating 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 gettingproperty values, property assignment, method invocation, accessing the context of arrays,collections and indexers, logical and arithmetic operators, named variables, and retrieval ofobjects by name from Spring's IoC container. It also supports list projection and selection as wellas common list aggregations.

1.2.2 Data Access/Integration

Page 30: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 30/81

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

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

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

The OXM module provides an abstraction layer that supports Object/XML mappingimplementations for JAXB, Castor, XMLBeans, JiBX and XStream.

The Java Messaging Service (JMS) module contains features for producing and consumingmessages.

The Transaction module supports programmatic and declarative transaction management forclasses that implement special interfaces and for all your POJOs (plain old Java objects).

1.2.3 Web

The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules.

Spring's 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 the web-related parts of Spring's remoting support.

The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for webapplications. Spring's MVC framework provides a clean separation between domain model codeand web forms, and integrates with all the other features of the Spring Framework.

The Web-Struts module contains the support classes for integrating a classic Struts web tierwithin a Spring application. Note that this support is now deprecated as of Spring 3.0. Considermigrating your application to Struts 2.0 and its Spring integration or to a Spring MVC solution.

The Web-Portlet module provides the MVC implementation to be used in a portlet environmentand mirrors the functionality of Web-Servlet module.

1.2.4 AOP and Instrumentation

Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programmingimplementation allowing you to define, for example, method-interceptors and pointcuts to cleanlydecouple code that implements functionality that should be separated. Using source-levelmetadata functionality, you can also incorporate behavioral information into your code, in amanner similar to that of .NET attributes.

The separate Aspects module provides integration with AspectJ.

The Instrumentation module provides class instrumentation support and classloaderimplementations to be used in certain application servers.

1.2.5 Test

The Test module supports the testing of Spring components with JUnit or TestNG. It providesconsistent loading of Spring ApplicationContexts and caching of those contexts. It also providesmock objects that you can use to test your code in isolation.

Page 31: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 31/81

1.3 Usage scenarios

The building blocks described previously make Spring a logical choice in many scenarios, fromapplets to full-fledged enterprise applications that use Spring's transaction managementfunctionality and web framework integration.

Typical full-fledged Spring web application

Spring's declarative transaction management features make the web application fullytransactional, just as it would be if you used EJB container-managed transactions. All yourcustom business logic can be implemented with simple POJOs and managed by Spring's IoCcontainer. Additional services include support for sending email and validation that isindependent of the web layer, which lets you choose where to execute validation rules. Spring'sORM support is integrated with JPA, Hibernate, JDO and iBatis; for example, when usingHibernate, you can continue to use your existing mapping files and standard HibernateSessionFactory configuration. Form controllers seamlessly integrate the web-layer with thedomain model, removing the need for ActionForms or other classes that transform HTTPparameters to values for your domain model.

Page 32: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 32/81

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-nothingsolution. Existing front-ends built with WebWork, Struts, Tapestry, or other UI frameworks can beintegrated 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 aWebApplicationContext to integrate your web layer.

Page 33: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 33/81

Remoting usage scenario

When you need to access existing code through web services, you can use Spring's Hessian-,Burlap-, Rmi- or JaxRpcProxyFactory classes. Enabling remote access to existing applicationsis not difficult.

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 inscalable, fail-safe web applications that might need declarative security.

1.3.1 Dependency Management and Naming Conventions

Dependency management and dependency injection are different things. To get those nicefeatures of Spring into your application (like dependency injection) you need to assemble all thelibraries needed (jar files) and get them onto your classpath at runtime, and possibly at compiletime. These dependencies are not virtual components that are injected, but physical resources ina file system (typically). The process of dependency management involves locating thoseresources, storing them and adding them to classpaths. Dependencies can be direct (e.g. myapplication depends on Spring at runtime), or indirect (e.g. my application depends on commons-

Page 34: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 34/81

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 piecesof Spring that you need. To make this easier Spring is packaged as a set of modules thatseparate the dependencies as much as possible, so for example if you don't want to write a webapplication you don't need the spring-web modules. To refer to Spring library modules in thisguide we use a shorthand naming convention spring-* or spring-*.jar, where "*" representsthe short name for the module (e.g. spring-core, spring-webmvc, spring-jms, etc.). The actualjar file name that you use may be in this form (see below) or it may not, and normally it also has aversion number in the file name (e.g. spring-core-3.0.0.RELEASE.jar).

In general, Spring publishes its artifacts to four different places:

On the community download site http://www.springsource.org/download/community. Hereyou find all the Spring jars bundled together into a zip file for easy download. The names ofthe jars here since version 3.0 are in the form org.springframework.*-<version>.jar.

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

The Enterprise Bundle Repository (EBR), which is run by SpringSource and also hosts allthe libraries that integrate with Spring. Both Maven and Ivy repositories are available herefor all Spring jars and their dependencies, plus a large number of other common librariesthat people use in applications with Spring. Both full releases and also milestones anddevelopment snapshots are deployed here. The names of the jar files are in the same formas the community download (org.springframework.*-<version>.jar), and thedependencies are also in this "long" form, with external libraries (not from SpringSource)having the prefix com.springsource. See the FAQ for more information.

In a public Maven repository hosted on Amazon S3 for development snapshots andmilestone releases (a copy of the final releases is also held here). The jar file names are inthe same form as Maven Central, so this is a useful place to get development versions ofSpring to use with other libraries depoyed in Maven Central.

So the first thing you need to decide is how to manage your dependencies: most people use anautomated system like Maven or Ivy, but you can also do it manually by downloading all the jarsyourself. When obtaining Spring with Maven or Ivy you have then to decide which place you'll get itfrom. In general, if you care about OSGi, use the EBR, since it houses OSGi compatible artifactsfor all of Spring's dependencies, such as Hibernate and Freemarker. If OSGi does not matter toyou, either place works, though there are some pros and cons between them. In general, pick oneplace or the other for your project; do not mix them. This is particularly important since EBRartifacts necessarily use a different naming convention than Maven Central artifacts.

Table 1.1. Comparison of Maven Central and SpringSource EBR Repositories

Feature Maven Central EBR

OSGiCompatible

Not explicit Yes

Number ofArtifacts

Tens of thousands; all kindsHundreds; those that Spring integrateswith

ConsistentNamingConventions

No Yes

Page 35: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 35/81

NamingConvention:GroupId

Varies. Newer artifacts oftenuse domain name, e.g.org.slf4j. Older ones often justuse the artifact name, e.g.log4j.

Domain name of origin or mainpackage root, e.g. org.springframework

NamingConvention:ArtifactId

Varies. Generally the projector module name, using ahyphen "-" separator, e.g.spring-core, logj4.

Bundle Symbolic Name, derived fromthe main package root, e.g.org.springframework.beans. If the jarhad to be patched to ensure OSGicompliance then com.springsource isappended, e.g.com.springsource.org.apache.log4j

NamingConvention:Version

Varies. Many new artifactsuse m.m.m or m.m.m.X (withm=digit, X=text). Older onesuse m.m. Some neither.Ordering is defined but notoften relied on, so not strictlyreliable.

OSGi version number m.m.m.X, e.g.3.0.0.RC3. The text qualifier imposesalphabetic ordering on versions with thesame numeric values.

Publishing

Usually automatic via rsync orsource control updates.Project authors can uploadindividual jars to JIRA.

Manual (JIRA processed bySpringSource)

QualityAssurance

By policy. Accuracy isresponsibility of authors.

Extensive for OSGi manifest, MavenPOM and Ivy metadata. QA performedby Spring team.

HostingContegix. Funded bySonatype with severalmirrors.

S3 funded by SpringSource.

SearchUtilities

Various http://www.springsource.com/repository

IntegrationwithSpringSourceTools

Integration through STS withMaven dependencymanagement

Extensive integration through STS withMaven, Roo, CloudFoundry

1.3.1.1 Spring Dependencies and Depending on Spring

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

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

1.3.1.2 Maven Dependency Management

If you are using Maven for dependency management you don't even need to supply the loggingdependency explicitly. For example, to create an application context and use dependency

Page 36: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 36/81

injection to configure an application, your Maven dependencies will look like this:

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.0.0.RELEASE</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 SpringAPIs, which is typically the case for basic dependency injection use cases.

We used the Maven Central naming conventions in the example above, so that works with MavenCentral or the SpringSource S3 Maven repository. To use the S3 Maven repository (e.g. formilestones or developer snaphots), you need to specify the repository location in your Mavenconfiguration. For full releases:

<repositories> <repository> <id>com.springsource.repository.maven.release</id> <url>http://maven.springframework.org/release/</url> <snapshots><enabled>false</enabled></snapshots> </repository></repositories>

For milestones:

<repositories> <repository> <id>com.springsource.repository.maven.milestone</id> <url>http://maven.springframework.org/milestone/</url> <snapshots><enabled>false</enabled></snapshots> </repository></repositories>

And for snapshots:

<repositories> <repository> <id>com.springsource.repository.maven.snapshot</id> <url>http://maven.springframework.org/snapshot/</url> <snapshots><enabled>true</enabled></snapshots> </repository></repositories>

To use the SpringSource EBR you would need to use a different naming convention for thedependencies. The names are usually easy to guess, e.g. in this case it is:

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.context</artifactId> <version>3.0.0.RELEASE</version> <scope>runtime</scope> </dependency></dependencies>

You also need to declare the location of the repository explicitly (only the URL is important):

<repositories> <repository> <id>com.springsource.repository.bundles.release</id> <url>http://repository.springsource.com/maven/bundles/release/</url> </repository></repositories>

Page 37: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 37/81

If you are managing your dependencies by hand, the URL in the repository declaration above isnot browseable, but there is a user interface at http://www.springsource.com/repository that canbe used to search for and download dependencies. It also has handy snippets of Maven and Ivyconfiguration that you can copy and paste if you are using those tools.

1.3.1.3 Ivy Dependency Management

If you prefer to use Ivy to manage dependencies then there are similar names and configurationoptions.

To configure Ivy to point to the SpringSource EBR add the following resolvers to yourivysettings.xml:

<resolvers> <url name="com.springsource.repository.bundles.release">

<ivy pattern="http://repository.springsource.com/ivy/bundles/release/ [organisation]/[module]/[revision]/[artifact]-[revision].[ext]" /> <artifact pattern="http://repository.springsource.com/ivy/bundles/release/ [organisation]/[module]/[revision]/[artifact]-[revision].[ext]" />

</url>

<url name="com.springsource.repository.bundles.external">

<ivy pattern="http://repository.springsource.com/ivy/bundles/external/ [organisation]/[module]/[revision]/[artifact]-[revision].[ext]" /> <artifact pattern="http://repository.springsource.com/ivy/bundles/external/ [organisation]/[module]/[revision]/[artifact]-[revision].[ext]" />

</url>

</resolvers>

The XML above is not valid because the lines are too long - if you copy-paste then remove theextra line endings in the middle of the url patterns.

Once Ivy is configured to look in the EBR adding a dependency is easy. Simply pull up the detailspage for the bundle in question in the repository browser and you'll find an Ivy snippet ready foryou to include in your dependencies section. For example (in ivy.xml):

<dependency org="org.springframework" name="org.springframework.core" rev="3.0.0.RELEASE" conf="compile->runtime"/>

1.3.2 Logging

Logging is a very important dependency for Spring because a) it is the only mandatory externaldependency, b) everyone likes to see some output from the tools they are using, and c) Springintegrates 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 acentral place for the whole application, including all external components. This is more difficultthan 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). Wecompile against JCL and we also make JCL Log objects visible for classes that extend theSpring 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 thatextend Spring. The way we do this is to make one of the modules in Spring depend explicitly oncommons-logging (the canonical implementation of JCL), and then make all the other modulesdepend on that at compile time. If you are using Maven for example, and wondering where youpicked up the dependency on commons-logging, then it is from Spring and specifically from thecentral module called spring-core.

Page 38: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 38/81

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

1.3.2.1 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 woulduse a different logging dependency. The first choice would probably be the Simple LoggingFacade for Java (SLF4J), which is also used by a lot of other tools that people use with Springinside their applications.

Switching off commons-logging is easy: just make sure it isn't on the classpath at runtime. InMaven terms you exclude the dependency, and because of the way that the Spring dependenciesare declared, you only have to do that once.

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.0.0.RELEASE</version> <scope>runtime</scope> <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 onthe classpath, so to fix it a new one has to be provided. In the next section we show you how toprovide an alternative implementation of JCL using SLF4J as an example.

1.3.2.2 Using SLF4J

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

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

A common choice might be to bridge Spring to SLF4J, and then provide explicit binding fromSLF4J 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

<dependencies> <dependency> <groupId>org.springframework</groupId>

Page 39: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 39/81

<artifactId>spring-context</artifactId> <version>3.0.0.RELEASE</version> <scope>runtime</scope> <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> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.5.8</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.8</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> <scope>runtime</scope> </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 performancebenefit because the bindings are at compile-time not runtime.

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

1.3.2.3 Using Log4J

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

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

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.0.0.RELEASE</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> <scope>runtime</scope> </dependency>

Page 40: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 40/81

Java SE and Java EE Support

The Spring Framework is nowbased on Java 5, and Java 6 isfully supported.

Furthermore, Spring is compatiblewith J2EE 1.4 and Java EE 5, whileat the same time introducing someearly support for Java EE 6.

</dependencies>

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

log4j.rootCategory=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.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 ofJCL. 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 yourapplication is not enough in most situations.

To be clear about this: the problems reported are usually not with JCL per se, or even withcommons-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 runtimediscovery in between the older versions (1.0) found in some containers and the modern versionsthat most people use now (1.1). Spring does not use any unusual parts of the JCL API, so nothingbreaks there, but as soon as Spring or your application tries to do any logging you can find thatthe 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 optionisn't always open, but there are plenty of other suggestions in the public domain for alternativeapproaches, and your mileage may vary depending on the exact version and feature set of thecontainer.

Part II. What's New in Spring 3

2. New Features and Enhancements in Spring 3.0

If you have been using the Spring Framework for some time, you will be aware that Spring hasundergone two major revisions: Spring 2.0, released in October 2006, and Spring 2.5, releasedin November 2007. It is now time for a third overhaul resulting in Spring 3.0.

2.1 Java 5

The entire framework code has been revised to take advantage of Java 5 features like generics,

Page 41: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 41/81

varargs and other language improvements. We have done our best to still keep the codebackwards compatible. We now have consistent use of generic Collections and Maps, consistentuse of generic FactoryBeans, and also consistent resolution of bridge methods in the SpringAOP API. Generic ApplicationListeners automatically receive specific event types only. Allcallback interfaces such as TransactionCallback and HibernateCallback declare a generic resultvalue now. Overall, the Spring core codebase is now freshly revised and optimized for Java 5.

Spring's TaskExecutor abstraction has been updated for close integration with Java 5'sjava.util.concurrent facilities. We provide first-class support for Callables and Futures now, as wellas ExecutorService adapters, ThreadFactory integration, etc. This has been aligned with JSR-236 (Concurrency Utilities for Java EE 6) as far as possible. Furthermore, we provide support forasynchronous method invocations through the use of the new @Async annotation (or EJB 3.1's@Asynchronous annotation).

2.2 Improved documentation

The Spring reference documentation has also substantially been updated to reflect all of thechanges and new features for Spring 3.0. While every effort has been made to ensure that thereare no errors in this documentation, some errors may nevertheless have crept in. If you do spotany typos or even more serious errors, and you can spare a few cycles during lunch, please dobring the error to the attention of the Spring team by raising an issue.

2.3 New articles and tutorials

There are many excellent articles and tutorials that show how to get started with Spring 3features. Read them at the Spring Documentation page.

The samples have been improved and updated to take advantage of the new features in Spring3. Additionally, the samples have been moved out of the source tree into a dedicated SVNrepository available at:

https://anonsvn.springframework.org/svn/spring-samples/

As such, the samples are no longer distributed alongside Spring 3 and need to be downloadedseparately from the repository mentioned above. However, this documentation will continue torefer to some samples (in particular Petclinic) to illustrate various features.

Note

For more information on Subversion (or in short SVN), see the projecthomepage at: http://subversion.apache.org/

2.4 New module organization and build system

The framework modules have been revised and are now managed separately with one source-tree per module jar:

org.springframework.aop

org.springframework.beans

org.springframework.context

org.springframework.context.support

org.springframework.expression

org.springframework.instrument

Page 42: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 42/81

Note:

The spring.jar artifact thatcontained almost the entireframework is no longer provided.

org.springframework.jdbc

org.springframework.jms

org.springframework.orm

org.springframework.oxm

org.springframework.test

org.springframework.transaction

org.springframework.web

org.springframework.web.portlet

org.springframework.web.servlet

org.springframework.web.struts

We are now using a new Spring build system asknown from Spring Web Flow 2.0. This gives us:

Ivy-based "Spring Build" system

consistent deployment procedure

consistent dependency management

consistent generation of OSGi manifests

2.5 Overview of new features

This is a list of new features for Spring 3.0. We will cover these features in more detail later in thissection.

Spring Expression Language

IoC enhancements/Java based bean metadata

General-purpose type conversion system and field formatting system

Object to XML mapping functionality (OXM) moved from Spring Web Services project

Comprehensive REST support

@MVC additions

Declarative model validation

Early support for Java EE 6

Embedded database support

2.5.1 Core APIs updated for Java 5

BeanFactory interface returns typed bean instances as far as possible:

T getBean(Class<T> requiredType)

T getBean(String name, Class<T> requiredType)

Page 43: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 43/81

Map<String, T> getBeansOfType(Class<T> type)

Spring's TaskExecutor interface now extends java.util.concurrent.Executor:

extended AsyncTaskExecutor supports standard Callables with Futures

New Java 5 based converter API and SPI:

stateless ConversionService and Converters

superseding standard JDK PropertyEditors

Typed ApplicationListener<E>

2.5.2 Spring Expression Language

Spring introduces an expression language which is similar to Unified EL in its syntax but offerssignificantly more features. The expression language can be used when defining XML andAnnotation based bean definitions and also serves as the foundation for expression languagesupport across the Spring portfolio. Details of this new functionality can be found in the chapterSpring Expression Language (SpEL).

The Spring Expression Language was created to provide the Spring community a single, wellsupported expression language that can be used across all the products in the Spring portfolio.Its language features are driven by the requirements of the projects in the Spring portfolio,including tooling requirements for code completion support within the Eclipse basedSpringSource Tool Suite.

The following is an example of how the Expression Language can be used to configure someproperties of a database setup

<bean class="mycompany.RewardsTestDatabase"> <property name="databaseName" value="#{systemProperties.databaseName}"/> <property name="keyGenerator" value="#{strategyBean.databaseKeyGenerator}"/></bean>

This functionality is also available if you prefer to configure your components using annotations:

@Repository public class RewardsTestDatabase {

@Value("#{systemProperties.databaseName}") public void setDatabaseName(String dbName) { … }

@Value("#{strategyBean.databaseKeyGenerator}") public void setKeyGenerator(KeyGenerator kg) { … }}

2.5.3 The Inversion of Control (IoC) container

2.5.3.1 Java based bean metadata

Some core features from the JavaConfig project have been added to the Spring Framework now.This means that the following annotations are now directly supported:

@Configuration

@Bean

@DependsOn

Page 44: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 44/81

@Primary

@Lazy

@Import

@ImportResource

@Value

Here is an example of a Java class providing basic configuration using the new JavaConfigfeatures:

package org.example.config;

@Configurationpublic class AppConfig { private @Value("#{jdbcProperties.url}") String jdbcUrl; private @Value("#{jdbcProperties.username}") String username; private @Value("#{jdbcProperties.password}") String password;

@Bean public FooService fooService() { return new FooServiceImpl(fooRepository()); }

@Bean public FooRepository fooRepository() { return new HibernateFooRepository(sessionFactory()); }

@Bean public SessionFactory sessionFactory() { // wire up a session factory AnnotationSessionFactoryBean asFactoryBean = new AnnotationSessionFactoryBean(); asFactoryBean.setDataSource(dataSource()); // additional config return asFactoryBean.getObject(); }

@Bean public DataSource dataSource() { return new DriverManagerDataSource(jdbcUrl, username, password); }}

To get this to work you need to add the following component scanning entry in your minimalapplication context XML file.

<context:component-scan base-package="org.example.config"/><util:properties id="jdbcProperties" location="classpath:org/example/config/jdbc.properties"/>

Or you can bootstrap a @Configuration class directly usingAnnotationConfigApplicationContext:

public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); FooService fooService = ctx.getBean(FooService.class); fooService.doStuff();}

See Section 4.12.2, “Instantiating the Spring container usingAnnotationConfigApplicationContext” for full information onAnnotationConfigApplicationContext.

2.5.3.2 Defining bean metadata within components

Page 45: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 45/81

@Bean annotated methods are also supported inside Spring components. They contribute afactory bean definition to the container. See Defining bean metadata within components for moreinformation

2.5.4 General purpose type conversion system and field formattingsystem

A general purpose type conversion system has been introduced. The system is currently used bySpEL for type conversion, and may also be used by a Spring Container and DataBinder whenbinding bean property values.

In addition, a formatter SPI has been introduced for formatting field values. This SPI provides asimpler and more robust alternative to JavaBean PropertyEditors for use in client environmentssuch as Spring MVC.

2.5.5 The Data Tier

Object to XML mapping functionality (OXM) from the Spring Web Services project has beenmoved to the core Spring Framework now. The functionality is found in theorg.springframework.oxm package. More information on the use of the OXM module can be foundin the Marshalling XML using O/X Mappers chapter.

2.5.6 The Web Tier

The most exciting new feature for the Web Tier is the support for building RESTful web servicesand web applications. There are also some new annotations that can be used in any webapplication.

2.5.6.1 Comprehensive REST support

Server-side support for building RESTful applications has been provided as an extension of theexisting annotation driven MVC web framework. Client-side support is provided by theRestTemplate class in the spirit of other template classes such as JdbcTemplate andJmsTemplate. Both server and client side REST functionality make use of HttpConverters tofacilitate the conversion between objects and their representation in HTTP requests andresponses.

The MarshallingHttpMessageConverter uses the Object to XML mapping functionalitymentioned earlier.

Refer to the sections on MVC and the RestTemplate for more information.

2.5.6.2 @MVC additions

A mvc namespace has been introduced that greatly simplifies Spring MVC configuration.

Additional annotations such as @CookieValue and @RequestHeaders have been added. SeeMapping cookie values with the @CookieValue annotation and Mapping request headerattributes with the @RequestHeader annotation for more information.

2.5.7 Declarative model validation

Several validation enhancements, including JSR 303 support that uses Hibernate Validator asthe default provider.

2.5.8 Early support for Java EE 6

Page 46: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 46/81

We provide support for asynchronous method invocations through the use of the new @Asyncannotation (or EJB 3.1's @Asynchronous annotation).

JSR 303, JSF 2.0, JPA 2.0, etc

2.5.9 Support for embedded databases

Convenient support for embedded Java database engines, including HSQL, H2, and Derby, isnow provided.

3. New Features and Enhancements in Spring 3.1

Building on the support introduced in Spring 3.0, Spring 3.1 is currently under development, andat the time of this writing Spring 3.1 RC1 is being prepared for release.

3.1 Overview of new features

This is a list of new features for Spring 3.1. Most features do not yet have dedicated referencedocumentation but do have Javadoc. In such cases, fully-qualified class names are given. Seealso Appendix B, Migrating to Spring Framework 3.1

3.1.1 Cache Abstraction

Chapter 28, Cache Abstraction

Cache Abstraction (SpringSource team blog)

3.1.2 Bean Definition Profiles

XML profiles (SpringSource Team Blog)

Introducing @Profile (SpringSource Team Blog)

See org.springframework.context.annotation.Configuration Javadoc

See org.springframework.context.annotation.Profile Javadoc

3.1.3 Environment Abstraction

Environment Abstraction (SpringSource Team Blog)

See org.springframework.core.env.Environment Javadoc

3.1.4 PropertySource Abstraction

Unified Property Management (SpringSource Team Blog)

See org.springframework.core.env.Environment Javadoc

See org.springframework.core.env.PropertySource Javadoc

See org.springframework.context.annotation.PropertySource Javadoc

3.1.5 Code equivalents for Spring's XML namespaces

Code-based equivalents to popular Spring XML namespace elements <context:component-

Page 47: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 47/81

scan/>, <tx:annotation-driven/> and <mvc:annotation-driven> have been developed, most in theform of @Enable annotations. These are designed for use in conjunction with Spring's@Configuration classes, which were introduced in Spring 3.0.

See org.springframework.context.annotation.Configuration Javadoc

See org.springframework.context.annotation.ComponentScan Javadoc

See org.springframework.transaction.annotation.EnableTransactionManagement Javadoc

See org.springframework.cache.annotation.EnableCaching Javadoc

See org.springframework.web.servlet.config.annotation.EnableWebMvc Javadoc

See org.springframework.scheduling.annotation.EnableScheduling Javadoc

See org.springframework.scheduling.annotation.EnableAsync Javadoc

See org.springframework.context.annotation.EnableAspectJAutoProxy Javadoc

See org.springframework.context.annotation.EnableLoadTimeWeaving Javadoc

See org.springframework.beans.factory.aspectj.EnableSpringConfigured Javadoc

3.1.6 Support for Hibernate 4.x

See Javadoc for classes within the new org.springframework.orm.hibernate4 package

3.1.7 TestContext framework support for @Configuration classes andbean definition profiles

The @ContextConfiguration annotation now supports supplying @Configuration classes forconfiguring the Spring TestContext. In addition, a new @ActiveProfiles annotation has beenintroduced to support declarative configuration of active bean definition profiles inApplicationContext integration tests.

Spring 3.1 M2: Testing with @Configuration Classes and Profiles (SpringSource TeamBlog)

See Section 10.3.5, “Spring TestContext Framework”

See the section called “Context configuration with @Configuration classes” andorg.springframework.test.context.ContextConfiguration Javadoc

See org.springframework.test.context.ActiveProfiles Javadoc

See org.springframework.test.context.SmartContextLoader Javadoc

See org.springframework.test.context.support.DelegatingSmartContextLoader

Javadoc

See org.springframework.test.context.support.AnnotationConfigContextLoader

Javadoc

3.1.8 c: namespace for more concise constructor injection

Section 4.4.2.7, “XML shortcut with the c-namespace”

3.1.9 Support for injection against non-standard JavaBeans setters

Page 48: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 48/81

Prior to Spring 3.1, in order to inject against a property method it had to conform strictly toJavaBeans property signature rules, namely that any 'setter' method must be void-returning. It isnow possible in Spring XML to specify setter methods that return any object type. This is usefulwhen considering designing APIs for method-chaining, where setter methods return a referenceto 'this'.

3.1.10 Support for Servlet 3 code-based configuration of ServletContainer

The new WebApplicationInitializer builds atop Servlet 3.0's ServletContainerInitializersupport to provide a programmatic alternative to the traditional web.xml.

See org.springframework.web.WebApplicationInitializer Javadoc

Diff from Spring's Greenhouse reference application demonstrating migration from web.xmlto WebApplicationInitializer

3.1.11 Support for Servlet 3 MultipartResolver

See org.springframework.web.multipart.support.StandardServletMultipartResolver Javadoc

3.1.12 JPA EntityManagerFactory bootstrapping withoutpersistence.xml

In standard JPA, persistence units get defined through META-INF/persistence.xml files inspecific jar files which will in turn get searched for @Entity classes. In many cases,persistence.xml does not contain more than a unit name and relies on defaults and/or externalsetup for all other concerns (such as the DataSource to use, etc). For that reason, Spring 3.1provides an alternative: LocalContainerEntityManagerFactoryBean accepts a'packagesToScan' property, specifying base packages to scan for @Entity classes. This isanalogous to AnnotationSessionFactoryBean's property of the same name for native Hibernatesetup, and also to Spring's component-scan feature for regular Spring beans. Effectively, thisallows for XML-free JPA setup at the mere expense of specifying a base package for entityscanning: a particularly fine match for Spring applications which rely on component scanning forSpring beans as well, possibly even bootstrapped using a code-based Servlet 3.0 initializer.

3.1.13 New HandlerMethod-based Support Classes For AnnotatedController Processing

Spring 3.1 introduces a new set of support classes for processing requests with annotatedcontrollers:

RequestMappingHandlerMapping

RequestMappingHandlerAdapter

ExceptionHandlerExceptionResolver

These classes are a replacement for the existing:

DefaultAnnotationHandlerMapping

AnnotationMethodHandlerAdapter

AnnotationMethodHandlerExceptionResolver

The new classes were developed in response to many requests to make annotation controllersupport classes more customizable and open for extension. Whereas previously you could

Page 49: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 49/81

configure a custom annotated controller method argument resolver, with the new support classesyou can customize the processing for any supported method argument or return value type.

See org.springframework.web.method.support.HandlerMethodArgumentResolver Javadoc

See org.springframework.web.method.support.HandlerMethodReturnValueHandlerJavadoc

A second notable difference is the introduction of a HandlerMethod abstraction to represent an@RequestMapping method. This abstraction is used throughout by the new support classes asthe handler instance. For example a HandlerInterceptor can cast the handler from Object toHandlerMethod and get access to the target controller method, its annotations, etc.

The new classes are enabled by default by the MVC namespace and by Java-basedconfiguration via @EnableWebMvc. The existing classes will continue to be available but use ofthe new classes is recommended going forward.

See Section 16.3.2.1, “New Support Classes for @RequestMapping methods in Spring MVC3.1” for additional details and a list of features not available with the new support classes.

3.1.14 "consumes" and "produces" conditions in @RequestMapping

Improved support for specifying media types consumed by a method through the 'Content-Type'header as well as for producible types specified through the 'Accept' header. SeeSection 16.3.2.5, “Consumable Media Types” and Section 16.3.2.6, “Producible Media Types”

3.1.15 Flash Attributes and RedirectAttributes

Flash attributes can now be stored in a FlashMap and saved in the HTTP session to survive aredirect. For an overview of the general support for flash attributes in Spring MVC seeSection 16.6, “Using flash attributes”.

In annotated controllers, an @RequestMapping method can add flash attributes by declaring amethod argument of type RedirectAttributes. This method argument can now also be used toget precise control over the attributes used in a redirect scenario. See Section 16.3.3.10,“Specifying redirect and flash attributes” for more details.

3.1.16 URI Template Variable Enhancements

URI template variables from the current request are used in more places:

URI template variables are used in addition to request parameters when binding a requestto @ModelAttribute method arguments.

@PathVariable method argument values are merged into the model before rendering,except in views that generate content in an automated fashion such as JSON serializationor XML marshalling.

A redirect string can contain placeholders for URI variables (e.g."redirect:/blog/{year}/{month}"). When expanding the placeholders, URI templatevariables from the current request are automatically considered.

An @ModelAttribute method argument can be instantiated from a URI template variableprovided there is a registered Converter or PropertyEditor to convert from a String to thetarget object type.

3.1.17 @Valid On @RequestBody Controller Method Arguments

Page 50: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 50/81

An @RequestBody method argument can be annotated with @Valid to invoke automaticvalidation similar to the support for @ModelAttribute method arguments. A resultingMethodArgumentNotValidException is handled in the DefaultHandlerExceptionResolver andresults in a 400 response code.

3.1.18 @RequestPart Annotation On Controller Method Arguments

This new annotation provides access to the content of a "multipart/form-data" request part. SeeSection 16.10.5, “Handling a file upload request from programmatic clients” and Section 16.10,“Spring's multipart (file upload) support”.

3.1.19 UriComponentsBuilder and UriComponents

A new UriComponents class has been added, which is an immutable container of URIcomponents providing access to all contained URI components. A new UriComponentsBuilderclass is also provided to help create UriComponents instances. Together the two classes givefine-grained control over all aspects of preparing a URI including construction, expansion fromURI template variables, and encoding.

In most cases the new classes can be used as a more flexible alternative to the existingUriTemplate especially since UriTemplate relies on those same classes internally.

A ServletUriComponentsBuilder sub-class provides static factory methods to copy informationfrom a Servlet request. See Section 16.7, “Building URIs”.

Part III. Core Technologies

This part of the reference documentation covers all of those technologies that are absolutelyintegral to the Spring Framework.

Foremost amongst these is the Spring Framework's Inversion of Control (IoC) container. Athorough treatment of the Spring Framework's IoC container is closely followed bycomprehensive coverage of Spring's Aspect-Oriented Programming (AOP) technologies. TheSpring Framework has its own AOP framework, which is conceptually easy to understand, andwhich successfully addresses the 80% sweet spot of AOP requirements in Java enterpriseprogramming.

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

Finally, the adoption of the test-driven-development (TDD) approach to software development iscertainly advocated by the Spring team, and so coverage of Spring's support for integrationtesting is covered (alongside best practices for unit testing). The Spring team has found that thecorrect use of IoC certainly does make both unit and integration testing easier (in that thepresence of setter methods and appropriate constructors on classes makes them easier to wiretogether in a test without having to set up service locator registries and suchlike)... the chapterdedicated solely to testing will hopefully convince you of this as well.

Chapter 4, The IoC container

Chapter 5, Resources

Chapter 6, Validation, Data Binding, and Type Conversion

Chapter 7, Spring Expression Language (SpEL)

Chapter 8, Aspect Oriented Programming with Spring

Page 51: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 51/81

Chapter 9, Spring AOP APIs

Chapter 10, Testing

4. The IoC container

4.1 Introduction to the Spring IoC container and beans

This chapter covers the Spring Framework implementation of the Inversion of Control (IoC)[1]principle. IoC is also known as dependency injection (DI). It is a process whereby objectsdefine their dependencies, that is, the other objects they work with, only through constructorarguments, arguments to a factory method, or properties that are set on the object instance afterit is constructed or returned from a factory method. The container then injects thosedependencies 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 itsdependencies 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 basisfor Spring Framework's IoC container. The BeanFactory interface provides an advancedconfiguration mechanism capable of managing any type of object. ApplicationContext is a sub-interface of BeanFactory. It adds easier integration with Spring's AOP features; messageresource handling (for use in internationalization), event publication; and application-layer specificcontexts such as the WebApplicationContext for use in web applications.

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

In Spring, the objects that form the backbone of your application and that are managed by theSpring IoC container are called beans. A bean is an object that is instantiated, assembled, andotherwise 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 configurationmetadata used by a container.

4.2 Container overview

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

Several implementations of the ApplicationContext interface are supplied out-of-the-box withSpring. In standalone applications it is common to create an instance ofClassPathXmlApplicationContext or FileSystemXmlApplicationContext. While XML has beenthe traditional format for defining configuration metadata you can instruct the container to useJava annotations or code as the metadata format by providng a small amount of XMLconfiguration to declaratively enable support for these additional metadata formats.

In most application scenarios, explicit user code is not required to instantiate one or moreinstances of a Spring IoC container. For example, in a web application scenario, a simple eight(or so) lines of boilerplate J2EE web descriptor XML in the web.xml file of the application will

Page 52: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 52/81

typically suffice (see Section 4.14.4, “Convenient ApplicationContext instantiation for webapplications”). If you are using the SpringSource Tool Suite Eclipse-powered developmentenvironment or Spring Roo this boilerplate configuration can be easily created with few mouseclicks or keystrokes.

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

The Spring IoC container

4.2.1 Configuration metadata

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

Configuration metadata is traditionally supplied in a simple and intuitive XML format, which iswhat 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 whichthis configuration metadata is actually written.

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

Annotation-based configuration: Spring 2.5 introduced support for annotation-basedconfiguration metadata.

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

Spring configuration consists of at least one and typically more than one bean definition that thecontainer must manage. XML-based configuration metadata shows these beans configured as

Page 53: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 53/81

<bean/> elements inside a top-level <beans/> element.

These bean definitions correspond to the actual objects that make up your application. Typicallyyou define service layer objects, data access objects (DAOs), presentation objects such asStruts Action instances, infrastructure objects such as Hibernate SessionFactories, JMSQueues, and so forth. Typically one does not configure fine-grained domain objects in thecontainer, because it is usually the responsibility of DAOs and business logic to create and loaddomain objects. However, you can use Spring's integration with AspectJ to configure objects thathave 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 classattribute defines the type of the bean and uses the fully qualified classname. The value of the idattribute refers to collaborating objects. The XML for referring to collaborating objects is notshown in this example; see Dependencies for more information.

4.2.2 Instantiating a container

Instantiating a Spring IoC container is straightforward. The location path or paths supplied to anApplicationContext constructor are actually resource strings that allow the container to loadconfiguration metadata from a variety of external resources such as the local file system, from theJava 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 moreabout Spring's Resource abstraction, as described in Chapter 5, Resources,which provides a convenient mechanism for reading an InputSream fromlocations defined in a URI syntax. In particular, Resource paths are used toconstruct applications contexts as described in Section 5.7, “Applicationcontexts and Resource paths”.

The following example shows the service layer objects (services.xml) configuration 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">

<!-- services -->

Page 54: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 54/81

<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.ibatis.SqlMapAccountDao"> <!-- additional collaborators and configuration for this bean go here --> </bean>

<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapItemDao"> <!-- 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 twodata access objects of the type SqlMapAccountDao and SqlMapItemDao are based on the iBatisObject/Relational mapping framework. The property name element refers to the name of theJavaBean property, and the ref element refers to the name of another bean definition. Thislinkage between id and ref elements expresses the dependency between collaborating objects.For details of configuring an object's dependencies, see Dependencies.

4.2.2.1 Composing XML-based configuration metadata

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

You can use the application context constructor to load bean definitions from all these XMLfragments. This constructor takes multiple Resource locations, as was shown in the previoussection. Alternatively, use one or more occurrences of the <import/> element to load beandefinitions 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>

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 filedoing the importing, so services.xml must be in the same directory or classpath location as thefile doing the importing, while messageSource.xml and themeSource.xml must be in a resourceslocation below the location of the importing file. As you can see, a leading slash is ignored, butgiven that these paths are relative, it is better form not to use the slash at all. The contents of thefiles being imported, including the top level <beans/> element, must be valid XML bean

Page 55: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 55/81

definitions according to the Spring Schema or DTD.

Note

It is possible, but not recommended, to reference files in parent directoriesusing a relative "../" path. Doing so creates a dependency on a file that isoutside the current application. In particular, this reference is notrecommended for "classpath:" URLs (for example,"classpath:../services.xml"), where the runtime resolution process choosesthe "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 relativepaths: for example, "file:C:/config/services.xml" or"classpath:/config/services.xml". However, be aware that you are couplingyour application's configuration to specific absolute locations. It is generallypreferable to keep an indirection for such absolute locations, for example,through "${...}" placeholders that are resolved against JVM system propertiesat runtime.

4.2.3 Using the container

The ApplicationContext is the interface for an advanced factory capable of maintaining aregistry 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 beansApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

// retrieve configured instancePetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.class);

// use configured instanceList userList service.getUsernameList();

You use getBean() to retrieve instances of your beans. The ApplicationContext interface has afew 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 nodependency on Spring APIs at all. For example, Spring's integration with web frameworksprovides for dependency injection for various web framework classes such as controllers andJSF-managed beans.

4.3 Bean overview

A Spring IoC container manages one or more beans. These beans are created with theconfiguration 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:

A package-qualified class name: typically the actual implementation class of the beanbeing defined.

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

Page 56: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 56/81

Bean naming conventions

The convention is to use the

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 ofconnections 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 4.1. The bean definition

Property Explained in...

class Section 4.3.2, “Instantiating beans”

name Section 4.3.1, “Naming beans”

scope Section 4.5, “Bean scopes”

constructor arguments Section 4.4.1, “Dependency injection”

properties Section 4.4.1, “Dependency injection”

autowiring mode Section 4.4.5, “Autowiring collaborators”

lazy-initialization mode Section 4.4.4, “Lazy-initialized beans”

initialization method Section 4.6.1.1, “Initialization callbacks”

destruction method Section 4.6.1.2, “Destruction callbacks”

In addition to bean definitions that contain information on how to create a specific bean, theApplicationContext implementations also permit the registration of existing objects that arecreated outside the container, by users. This is done by accessing the ApplicationContext'sBeanFactory via the method getBeanFactory() which returns the BeanFactory implementationDefaultListableBeanFactory. DefaultListableBeanFactory supports this registration throughthe methods registerSingleton(..) and registerBeanDefinition(..). However, typicalapplications work solely with beans defined through metadata bean definitions.

4.3.1 Naming beans

Every bean has one or more identifiers. These identifiers must be unique within the container thathosts the bean. A bean usually has only one identifier, but if it requires more than one, the extraones can be considered aliases.

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

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

4.3.1.1 Aliasing a bean outside the bean definition

In a bean definition itself, you can supply more thanone name for the bean, by using a combination of up

Page 57: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 57/81

standard Java convention forinstance field names when namingbeans. That is, bean names startwith a lowercase letter, and arecamel-cased from then on.Examples of such names would be(without quotes)'accountManager','accountService', 'userDao','loginController', and soforth.

Naming beans consistently makesyour configuration easier to readand understand, and if you areusing Spring AOP it helps a lotwhen applying advice to a set ofbeans related by name.

to one name specified by the id attribute, and anynumber of other names in the name attribute. Thesenames can be equivalent aliases to the same bean,and are useful for some situations, such as allowingeach component in an application to refer to acommon dependency by using a bean name that isspecific to that component itself.

Specifying all aliases where the bean is actuallydefined is not always adequate, however. It issometimes desirable to introduce an alias for a beanthat is defined elsewhere. This is commonly the casein large systems where configuration is split amongsteach subsystem, each subsystem having its own set ofobject definitions. In XML-based configurationmetadata, you can use the <alias/> element toaccomplish this.

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

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

For example, the configuration metadata for subsystem A may refer to a DataSource via thename 'subsystemA-dataSource. The configuration metadata for subsystem B may refer to aDataSource via the name 'subsystemB-dataSource'. When composing the main application thatuses 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 MyAppconfiguration 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 thatis unique and guaranteed not to clash with any other definition (effectively creating a namespace),yet they refer to the same bean.

4.3.2 Instantiating beans

A bean definition essentially is a recipe for creating one or more objects. The container looks atthe recipe for a named bean when asked, and uses the configuration metadata encapsulated bythat 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 tobe instantiated in the class attribute of the <bean/> element. This class attribute, which internallyis a Class property on a BeanDefinition instance, is usually mandatory. (For exceptions, seeSection 4.3.2.3, “Instantiation using an instance factory method” and Section 4.7, “Bean definitioninheritance”.) 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 itselfdirectly creates the bean by calling its constructor reflectively, somewhat equivalent to Javacode using the new operator.

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

Page 58: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 58/81

Inner class names

If you want to configure a beandefinition for a static nestedclass, you have to use the binaryname of the inner class.

For example, if you have a classcalled Foo in the com.examplepackage, and this Foo class has astatic inner class called Bar, thevalue of the 'class' attribute ona bean definition would be...

com.example.Foo$Bar

Notice the use of the $ characterin the name to separate the innerclass name from the outer classname.

4.3.2.1 Instantiation with a constructor

When you create a bean by the constructor approach,all normal classes are usable by and compatible withSpring. That is, the class being developed does notneed to implement any specific interfaces or to becoded in a specific fashion. Simply specifying thebean class should suffice. However, depending onwhat type of IoC you use for that specific bean, youmay need a default (empty) constructor.

The Spring IoC container can manage virtually anyclass you want it to manage; it is not limited tomanaging true JavaBeans. Most Spring users preferactual JavaBeans with only a default (no-argument)constructor and appropriate setters and gettersmodeled after the properties in the container. You canalso have more exotic non-bean-style classes in yourcontainer. If, for example, you need to use a legacyconnection pool that absolutely does not adhere to theJavaBean 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) andsetting object instance properties after the object is constructed, see Injecting Dependencies.

4.3.2.2 Instantiation with a static factory method

When defining a bean that you create with a static factory method, you use the class attribute tospecify the class containing the static factory method and an attribute named factory-methodto specify the name of the factory method itself. You should be able to call this method (withoptional arguments as described later) and return a live object, which subsequently is treated asif it had been created through a constructor. One use for such a bean definition is to call staticfactories 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 andsetting object instance properties after the object is returned from the factory, see Dependenciesand configuration in detail.

Page 59: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 59/81

4.3.2.3 Instantiation using an instance factory method

Similar to instantiation through a static factory method, instantiation with an instance factorymethod 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 bean in the current (or parent/ancestor) container that contains the instancemethod that is to be invoked to create the object. Set the name of the factory method itself withthe 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 throughdependency injection (DI). See Dependencies and configuration in detail.

Note

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

4.4 Dependencies

Page 60: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 60/81

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

4.4.1 Dependency injection

Dependency injection (DI) is a process whereby objects define their dependencies, that is, theother 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 factorymethod. The container then injects those dependencies when it creates the bean. This process isfundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controllingthe 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 providedwith their dependencies. The object does not look up its dependencies, and does not know thelocation or class of the dependencies. As such, your classes become easier to test, in particularwhen the dependencies are on interfaces or abstract base classes, which allow for stub or mockimplementations to be used in unit tests.

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

4.4.1.1 Constructor-based dependency injection

Constructor-based DI is accomplished by the container invoking a constructor with a number ofarguments, each representing a dependency. Calling a static factory method with specificarguments to construct the bean is nearly equivalent, and this discussion treats arguments to aconstructor and to a static factory method similarly. The following example shows a class thatcan only be dependency-injected with constructor injection. Notice that there is nothing specialabout this class, it is a POJO that has no dependencies on container specific interfaces, baseclasses 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 potentialambiguity exists in the constructor arguments of a bean definition, then the order in which theconstructor arguments are defined in a bean definition is the order in which those arguments aresupplied to the appropriate constructor when the bean is being instantiated. Consider thefollowing class:

package x.y;

public class Foo {

public Foo(Bar bar, Baz baz) {

Page 61: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 61/81

// ... }}

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 constructorargument 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 casewith the preceding example). When a simple type is used, such as <value>true<value>, Springcannot determine the type of the value, and so cannot match by type without help. Consider thefollowing class:

package examples;

public class ExampleBean {

// No. of years to the 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; }}

Constructor argument type matching

In the preceding scenario, the container can use type matching with simple types if you explicitlyspecify 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>

Constructor argument index

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 0based.

Constructor argument name

Page 62: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 62/81

Constructor-based or setter-based DI?

Since you can mix both,Constructor- and Setter-based DI,it is a good rule of thumb to use

As of Spring 3.0 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 debugflag enabled so that Spring can look up the parameter name from the constructor. If you can'tcompile your code with debug flag (or don't want to) you can use @ConstructorProperties JDKannotation to explicitly name your constructor arguments. The sample class would then have tolook as follows:

package examples;

public class ExampleBean {

// Fields omitted

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

4.4.1.2 Setter-based dependency injection

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

The following example shows a class that can only be dependency-injected using pure setterinjection. This class is conventional Java. It is a POJO that has no dependencies on containerspecific 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- and setter-based DI for the beans it manages. Italso supports setter-based DI after some dependencies are already injected through theconstructor approach. You configure the dependencies in the form of a BeanDefinition, whichyou use with PropertyEditor instances to convert properties from one format to another.However, most Spring users do not work with these classes directly (programmatically), butrather with an XML definition file that is then converted internally into instances of these classes,and used to load an entire Spring IoC container instance.

4.4.1.3 Dependency resolution process

The container performs bean dependency resolutionas follows:

1. The ApplicationContext is created and

Page 63: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 63/81

constructor arguments formandatory dependencies andsetters for optional dependencies.Note that the use of a @Requiredannotation on a setter can beused to make setters requireddependencies.

The Spring team generallyadvocates setter injection,because large numbers ofconstructor arguments can getunwieldy, especially whenproperties are optional. Settermethods also make objects of thatclass amenable to reconfigurationor re-injection later. Managementthrough JMX MBeans is acompelling use case.

Some purists favor constructor-based injection. Supplying allobject dependencies means thatthe object is always returned toclient (calling) code in a totallyinitialized state. The disadvantageis that the object becomes lessamenable to reconfiguration andre-injection.

Use the DI that makes the mostsense for a particular class.Sometimes, when dealing withthird-party classes to which you donot have the source, the choice ismade for you. A legacy class maynot expose any setter methods,and so constructor injection is theonly available DI.

Circular dependencies

If you use predominantlyconstructor injection, it is possibleto create an unresolvable circulardependency scenario.

For example: Class A requires aninstance of class B throughconstructor injection, and class Brequires an instance of class Athrough constructor injection. Ifyou configure beans for classes Aand B to be injected into eachother, the Spring IoC containerdetects this circular reference atruntime, and throws aBeanCurrentlyInCreationException.

One possible solution is to edit thesource code of some classes to beconfigured by setters rather thanconstructors. Alternatively, avoid

initialized with configuration metadata thatdescribes all the beans. Configuration metadatacan be specified via XML, Java code orannotations.

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

3. Each property or constructor argument is anactual definition of the value to set, or areference to another bean in the container.

4. Each property or constructor argument which isa value is converted from its specified format tothe actual type of that property or constructorargument. By default Spring can convert a valuesupplied in string format to all built-in types, suchas int, long, String, boolean, etc.

The Spring container validates the configuration ofeach bean as the container is created, including thevalidation of whether bean reference properties referto valid beans. However, the bean propertiesthemselves are not set until the bean is actually

created. Beans that are singleton-scoped and set tobe pre-instantiated (the default) are created when thecontainer is created. Scopes are defined inSection 4.5, “Bean scopes” Otherwise, the bean iscreated only when it is requested. Creation of a beanpotentially causes a graph of beans to be created, asthe bean's dependencies and its dependencies'dependencies (and so on) are created and assigned.

You can generally trust Spring to do the right thing. Itdetects configuration problems, such as references tonon-existent beans and circular dependencies, atcontainer load-time. Spring sets properties andresolves dependencies as late as possible, when thebean is actually created. This means that a Springcontainer which has loaded correctly can latergenerate an exception when you request an object ifthere is a problem creating that object or one of itsdependencies. For example, the bean throws anexception as a result of a missing or invalid property.This potentially delayed visibility of some configurationissues is why ApplicationContext implementationsby default pre-instantiate singleton beans. At the costof some upfront time and memory to create thesebeans before they are actually needed, you discoverconfiguration issues when the ApplicationContext iscreated, not later. You can still override this defaultbehavior so that singleton beans will lazy-initialize,rather than be pre-instantiated.

Page 64: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 64/81

constructor injection and usesetter injection only. In otherwords, although it is notrecommended, you can configurecircular dependencies with setterinjection.

Unlike the typical case (with nocircular dependencies), a circulardependency between bean A andbean B forces one of the beans tobe injected into the other prior tobeing fully initialized itself (aclassic chicken/egg scenario).

If no circular dependencies exist, when one or morecollaborating beans are being injected into a

dependent bean, each collaborating bean is totallyconfigured prior to being injected into the dependentbean. This means that if bean A has a dependency onbean B, the Spring IoC container completelyconfigures bean B prior to invoking the setter methodon bean A. In other words, the bean is instantiated (ifnot a pre-instantiated singleton), its dependencies areset, and the relevant lifecycle methods (such as aconfigured init method or the InitializingBean callbackmethod) are invoked.

4.4.1.4 Examples of dependency injection

The following example uses XML-based configuration metadata for setter-based DI. A small partof 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"/>

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 theXML 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"/>

Page 65: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 65/81

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 theconstructor of the ExampleBean.

Now consider a variant of this example, where instead of using a constructor, Spring is told to calla 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"/>

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, exactlythe same as if a constructor had actually been used. The type of the class being returned by thefactory method does not have to be of the same type as the class that contains the static factorymethod, although in this example it is. An instance (non-static) factory method would be used inan essentially identical fashion (aside from the use of the factory-bean attribute instead of theclass attribute), so details will not be discussed here.

4.4.2 Dependencies and configuration in detail

As mentioned in the previous section, you can define bean properties and constructor argumentsas 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.

4.4.2.1 Straight values (primitives, Strings, and so on)

The value attribute of the <property/> element specifies a property or constructor argument as ahuman-readable string representation. As mentioned previously, JavaBeans PropertyEditors

Page 66: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 66/81

are used to convert these string values from a String to the actual type of the property orargument.

<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.

<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 thandesign time, unless you use an IDE such as IntelliJ IDEA or the SpringSource Tool Suite (STS)that support automatic property completion when you create bean definitions. Such IDEassistance 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.Propertiesinstance by using the JavaBeans PropertyEditor mechanism. This is a nice shortcut, and is oneof a few places where the Spring team do favor the use of the nested <value/> element over thevalue attribute style.

The idref element

The idref element is simply an error-proof way to pass the id (string value - not a reference) ofanother 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>

Page 67: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 67/81

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 tovalidate at deployment time that the referenced, named bean actually exists. In the secondvariation, no validation is performed on the value that is passed to the targetName property of theclient bean. Typos are only discovered (with most likely fatal results) when the client bean isactually instantiated. If the client bean is a prototype bean, this typo and the resulting exceptionmay only be discovered long after the container is deployed.

Additionally, if the referenced bean is in the same XML unit, and the bean name is the bean id,you can use the local attribute, which allows the XML parser itself to validate the bean id earlier,at XML document parse time.

<property name="targetName"> <!-- a bean with id 'theTargetBean' must exist; otherwise an exception will be thrown --> <idref local="theTargetBean"/></property>

A common place (at least in versions earlier than Spring 2.0) where the <idref/> element bringsvalue 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 aninterceptor id.

4.4.2.2 References to other beans (collaborators)

The ref element is the final element inside a <constructor-arg/> or <property/> definitionelement. Here you set the value of the specified property of a bean to be a reference to anotherbean (a collaborator) managed by the container. The referenced bean is a dependency of thebean whose property will be set, and it is initialized on demand as needed before the property isset. (If the collaborator is a singleton bean, it may be initialized already by the container.) Allreferences are ultimately a reference to another object. Scoping and validation depend onwhether 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 sameas the id attribute of the target bean, or as one of the values in the name attribute of the targetbean.

<ref bean="someBean"/>

Specifying the target bean through the local attribute leverages the ability of the XML parser tovalidate XML id references within the same file. The value of the local attribute must be thesame as the id attribute of the target bean. The XML parser issues an error if no matchingelement is found in the same file. As such, using the local variant is the best choice (in order toknow about errors as early as possible) if the target bean is in the same XML file.

<ref local="someBean"/>

Specifying the target bean through the parent attribute creates a reference to a bean that is in aparent container of the current container. The value of the parent attribute may be the same aseither the id attribute of the target bean, or one of the values in the name attribute of the target

Page 68: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 68/81

bean, and the target bean must be in a parent container of the current one. You use this beanreference variant mainly when you have a hierarchy of containers and you want to wrap anexisting 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>

4.4.2.3 Inner beans

A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-calledinner 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; the container ignores these

values. It also ignores the scope flag. Inner beans are always anonymous and they are alwaysscoped as prototypes. It is not possible to inject inner beans into collaborating beans other thaninto the enclosing bean.

4.4.2.4 Collections

In the <list/>, <set/>, <map/>, and <props/> elements, you set the properties and arguments ofthe 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">

Page 69: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 69/81

<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:

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

Collection merging

As of Spring 2.0, the container supports the merging of collections. An application developer candefine 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. Thatis, the child collection's values are the result of merging the elements of the parent and childcollections, 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 withparent 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 propertyof 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 themerging 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 thespecific case of the <list/> element, the semantics associated with the List collection type, thatis, the notion of an ordered collection of values, is maintained; the parent's values precede all ofthe child list's values. In the case of the Map, Set, and Properties collection types, no orderingexists. Hence no ordering semantics are in effect for the collection types that underlie theassociated Map, Set, and Properties implementation types that the container uses internally.

Page 70: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 70/81

Limitations of collection merging

You cannot merge different collection types (such as a Map and a List), and if you do attempt todo so an appropriate Exception is thrown. The merge attribute must be specified on the lower,inherited, child definition; specifying the merge attribute on a parent collection definition isredundant and will not result in the desired merging. The merging feature is available only inSpring 2.0 and later.

Strongly-typed collection (Java 5+ only)

In Java 5 and later, you can use strongly typed collections (using generic types). That is, it ispossible to declare a Collection type such that it can only contain String elements (forexample). 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 yourstrongly-typed Collection instances are converted to the appropriate type prior to being addedto 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 informationabout the element type of the strongly-typed Map<String, Float> is available by reflection. ThusSpring's type conversion infrastructure recognizes the various value elements as being of typeFloat, and the string values 9.99, 2.75, and 3.99 are converted into an actual Float type.

4.4.2.5 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).

4.4.2.6 XML shortcut with the p-namespace

Page 71: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 71/81

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 2.0 and later supports extensible configuration formats with namespaces, which arebased on an XML Schema definition. The beans configuration format discussed in this chapter isdefined in an XML Schema document. However, the p-namespace is not defined in an XSD fileand exists only in the core of Spring.

The following example shows two XML snippets that resolve to the same result: The first usesstandard 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 tellsSpring to include a property declaration. As previously mentioned, the p-namespace does nothave 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 alsouses 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, thesecond bean definition uses p:spouse-ref="jane" as an attribute to do the exact same thing. Inthis case spouse is the property name, whereas the -ref part indicates that this is not a straightvalue but rather a reference to another bean.

Note

The p-namespace is not as flexible as the standard XML format. Forexample, the format for declaring property references clashes with propertiesthat end in Ref, whereas the standard XML format does not. We recommendthat you choose your approach carefully and communicate this to your teammembers, to avoid producing XML documents that use all three approachesat the same time.

Page 72: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 72/81

4.4.2.7 XML shortcut with the c-namespace

Similar to the Section 4.4.2.6, “XML shortcut with the p-namespace”, the c-namespace, newlyintroduced in Spring 3.1, allows usage of inlined attributes for configuring the constructorarguments rather then nested constructor-arg elements.

Let's review the examples from Section 4.4.1.1, “Constructor-based dependency injection” withthe 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 declaredeven 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 thebytecode was compiled without debugging information), one can use fallback to the argumentindexes:

<-- '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 theleading _ as XML attribute names cannot start with a number (even thoughsome IDE allow it).

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

4.4.2.8 Compound property names

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

<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 thatfinal 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

Page 73: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 73/81

NullPointerException is thrown.

4.4.3 Using depends-on

If a bean is a dependency of another that usually means that one bean is set as a property ofanother. Typically you accomplish this with the <ref/> element in XML-based configurationmetadata. However, sometimes dependencies between beans are less direct; for example, astatic initializer in a class needs to be triggered, such as database driver registration. Thedepends-on attribute can explicitly force one or more beans to be initialized before the bean usingthis element is initialized. The following example uses the depends-on attribute to express adependency 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 thedepends-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 aninitialization time dependency and, in the case of singleton beans only, acorresponding destroy time dependency. Dependent beans that define adepends-on relationship with a given bean are destroyed first, prior to thegiven bean itself being destroyed. Thus depends-on can also controlshutdown order.

4.4.4 Lazy-initialized beans

By default, ApplicationContext implementations eagerly create and configure all singletonbeans as part of the initialization process. Generally, this pre-instantiation is desirable, becauseerrors 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-instantiationof a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tellsthe 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; forexample:

<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 namedlazy is not eagerly pre-instantiated when the ApplicationContext is starting up, whereas thenot.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 mustsatisfy the singleton's dependencies. The lazy-initialized bean is injected into a singleton beanelsewhere that is not lazy-initialized.

Page 74: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 74/81

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

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

4.4.5 Autowiring collaborators

The Spring container can autowire relationships between collaborating beans. You can allowSpring to resolve collaborators (other beans) automatically for your bean by inspecting thecontents 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 alsovaluable in this regard.)

Autowiring can update a configuration as your objects evolve. For example, if you need toadd a dependency to a class, that dependency can be satisfied automatically without youneeding to modify the configuration. Thus autowiring can be especially useful duringdevelopment, without negating the option of switching to explicit wiring when the code basebecomes more stable.

When using XML-based configuration metadata[2], you specify autowire mode for a beandefinition with the autowire attribute of the <bean/> element. The autowiring functionality has fivemodes. You specify autowiring per bean and thus can choose which ones to autowire.

Table 4.2. Autowiring modes

Mode Explanation

no

(Default) No autowiring. Bean references must be defined via a refelement. Changing the default setting is not recommended for largerdeployments, because specifying collaborators explicitly gives greatercontrol 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 nameas the property 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 definitionnamed master, and uses it to set the property.

byType

Allows a property to be autowired if exactly one bean of the property typeexists 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. Ifthere are no matching beans, nothing happens; the property is not set.

constructorAnalogous to byType, but applies to constructor arguments. If there is notexactly one bean of the constructor argument type in the container, a fatalerror is raised.

With byType or constructor autowiring mode, you can wire arrays and typed-collections. In suchcases all autowire candidates within the container that match the expected type are provided tosatisfy 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 theMaps keys will contain the corresponding bean names.

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

Page 75: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 75/81

autowiring completes.

4.4.5.1 Limitations and disadvantages of autowiring

Autowiring works best when it is used consistently across a project. If autowiring is not used ingeneral, 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 iscareful to avoid guessing in case of ambiguity that might have unexpected results, therelationships between your Spring-managed objects are no longer documented explicitly.

Wiring information may not be available to tools that may generate documentation from aSpring container.

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

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 falseas described in the next section.

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

If you are using Java 5 or later, implement the more fine-grained control available withannotation-based configuration, as described in Section 4.9, “Annotation-based containerconfiguration”.

4.4.5.2 Excluding a bean from autowiring

On a per-bean basis, you can exclude a bean from autowiring. In Spring's XML format, set theautowire-candidate attribute of the <bean/> element to false; the container makes that specificbean definition unavailable to the autowiring infrastructure (including annotation styleconfigurations 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-candidatesattribute. For example, to limit autowire candidate status to any bean whose name ends withRepository, provide a value of *Repository. To provide multiple patterns, define them in acomma-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 donot apply.

These techniques are useful for beans that you never want to be injected into other beans byautowiring. 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.

Page 76: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 76/81

You can read more about themotivation for Method Injection inthis blog entry.

4.4.6 Method injection

In most application scenarios, most beans in the container are singletons. When a singleton beanneeds to collaborate with another singleton bean, or a non-singleton bean needs to collaboratewith another non-singleton bean, you typically handle the dependency by defining one bean as aproperty of the other. A problem arises when the bean lifecycles are different. Suppose singletonbean 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 setthe properties. The container cannot provide bean A with a new instance of bean B every timeone is needed.

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

// a class that uses a stateful Command-style class to perform some processingpackage fiona.apple;

// Spring-API importsimport 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 theSpring Framework. Method Injection, a somewhat advanced feature of the Spring IoC container,allows this use case to be handled in a clean fashion.

4.4.6.1 Lookup method injection

Lookup method injection is the ability of the containerto override methods on container managed beans, toreturn the lookup result for another named bean in thecontainer. The lookup typically involves a prototypebean as in the scenario described in the precedingsection. The Spring Framework implements this method injection by using bytecode generationfrom the CGLIB library to generate dynamically a subclass that overrides the method.

Note

For this dynamic subclassing to work, you must have the CGLIB jar(s) in yourclasspath. The class that the Spring container will subclass cannot be final,and the method to be overridden cannot be final either. Also, testing a class

Page 77: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 77/81

that has an abstract method requires you to subclass the class yourself andto supply a stub implementation of the abstract method. Finally, objects thathave been the target of method injection cannot be serialized.

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

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), themethod 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 theoriginal 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 itneeds a new instance of the command bean. You must be careful to deploy the command bean asa prototype, if that is actually what is needed. If it is deployed as a singleton, the same instance ofthe command bean is returned each time.

Tip

The interested reader may also find the ServiceLocatorFactoryBean (in theorg.springframework.beans.factory.config package) to be of use. Theapproach used in ServiceLocatorFactoryBean is similar to that of anotherutility class, ObjectFactoryCreatingFactoryBean, but it allows you to specifyyour own lookup interface as opposed to a Spring-specific lookup interface.Consult the JavaDocs for these classes as well as this blog entry foradditional information ServiceLocatorFactoryBean.

4.4.6.2 Arbitrary method replacement

A less useful form of method injection than lookup method Injection is the ability to replace

Page 78: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 78/81

arbitrary methods in a managed bean with another method implementation. Users may safelyskip the rest of this section until the functionality is actually needed.

With XML-based configuration metadata, you can use the replaced-method element to replacean existing method implementation with another, for a deployed bean. Consider the followingclass, 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.MethodReplacerinterface 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 likethis:

<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 thearguments is necessary only if the method is overloaded and multiple variants exist within theclass. For convenience, the type string for an argument may be a substring of the fully qualifiedtype 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 matchan argument type.

4.5 Bean scopes

When you create a bean definition, you create a recipe for creating actual instances of the classdefined by that bean definition. The idea that a bean definition is a recipe is important, because it

Page 79: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 79/81

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 theobjects created from a particular bean definition. This approach is powerful and flexible in thatyou can choose the scope of the objects you create through configuration instead of having tobake in the scope of an object at the Java class level. Beans can be defined to be deployed inone of a number of scopes: out of the box, the Spring Framework supports five scopes, three ofwhich 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 4.3. Bean scopes

Scope Description

singleton(Default) Scopes a single bean definition to a single object instance perSpring 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 theback of a single bean definition. Only valid in the context of a web-awareSpring ApplicationContext.

sessionScopes a single bean definition to the lifecycle of an HTTP Session. Onlyvalid in the context of a web-aware Spring ApplicationContext.

globalsession

Scopes a single bean definition to the lifecycle of a global HTTP Session.Typically only valid when used in a portlet context. Only valid in the context ofa web-aware Spring ApplicationContext.

Thread-scoped beans

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

4.5.1 The singleton scope

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

To put it another way, when you define a bean definition and it is scoped as a singleton, theSpring 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 requestsand 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 ofFour (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 Springsingleton is best described as per container and per bean. This means that if you define one

Page 80: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 80/81

bean for a particular class in a single Spring container, then the Spring container creates one andonly 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"/>

4.5.2 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 intoanother bean or you request it through a getBean() method call on the container. As a rule, usethe 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 nottypically 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.

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

<!-- using spring-beans-2.0.dtd --><bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>

In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototypebean: 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 initializationlifecycle callback methods are called on all objects regardless of scope, in the case ofprototypes, configured destruction lifecycle callbacks are not called. The client code must cleanup prototype-scoped objects and release expensive resources that the prototype bean(s) areholding. To get the Spring container to release resources held by prototype-scoped beans, tryusing a custom bean post-processor, which holds a reference to beans that need to be cleanedup.

In some respects, the Spring container's role in regard to a prototype-scoped bean is areplacement for the Java new operator. All lifecycle management past that point must be handledby the client. (For details on the lifecycle of a bean in the Spring container, see Section 4.6.1,“Lifecycle callbacks”.)

4.5.3 Singleton beans with prototype-bean dependencies

When you use singleton-scoped beans with dependencies on prototype beans, be aware thatdependencies 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 thendependency-injected into the singleton bean. The prototype instance is the sole instance that isever supplied to the singleton-scoped bean.

However, suppose you want the singleton-scoped bean to acquire a new instance of theprototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scopedbean into your singleton bean, because that injection occurs only once, when the Spring containeris instantiating the singleton bean and resolving and injecting its dependencies. If you need a new

Page 81: Reference Documentation

11/29/13 Reference Documentation

docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/ 81/81

instance of a prototype bean at runtime more than once, see Section 4.4.6, “Method injection”

4.5.4 Request, session, and global session scopes

The request, session, and global session scopes are only available if you use a web-awareSpring ApplicationContext implementation (such as XmlWebApplicationContext). If you usethese scopes with regular Spring IoC containers such as the ClassPathXmlApplicationContext,you get an IllegalStateException complaining about an unknown bean scope.

4.5.4.1 Initial web configuration

To support the scoping of beans at the request, session, and global session levels (web-scoped beans), some minor initial configuration is required before you define your beans. (Thisinitial 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 processedby the Spring DispatcherServlet, or DispatcherPortlet, then no special setup is necessary:DispatcherServlet and DispatcherPortlet already expose all relevant state.

If you use a Servlet 2.4+ web contai