Spring Framework

1279
Spring Framework Reference Documentation 3.0 Copyright © 2004-2010 Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, Rob Harrop, Alef Arendsen, Thomas Risberg, Darren Davison, Dmitriy Kopylenko, Mark Pollack, Thierry Templier, Erwin Vervaet, Portia Tung, Ben Hale, Adrian Colyer, John Lewis, Costin Leau, Mark Fisher, Sam Brannen, Ramnivas Laddad, Arjen Poutsma, Chris Beams, Tareq Abedrabbo, Andy Clement, Dave Syer, Oliver Gierke Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically. Table of Contents I. Overview of Spring Framework 1. 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

Transcript of Spring Framework

Spring Framework Reference Documentation3.0

Copyright 2004-2010 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 GierkeCopies 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.0 2. New Features and Enhancements in Spring 3.0 2.1. Java 51

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 2.5.3. The Inversion of Control (IoC) container 2.5.3.1. Java based bean metadata 2.5.3.2. Defining bean metadata within components 2.5.4. General purpose type conversion system and field formatting system 2.5.5. The Data Tier 2.5.6. The Web Tier 2.5.6.1. Comprehensive REST support 2.5.6.2. @MVC additions 2.5.7. Declarative model validation 2.5.8. Early support for Java EE 6 2.5.9. Support for embedded databases III. Core Technologies 3. The IoC container 3.1. Introduction to the Spring IoC container and beans 3.2. Container overview 3.2.1. Configuration metadata 3.2.2. Instantiating a container 3.2.2.1. Composing XML-based configuration metadata 3.2.3. Using the container 3.3. Bean overview 3.3.1. Naming beans 3.3.1.1. Aliasing a bean outside the bean definition 3.3.2. Instantiating beans 3.3.2.1. Instantiation with a constructor 3.3.2.2. Instantiation with a static factory method 3.3.2.3. Instantiation using an instance factory method 3.4. Dependencies 3.4.1. Dependency injection 3.4.1.1. Constructor-based dependency injection 3.4.1.2. Setter-based dependency injection 3.4.1.3. Dependency resolution process 3.4.1.4. Examples of dependency injection 3.4.2. Dependencies and configuration in detail 3.4.2.1. Straight values (primitives, Strings, and so on) 3.4.2.2. References to other beans (collaborators)2

3.4.2.3. Inner beans 3.4.2.4. Collections 3.4.2.5. Null and empty string values 3.4.2.6. XML shortcut with the p-namespace 3.4.2.7. Compound property names 3.4.3. Using depends-on 3.4.4. Lazy-initialized beans 3.4.5. Autowiring collaborators 3.4.5.1. Limitations and disadvantages of autowiring 3.4.5.2. Excluding a bean from autowiring 3.4.6. Method injection 3.4.6.1. Lookup method injection 3.4.6.2. Arbitrary method replacement 3.5. Bean scopes 3.5.1. The singleton scope 3.5.2. The prototype scope 3.5.3. Singleton beans with prototype-bean dependencies 3.5.4. Request, session, and global session scopes 3.5.4.1. Initial web configuration 3.5.4.2. Request scope 3.5.4.3. Session scope 3.5.4.4. Global session scope 3.5.4.5. Scoped beans as dependencies 3.5.5. Custom scopes 3.5.5.1. Creating a custom scope 3.5.5.2. Using a custom scope 3.6. Customizing the nature of a bean 3.6.1. Lifecycle callbacks 3.6.1.1. Initialization callbacks 3.6.1.2. Destruction callbacks 3.6.1.3. Default initialization and destroy methods 3.6.1.4. Combining lifecycle mechanisms 3.6.1.5. Startup and shutdown callbacks 3.6.1.6. Shutting down the Spring IoC container gracefully in non-web applications 3.6.2. ApplicationContextAware and BeanNameAware 3.6.3. Other Aware interfaces 3.7. Bean definition inheritance 3.8. Container extension points 3.8.1. Customizing beans using the BeanPostProcessor Interface 3.8.1.1. Example: Hello World, BeanPostProcessor-style3

3.8.1.2. Example: The RequiredAnnotationBeanPostProcessor 3.8.2. Customizing configuration metadata with BeanFactoryPostProcessor interface 3.8.2.1. Example: the PropertyPlaceholderConfigurer 3.8.2.2. Example: the PropertyOverrideConfigurer 3.8.3. Customizing instantiation logic with the FactoryBean Interface 3.9. Annotation-based container configuration 3.9.1. @Required 3.9.2. @Autowired and @Inject 3.9.3. Fine-tuning annotation-based autowiring with qualifiers 3.9.4. CustomAutowireConfigurer 3.9.5. @Resource 3.9.6. @PostConstruct and @PreDestroy 3.10. Classpath scanning and managed components 3.10.1. @Component and further stereotype annotations 3.10.2. Automatically detecting classes and registering bean definitions 3.10.3. Using filters to customize scanning 3.10.4. Defining bean metadata within components 3.10.5. Naming autodetected components 3.10.6. Providing a scope for autodetected components 3.10.7. Providing qualifier metadata with annotations 3.11. Java-based container configuration 3.11.1. Basic concepts: @Configuration and @Bean 3.11.2. Instantiating the Spring container using AnnotationConfigApplicationContext 3.11.2.1. Simple construction 3.11.2.2. Building the container programmatically using register(Class...) 3.11.2.3. Enabling component scanning with scan(String...) 3.11.2.4. Support for web applications with AnnotationConfigWebApplicationContext 3.11.3. Composing Java-based configurations 3.11.3.1. Using the @Import annotation 3.11.3.2. Combining Java and XML configuration 3.11.4. Using the @Bean annotation 3.11.4.1. Declaring a bean 3.11.4.2. Injecting dependencies 3.11.4.3. Receiving lifecycle callbacks 3.11.4.4. Specifying bean scope 3.11.4.5. Customizing bean naming 3.11.4.6. Bean aliasing

4

3.11.5. Further information about how Java-based configuration works internally 3.12. Registering a LoadTimeWeaver 3.13. Additional Capabilities of the ApplicationContext 3.13.1. Internationalization using MessageSource 3.13.2. Standard and Custom Events 3.13.3. Convenient access to low-level resources 3.13.4. Convenient ApplicationContext instantiation for web applications 3.13.5. Deploying a Spring ApplicationContext as a J2EE RAR file 3.14. The BeanFactory 3.14.1. BeanFactory or ApplicationContext? 3.14.2. Glue code and the evil singleton 4. Resources 4.1. Introduction 4.2. The Resource interface 4.3. Built-in Resource implementations 4.3.1. UrlResource 4.3.2. ClassPathResource 4.3.3. FileSystemResource 4.3.4. ServletContextResource 4.3.5. InputStreamResource 4.3.6. ByteArrayResource 4.4. The ResourceLoader 4.5. The ResourceLoaderAware interface 4.6. Resources as dependencies 4.7. Application contexts and Resource paths 4.7.1. Constructing application contexts 4.7.1.1. Constructing ClassPathXmlApplicationContext instances - shortcuts 4.7.2. Wildcards in application context constructor resource paths 4.7.2.1. Ant-style Patterns 4.7.2.2. The classpath*: prefix 4.7.2.3. Other notes relating to wildcards 4.7.3. FileSystemResource caveats 5. Validation, Data Binding, and Type Conversion 5.1. Introduction 5.2. Validation using Spring's Validator interface 5.3. Resolving codes to error messages 5.4. Bean manipulation and the BeanWrapper 5.4.1. Setting and getting basic and nested properties 5.4.2. Built-in PropertyEditor implementations 5.4.2.1. Registering additional custom PropertyEditors5

5.5. Spring 3 Type Conversion 5.5.1. Converter SPI 5.5.2. ConverterFactory 5.5.3. GenericConverter 5.5.3.1. ConditionalGenericConverter 5.5.4. ConversionService API 5.5.5. Configuring a ConversionService 5.5.6. Using a ConversionService programatically 5.6. Spring 3 Field Formatting 5.6.1. Formatter SPI 5.6.2. Annotation-driven Formatting 5.6.2.1. Format Annotation API 5.6.3. FormatterRegistry SPI 5.6.4. Configuring Formatting in Spring MVC 5.7. Spring 3 Validation 5.7.1. Overview of the JSR-303 Bean Validation API 5.7.2. Configuring a Bean Validation Implementation 5.7.2.1. Injecting a Validator 5.7.2.2. Configuring Custom Constraints 5.7.2.3. Additional Configuration Options 5.7.3. Configuring a DataBinder 5.7.4. Spring MVC 3 Validation 5.7.4.1. Triggering @Controller Input Validation 5.7.4.2. Configuring a Validator for use by Spring MVC 5.7.4.3. Configuring a JSR-303 Validator for use by Spring MVC 6. Spring Expression Language (SpEL) 6.1. Introduction 6.2. Feature Overview 6.3. Expression Evaluation using Spring's Expression Interface 6.3.1. The EvaluationContext interface 6.3.1.1. Type Conversion 6.4. Expression support for defining bean definitions 6.4.1. XML based configuration 6.4.2. Annotation-based configuration 6.5. Language Reference 6.5.1. Literal expressions 6.5.2. Properties, Arrays, Lists, Maps, Indexers 6.5.3. Inline lists 6.5.4. Array construction 6.5.5. Methods 6.5.6. Operators6

6.5.6.1. Relational operators 6.5.6.2. Logical operators 6.5.6.3. Mathematical operators 6.5.7. Assignment 6.5.8. Types 6.5.9. Constructors 6.5.10. Variables 6.5.10.1. The #this and #root variables 6.5.11. Functions 6.5.12. Bean references 6.5.13. Ternary Operator (If-Then-Else) 6.5.14. The Elvis Operator 6.5.15. Safe Navigation operator 6.5.16. Collection Selection 6.5.17. Collection Projection 6.5.18. Expression templating 6.6. Classes used in the examples 7. Aspect Oriented Programming with Spring 7.1. Introduction 7.1.1. AOP concepts 7.1.2. Spring AOP capabilities and goals 7.1.3. AOP Proxies 7.2. @AspectJ support 7.2.1. Enabling @AspectJ Support 7.2.2. Declaring an aspect 7.2.3. Declaring a pointcut 7.2.3.1. Supported Pointcut Designators 7.2.3.2. Combining pointcut expressions 7.2.3.3. Sharing common pointcut definitions 7.2.3.4. Examples 7.2.3.5. Writing good pointcuts 7.2.4. Declaring advice 7.2.4.1. Before advice 7.2.4.2. After returning advice 7.2.4.3. After throwing advice 7.2.4.4. After (finally) advice 7.2.4.5. Around advice 7.2.4.6. Advice parameters 7.2.4.7. Advice ordering 7.2.5. Introductions 7.2.6. Aspect instantiation models7

7.2.7. Example 7.3. Schema-based AOP support 7.3.1. Declaring an aspect 7.3.2. Declaring a pointcut 7.3.3. Declaring advice 7.3.3.1. Before advice 7.3.3.2. After returning advice 7.3.3.3. After throwing advice 7.3.3.4. After (finally) advice 7.3.3.5. Around advice 7.3.3.6. Advice parameters 7.3.3.7. Advice ordering 7.3.4. Introductions 7.3.5. Aspect instantiation models 7.3.6. Advisors 7.3.7. Example 7.4. Choosing which AOP declaration style to use 7.4.1. Spring AOP or full AspectJ? 7.4.2. @AspectJ or XML for Spring AOP? 7.5. Mixing aspect types 7.6. Proxying mechanisms 7.6.1. Understanding AOP proxies 7.7. Programmatic creation of @AspectJ Proxies 7.8. Using AspectJ with Spring applications 7.8.1. Using AspectJ to dependency inject domain objects with Spring 7.8.1.1. Unit testing @Configurable objects 7.8.1.2. Working with multiple application contexts 7.8.2. Other Spring aspects for AspectJ 7.8.3. Configuring AspectJ aspects using Spring IoC 7.8.4. Load-time weaving with AspectJ in the Spring Framework 7.8.4.1. A first example 7.8.4.2. Aspects 7.8.4.3. 'META-INF/aop.xml' 7.8.4.4. Required libraries (JARS) 7.8.4.5. Spring configuration 7.8.4.6. Environment-specific configuration 7.9. Further Resources 8. Spring AOP APIs 8.1. Introduction 8.2. Pointcut API in Spring 8.2.1. Concepts8

8.2.2. Operations on pointcuts 8.2.3. AspectJ expression pointcuts 8.2.4. Convenience pointcut implementations 8.2.4.1. Static pointcuts 8.2.4.2. Dynamic pointcuts 8.2.5. Pointcut superclasses 8.2.6. Custom pointcuts 8.3. Advice API in Spring 8.3.1. Advice lifecycles 8.3.2. Advice types in Spring 8.3.2.1. Interception around advice 8.3.2.2. Before advice 8.3.2.3. Throws advice 8.3.2.4. After Returning advice 8.3.2.5. Introduction advice 8.4. Advisor API in Spring 8.5. Using the ProxyFactoryBean to create AOP proxies 8.5.1. Basics 8.5.2. JavaBean properties 8.5.3. JDK- and CGLIB-based proxies 8.5.4. Proxying interfaces 8.5.5. Proxying classes 8.5.6. Using 'global' advisors 8.6. Concise proxy definitions 8.7. Creating AOP proxies programmatically with the ProxyFactory 8.8. Manipulating advised objects 8.9. Using the "autoproxy" facility 8.9.1. Autoproxy bean definitions 8.9.1.1. BeanNameAutoProxyCreator 8.9.1.2. DefaultAdvisorAutoProxyCreator 8.9.1.3. AbstractAdvisorAutoProxyCreator 8.9.2. Using metadata-driven auto-proxying 8.10. Using TargetSources 8.10.1. Hot swappable target sources 8.10.2. Pooling target sources 8.10.3. Prototype target sources 8.10.4. ThreadLocal target sources 8.11. Defining new Advice types 8.12. Further resources 9. Testing 9.1. Introduction to testing9

9.2. Unit testing 9.2.1. Mock objects 9.2.1.1. JNDI 9.2.1.2. Servlet API 9.2.1.3. Portlet API 9.2.2. Unit testing support classes 9.2.2.1. General utilities 9.2.2.2. Spring MVC 9.3. Integration testing 9.3.1. Overview 9.3.2. Goals of integration testing 9.3.2.1. Context management and caching 9.3.2.2. Dependency Injection of test fixtures 9.3.2.3. Transaction management 9.3.2.4. Support classes for integration testing 9.3.3. JDBC testing support 9.3.4. Annotations 9.3.5. Spring TestContext Framework 9.3.5.1. Key abstractions 9.3.5.2. Context management and caching 9.3.5.3. Dependency Injection of test fixtures 9.3.5.4. Transaction management 9.3.5.5. TestContext support classes 9.3.6. PetClinic example 9.4. Further Resources IV. Data Access 10. Transaction Management 10.1. Introduction to Spring Framework transaction management 10.2. Advantages of the Spring Framework's transaction support model 10.2.1. Global transactions 10.2.2. Local transactions 10.2.3. Spring Framework's consistent programming model 10.3. Understanding the Spring Framework transaction abstraction 10.4. Synchronizing resources with transactions 10.4.1. High-level synchronization approach 10.4.2. Low-level synchronization approach 10.4.3. TransactionAwareDataSourceProxy 10.5. Declarative transaction management 10.5.1. Understanding the Spring Framework's declarative transaction implementation 10.5.2. Example of declarative transaction implementation10

10.5.3. Rolling back a declarative transaction 10.5.4. Configuring different transactional semantics for different beans 10.5.5. settings 10.5.6. Using @Transactional 10.5.6.1. @Transactional settings 10.5.6.2. Multiple Transaction Managers with @Transactional 10.5.6.3. Custom shortcut annotations 10.5.7. Transaction propagation 10.5.7.1. Required 10.5.7.2. RequiresNew 10.5.7.3. Nested 10.5.8. Advising transactional operations 10.5.9. Using @Transactional with AspectJ 10.6. Programmatic transaction management 10.6.1. Using the TransactionTemplate 10.6.1.1. Specifying transaction settings 10.6.2. Using the PlatformTransactionManager 10.7. Choosing between programmatic and declarative transaction management 10.8. Application server-specific integration 10.8.1. IBM WebSphere 10.8.2. BEA WebLogic Server 10.8.3. Oracle OC4J 10.9. Solutions to common problems 10.9.1. Use of the wrong transaction manager for a specific DataSource 10.10. Further Resources 11. DAO support 11.1. Introduction 11.2. Consistent exception hierarchy 11.3. Annotations used for configuring DAO or Repository classes 12. Data access with JDBC 12.1. Introduction to Spring Framework JDBC 12.1.1. Choosing an approach for JDBC database access 12.1.2. Package hierarchy 12.2. Using the JDBC core classes to control basic JDBC processing and error handling 12.2.1. JdbcTemplate 12.2.1.1. Examples of JdbcTemplate class usage 12.2.1.2. JdbcTemplate best practices 12.2.2. NamedParameterJdbcTemplate 12.2.3. SimpleJdbcTemplate11

12.2.4. SQLExceptionTranslator 12.2.5. Executing statements 12.2.6. Running queries 12.2.7. Updating the database 12.2.8. Retrieving auto-generated keys 12.3. Controlling database connections 12.3.1. DataSource 12.3.2. DataSourceUtils 12.3.3. SmartDataSource 12.3.4. AbstractDataSource 12.3.5. SingleConnectionDataSource 12.3.6. DriverManagerDataSource 12.3.7. TransactionAwareDataSourceProxy 12.3.8. DataSourceTransactionManager 12.3.9. NativeJdbcExtractor 12.4. JDBC batch operations 12.4.1. Batch operations with the JdbcTemplate 12.4.2. Batch operations with the SimpleJdbcTemplate 12.5. Simplifying JDBC operations with the SimpleJdbc classes 12.5.1. Inserting data using SimpleJdbcInsert 12.5.2. Retrieving auto-generated keys using SimpleJdbcInsert 12.5.3. Specifying columns for a SimpleJdbcInsert 12.5.4. Using SqlParameterSource to provide parameter values 12.5.5. Calling a stored procedure with SimpleJdbcCall 12.5.6. Explicitly declaring parameters to use for a SimpleJdbcCall 12.5.7. How to define SqlParameters 12.5.8. Calling a stored function using SimpleJdbcCall 12.5.9. Returning ResultSet/REF Cursor from a SimpleJdbcCall 12.6. Modeling JDBC operations as Java objects 12.6.1. SqlQuery 12.6.2. MappingSqlQuery 12.6.3. SqlUpdate 12.6.4. StoredProcedure 12.7. Common problems with parameter and data value handling 12.7.1. Providing SQL type information for parameters 12.7.2. Handling BLOB and CLOB objects 12.7.3. Passing in lists of values for IN clause 12.7.4. Handling complex types for stored procedure calls 12.8. Embedded database support 12.8.1. Why use an embedded database? 12.8.2. Creating an embedded database instance using Spring XML12

12.8.3. Creating an embedded database instance programmatically 12.8.4. Extending the embedded database support 12.8.5. Using HSQL 12.8.6. Using H2 12.8.7. Using Derby 12.8.8. Testing data access logic with an embedded database 12.9. Initializing a DataSource 12.9.1. Initializing a database instance using Spring XML 12.9.1.1. Initialization of Other Components that Depend on the Database 13. Object Relational Mapping (ORM) Data Access 13.1. Introduction to ORM with Spring 13.2. General ORM integration considerations 13.2.1. Resource and transaction management 13.2.2. Exception translation 13.3. Hibernate 13.3.1. SessionFactory setup in a Spring container 13.3.2. Implementing DAOs based on plain Hibernate 3 API 13.3.3. Declarative transaction demarcation 13.3.4. Programmatic transaction demarcation 13.3.5. Transaction management strategies 13.3.6. Comparing container-managed and locally defined resources 13.3.7. Spurious application server warnings with Hibernate 13.4. JDO 13.4.1. PersistenceManagerFactory setup 13.4.2. Implementing DAOs based on the plain JDO API 13.4.3. Transaction management 13.4.4. JdoDialect 13.5. JPA 13.5.1. Three options for JPA setup in a Spring environment 13.5.1.1. LocalEntityManagerFactoryBean 13.5.1.2. Obtaining an EntityManagerFactory from JNDI 13.5.1.3. LocalContainerEntityManagerFactoryBean 13.5.1.4. Dealing with multiple persistence units 13.5.2. Implementing DAOs based on plain JPA 13.5.3. Transaction Management 13.5.4. JpaDialect 13.6. iBATIS SQL Maps 13.6.1. Setting up the SqlMapClient 13.6.2. Using SqlMapClientTemplate and SqlMapClientDaoSupport 13.6.3. Implementing DAOs based on plain iBATIS API 14. Marshalling XML using O/X Mappers13

14.1. Introduction 14.2. Marshaller and Unmarshaller 14.2.1. Marshaller 14.2.2. Unmarshaller 14.2.3. XmlMappingException 14.3. Using Marshaller and Unmarshaller 14.4. XML Schema-based Configuration 14.5. JAXB 14.5.1. Jaxb2Marshaller 14.5.1.1. XML Schema-based Configuration 14.6. Castor 14.6.1. CastorMarshaller 14.6.2. Mapping 14.7. XMLBeans 14.7.1. XmlBeansMarshaller 14.7.1.1. XML Schema-based Configuration 14.8. JiBX 14.8.1. JibxMarshaller 14.8.1.1. XML Schema-based Configuration 14.9. XStream 14.9.1. XStreamMarshaller V. The Web 15. Web MVC framework 15.1. Introduction to Spring Web MVC framework 15.1.1. Features of Spring Web MVC 15.1.2. Pluggability of other MVC implementations 15.2. The DispatcherServlet 15.3. Implementing Controllers 15.3.1. Defining a controller with @Controller 15.3.2. Mapping requests with @RequestMapping 15.3.2.1. URI Templates 15.3.2.2. Advanced @RequestMapping options 15.3.2.3. Supported handler method arguments and return types 15.3.2.4. Binding request parameters to method parameters with @RequestParam 15.3.2.5. Mapping the request body with the @RequestBody annotation 15.3.2.6. Mapping the response body with the @ResponseBody annotation 15.3.2.7. Using HttpEntity 15.3.2.8. Providing a link to data from the model with @ModelAttribute 15.3.2.9. Specifying attributes to store in a session with @SessionAttributes 15.3.2.10. Mapping cookie values with the @CookieValue annotation14

15.3.2.11. Mapping request header attributes with the @RequestHeader annotation 15.3.2.12. Customizing WebDataBinder initialization 15.4. Handler mappings 15.4.1. Intercepting requests - the HandlerInterceptor interface 15.5. Resolving views 15.5.1. Resolving views with the ViewResolver interface 15.5.2. Chaining ViewResolvers 15.5.3. Redirecting to views 15.5.3.1. RedirectView 15.5.3.2. The redirect: prefix 15.5.3.3. The forward: prefix 15.5.4. ContentNegotiatingViewResolver 15.6. Using locales 15.6.1. AcceptHeaderLocaleResolver 15.6.2. CookieLocaleResolver 15.6.3. SessionLocaleResolver 15.6.4. LocaleChangeInterceptor 15.7. Using themes 15.7.1. Overview of themes 15.7.2. Defining themes 15.7.3. Theme resolvers 15.8. Spring's multipart (fileupload) support 15.8.1. Introduction 15.8.2. Using the MultipartResolver 15.8.3. Handling a file upload in a form 15.9. Handling exceptions 15.9.1. HandlerExceptionResolver 15.9.2. @ExceptionHandler 15.10. Convention over configuration support 15.10.1. The Controller ControllerClassNameHandlerMapping 15.10.2. The Model ModelMap (ModelAndView) 15.10.3. The View - RequestToViewNameTranslator 15.11. ETag support 15.12. Configuring Spring MVC 15.12.1. mvc:annotation-driven 15.12.2. mvc:interceptors 15.12.3. mvc:view-controller 15.12.4. mvc:resources 15.12.5. mvc:default-servlet-handler 15.13. More Spring Web MVC Resources15

16. View technologies 16.1. Introduction 16.2. JSP & JSTL 16.2.1. View resolvers 16.2.2. 'Plain-old' JSPs versus JSTL 16.2.3. Additional tags facilitating development 16.2.4. Using Spring's form tag library 16.2.4.1. Configuration 16.2.4.2. The form tag 16.2.4.3. The input tag 16.2.4.4. The checkbox tag 16.2.4.5. The checkboxes tag 16.2.4.6. The radiobutton tag 16.2.4.7. The radiobuttons tag 16.2.4.8. The password tag 16.2.4.9. The select tag 16.2.4.10. The option tag 16.2.4.11. The options tag 16.2.4.12. The textarea tag 16.2.4.13. The hidden tag 16.2.4.14. The errors tag 16.2.4.15. HTTP Method Conversion 16.3. Tiles 16.3.1. Dependencies 16.3.2. How to integrate Tiles 16.3.2.1. UrlBasedViewResolver 16.3.2.2. ResourceBundleViewResolver 16.3.2.3. SimpleSpringPreparerFactory and SpringBeanPreparerFactory 16.4. Velocity & FreeMarker 16.4.1. Dependencies 16.4.2. Context configuration 16.4.3. Creating templates 16.4.4. Advanced configuration 16.4.4.1. velocity.properties 16.4.4.2. FreeMarker 16.4.5. Bind support and form handling 16.4.5.1. The bind macros 16.4.5.2. Simple binding 16.4.5.3. Form input generation macros 16.4.5.4. HTML escaping and XHTML compliance 16.5. XSLT16

16.5.1. My First Words 16.5.1.1. Bean definitions 16.5.1.2. Standard MVC controller code 16.5.1.3. Convert the model data to XML 16.5.1.4. Defining the view properties 16.5.1.5. Document transformation 16.5.2. Summary 16.6. Document views (PDF/Excel) 16.6.1. Introduction 16.6.2. Configuration and setup 16.6.2.1. Document view definitions 16.6.2.2. Controller code 16.6.2.3. Subclassing for Excel views 16.6.2.4. Subclassing for PDF views 16.7. JasperReports 16.7.1. Dependencies 16.7.2. Configuration 16.7.2.1. Configuring the ViewResolver 16.7.2.2. Configuring the Views 16.7.2.3. About Report Files 16.7.2.4. Using JasperReportsMultiFormatView 16.7.3. Populating the ModelAndView 16.7.4. Working with Sub-Reports 16.7.4.1. Configuring Sub-Report Files 16.7.4.2. Configuring Sub-Report Data Sources 16.7.5. Configuring Exporter Parameters 16.8. Feed Views 16.9. XML Marshalling View 16.10. JSON Mapping View 17. Integrating with other web frameworks 17.1. Introduction 17.2. Common configuration 17.3. JavaServer Faces 1.1 and 1.2 17.3.1. DelegatingVariableResolver (JSF 1.1/1.2) 17.3.2. SpringBeanVariableResolver (JSF 1.1/1.2) 17.3.3. SpringBeanFacesELResolver (JSF 1.2+) 17.3.4. FacesContextUtils 17.4. Apache Struts 1.x and 2.x 17.4.1. ContextLoaderPlugin 17.4.1.1. DelegatingRequestProcessor 17.4.1.2. DelegatingActionProxy17

17.4.2. ActionSupport Classes 17.5. WebWork 2.x 17.6. Tapestry 3.x and 4.x 17.6.1. Injecting Spring-managed beans 17.6.1.1. Dependency Injecting Spring Beans into Tapestry pages 17.6.1.2. Component definition files 17.6.1.3. Adding abstract accessors 17.6.1.4. Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style 17.7. Further Resources 18. Portlet MVC Framework 18.1. Introduction 18.1.1. Controllers - The C in MVC 18.1.2. Views - The V in MVC 18.1.3. Web-scoped beans 18.2. The DispatcherPortlet 18.3. The ViewRendererServlet 18.4. Controllers 18.4.1. AbstractController and PortletContentGenerator 18.4.2. Other simple controllers 18.4.3. Command Controllers 18.4.4. PortletWrappingController 18.5. Handler mappings 18.5.1. PortletModeHandlerMapping 18.5.2. ParameterHandlerMapping 18.5.3. PortletModeParameterHandlerMapping 18.5.4. Adding HandlerInterceptors 18.5.5. HandlerInterceptorAdapter 18.5.6. ParameterMappingInterceptor 18.6. Views and resolving them 18.7. Multipart (file upload) support 18.7.1. Using the PortletMultipartResolver 18.7.2. Handling a file upload in a form 18.8. Handling exceptions 18.9. Annotation-based controller configuration 18.9.1. Setting up the dispatcher for annotation support 18.9.2. Defining a controller with @Controller 18.9.3. Mapping requests with @RequestMapping 18.9.4. Supported handler method arguments 18.9.5. Binding request parameters to method parameters with @RequestParam18

18.9.6. Providing a link to data from the model with @ModelAttribute 18.9.7. Specifying attributes to store in a Session with @SessionAttributes 18.9.8. Customizing WebDataBinder initialization 18.9.8.1. Customizing data binding with @InitBinder 18.9.8.2. Configuring a custom WebBindingInitializer 18.10. Portlet application deployment VI. Integration 19. Remoting and web services using Spring 19.1. Introduction 19.2. Exposing services using RMI 19.2.1. Exporting the service using the RmiServiceExporter 19.2.2. Linking in the service at the client 19.3. Using Hessian or Burlap to remotely call services via HTTP 19.3.1. Wiring up the DispatcherServlet for Hessian and co. 19.3.2. Exposing your beans by using the HessianServiceExporter 19.3.3. Linking in the service on the client 19.3.4. Using Burlap 19.3.5. Applying HTTP basic authentication to a service exposed through Hessian or Burlap 19.4. Exposing services using HTTP invokers 19.4.1. Exposing the service object 19.4.2. Linking in the service at the client 19.5. Web services 19.5.1. Exposing servlet-based web services using JAX-RPC 19.5.2. Accessing web services using JAX-RPC 19.5.3. Registering JAX-RPC Bean Mappings 19.5.4. Registering your own JAX-RPC Handler 19.5.5. Exposing servlet-based web services using JAX-WS 19.5.6. Exporting standalone web services using JAX-WS 19.5.7. Exporting web services using the JAX-WS RI's Spring support 19.5.8. Accessing web services using JAX-WS 19.6. JMS 19.6.1. Server-side configuration 19.6.2. Client-side configuration 19.7. Auto-detection is not implemented for remote interfaces 19.8. Considerations when choosing a technology 19.9. Accessing RESTful services on the Client 19.9.1. RestTemplate 19.9.1.1. Dealing with request and response headers 19.9.2. HTTP Message Conversion 19.9.2.1. StringHttpMessageConverter19

19.9.2.2. FormHttpMessageConverter 19.9.2.3. ByteArrayMessageConverter 19.9.2.4. MarshallingHttpMessageConverter 19.9.2.5. MappingJacksonHttpMessageConverter 19.9.2.6. SourceHttpMessageConverter 19.9.2.7. BufferedImageHttpMessageConverter 20. Enterprise JavaBeans (EJB) integration 20.1. Introduction 20.2. Accessing EJBs 20.2.1. Concepts 20.2.2. Accessing local SLSBs 20.2.3. Accessing remote SLSBs 20.2.4. Accessing EJB 2.x SLSBs versus EJB 3 SLSBs 20.3. Using Spring's EJB implementation support classes 20.3.1. EJB 2.x base classes 20.3.2. EJB 3 injection interceptor 21. JMS (Java Message Service) 21.1. Introduction 21.2. Using Spring JMS 21.2.1. JmsTemplate 21.2.2. Connections 21.2.2.1. Caching Messaging Resources 21.2.2.2. SingleConnectionFactory 21.2.2.3. CachingConnectionFactory 21.2.3. Destination Management 21.2.4. Message Listener Containers 21.2.4.1. SimpleMessageListenerContainer 21.2.4.2. DefaultMessageListenerContainer 21.2.5. Transaction management 21.3. Sending a Message 21.3.1. Using Message Converters 21.3.2. SessionCallback and ProducerCallback 21.4. Receiving a message 21.4.1. Synchronous Reception 21.4.2. Asynchronous Reception - Message-Driven POJOs 21.4.3. The SessionAwareMessageListener interface 21.4.4. The MessageListenerAdapter 21.4.5. Processing messages within transactions 21.5. Support for JCA Message Endpoints 21.6. JMS Namespace Support 22. JMX20

22.1. Introduction 22.2. Exporting your beans to JMX 22.2.1. Creating an MBeanServer 22.2.2. Reusing an existing MBeanServer 22.2.3. Lazy-initialized MBeans 22.2.4. Automatic registration of MBeans 22.2.5. Controlling the registration behavior 22.3. Controlling the management interface of your beans 22.3.1. The MBeanInfoAssembler Interface 22.3.2. Using Source-Level Metadata (JDK 5.0 annotations) 22.3.3. Source-Level Metadata Types 22.3.4. The AutodetectCapableMBeanInfoAssembler interface 22.3.5. Defining management interfaces using Java interfaces 22.3.6. Using MethodNameBasedMBeanInfoAssembler 22.4. Controlling the ObjectNames for your beans 22.4.1. Reading ObjectNames from Properties 22.4.2. Using the MetadataNamingStrategy 22.4.3. The element 22.5. JSR-160 Connectors 22.5.1. Server-side Connectors 22.5.2. Client-side Connectors 22.5.3. JMX over Burlap/Hessian/SOAP 22.6. Accessing MBeans via Proxies 22.7. Notifications 22.7.1. Registering Listeners for Notifications 22.7.2. Publishing Notifications 22.8. Further Resources 23. JCA CCI 23.1. Introduction 23.2. Configuring CCI 23.2.1. Connector configuration 23.2.2. ConnectionFactory configuration in Spring 23.2.3. Configuring CCI connections 23.2.4. Using a single CCI connection 23.3. Using Spring's CCI access support 23.3.1. Record conversion 23.3.2. The CciTemplate 23.3.3. DAO support 23.3.4. Automatic output record generation 23.3.5. Summary 23.3.6. Using a CCI Connection and Interaction directly21

23.3.7. Example for CciTemplate usage 23.4. Modeling CCI access as operation objects 23.4.1. MappingRecordOperation 23.4.2. MappingCommAreaOperation 23.4.3. Automatic output record generation 23.4.4. Summary 23.4.5. Example for MappingRecordOperation usage 23.4.6. Example for MappingCommAreaOperation usage 23.5. Transactions 24. Email 24.1. Introduction 24.2. Usage 24.2.1. Basic MailSender and SimpleMailMessage usage 24.2.2. Using the JavaMailSender and the MimeMessagePreparator 24.3. Using the JavaMail MimeMessageHelper 24.3.1. Sending attachments and inline resources 24.3.1.1. Attachments 24.3.1.2. Inline resources 24.3.2. Creating email content using a templating library 24.3.2.1. A Velocity-based example 25. Task Execution and Scheduling 25.1. Introduction 25.2. The Spring TaskExecutor abstraction 25.2.1. TaskExecutor types 25.2.2. Using a TaskExecutor 25.3. The Spring TaskScheduler abstraction 25.3.1. The Trigger interface 25.3.2. Trigger implementations 25.3.3. TaskScheduler implementations 25.4. The Task Namespace 25.4.1. The 'scheduler' element 25.4.2. The 'executor' element 25.4.3. The 'scheduled-tasks' element 25.5. Annotation Support for Scheduling and Asynchronous Execution 25.5.1. The @Scheduled Annotation 25.5.2. The @Async Annotation 25.5.3. The Element 25.6. Using the OpenSymphony Quartz Scheduler 25.6.1. Using the JobDetailBean 25.6.2. Using the MethodInvokingJobDetailFactoryBean 25.6.3. Wiring up jobs using triggers and the SchedulerFactoryBean22

25.7. Using JDK Timer support 25.7.1. Creating custom timers 25.7.2. Using the MethodInvokingTimerTaskFactoryBean 25.7.3. Wrapping up: setting up the tasks using the TimerFactoryBean 26. Dynamic language support 26.1. Introduction 26.2. A first example 26.3. Defining beans that are backed by dynamic languages 26.3.1. Common concepts 26.3.1.1. The element 26.3.1.2. Refreshable beans 26.3.1.3. Inline dynamic language source files 26.3.1.4. Understanding Constructor Injection in the context of dynamiclanguage-backed beans 26.3.2. JRuby beans 26.3.3. Groovy beans 26.3.3.1. Customising Groovy objects via a callback 26.3.4. BeanShell beans 26.4. Scenarios 26.4.1. Scripted Spring MVC Controllers 26.4.2. Scripted Validators 26.5. Bits and bobs 26.5.1. AOP - advising scripted beans 26.5.2. Scoping 26.6. Further Resources VII. Appendices A. Classic Spring Usage A.1. Classic ORM usage A.1.1. Hibernate A.1.1.1. The HibernateTemplate A.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 MVC A.3. JMS Usage A.3.1. JmsTemplate A.3.2. Asynchronous Message Reception A.3.3. Connections A.3.4. Transaction Management23

B. Classic Spring AOP Usage B.1. Pointcut API in Spring B.1.1. Concepts B.1.2. Operations on pointcuts B.1.3. AspectJ expression pointcuts B.1.4. Convenience pointcut implementations B.1.4.1. Static pointcuts B.1.4.2. Dynamic pointcuts B.1.5. Pointcut superclasses B.1.6. Custom pointcuts B.2. Advice API in Spring B.2.1. Advice lifecycles B.2.2. Advice types in Spring B.2.2.1. Interception around advice B.2.2.2. Before advice B.2.2.3. Throws advice B.2.2.4. After Returning advice B.2.2.5. Introduction advice B.3. Advisor API in Spring B.4. Using the ProxyFactoryBean to create AOP proxies B.4.1. Basics B.4.2. JavaBean properties B.4.3. JDK- and CGLIB-based proxies B.4.4. Proxying interfaces B.4.5. Proxying classes B.4.6. Using 'global' advisors B.5. Concise proxy definitions B.6. Creating AOP proxies programmatically with the ProxyFactory B.7. Manipulating advised objects B.8. Using the "autoproxy" facility B.8.1. Autoproxy bean definitions B.8.1.1. BeanNameAutoProxyCreator B.8.1.2. DefaultAdvisorAutoProxyCreator B.8.1.3. AbstractAdvisorAutoProxyCreator B.8.2. Using metadata-driven auto-proxying B.9. Using TargetSources B.9.1. Hot swappable target sources B.9.2. Pooling target sources B.9.3. Prototype target sources B.9.4. ThreadLocal target sources B.10. Defining new Advice types24

B.11. Further resources C. XML Schema-based configuration C.1. Introduction C.2. XML Schema-based configuration C.2.1. Referencing the schemas C.2.2. The util schema C.2.2.1. C.2.2.2. C.2.2.3. C.2.2.4. C.2.2.5. C.2.2.6. C.2.3. The jee schema C.2.3.1. (simple) C.2.3.2. (with single JNDI environment setting) C.2.3.3. (with multiple JNDI environment settings) C.2.3.4. (complex) C.2.3.5. (simple) C.2.3.6. (complex) C.2.3.7. C.2.4. The lang schema C.2.5. The jms schema C.2.6. The tx (transaction) schema C.2.7. The aop schema C.2.8. The context schema C.2.8.1. C.2.8.2. C.2.8.3. C.2.8.4. C.2.8.5. C.2.8.6. C.2.9. The tool schema C.2.10. The beans schema D. Extensible XML authoring D.1. Introduction D.2. Authoring the schema D.3. Coding a NamespaceHandler D.4. Coding a BeanDefinitionParser D.5. Registering the handler and the schema D.5.1. 'META-INF/spring.handlers' D.5.2. 'META-INF/spring.schemas'25

D.6. Using a custom extension in your Spring XML configuration D.7. Meatier examples D.7.1. Nesting custom tags within custom tags D.7.2. Custom attributes on 'normal' elements D.8. Further Resources E. spring-beans-2.0.dtd F. spring.tld F.1. Introduction F.2. The bind tag F.3. The escapeBody tag F.4. The hasBindErrors tag F.5. The htmlEscape tag F.6. The message tag F.7. The nestedPath tag F.8. The theme tag F.9. The transform tag F.10. The url tag F.11. The eval tag G. spring-form.tld G.1. Introduction G.2. The checkbox tag G.3. The checkboxes tag G.4. The errors tag G.5. The form tag G.6. The hidden tag G.7. The input tag G.8. The label tag G.9. The option tag G.10. The options tag G.11. The password tag G.12. The radiobutton tag G.13. The radiobuttons tag G.14. The select tag G.15. The textarea tag

26

Part I. Overview of Spring FrameworkThe Spring Framework is a lightweight solution and a potential one-stop-shop for building your enterprise-ready applications. However, Spring is modular, allowing you to use only those parts that you need, without having to bring in the rest. You can use the IoC container, with Struts on top, but you can also use only the Hibernate integration code or the JDBC abstraction layer. The Spring Framework supports declarative transaction management, remote access to your logic through RMI or web services, and various options for persisting your data. It offers a full-featured MVC framework, and enables you to integrate AOP transparently into your software. Spring is designed to be non-intrusive, meaning that your domain logic code generally has no dependencies on the framework itself. In your integration layer (such as the data access layer), some dependencies on the data access technology and the Spring libraries will exist. However, it should be easy to isolate these dependencies from the rest of your code base. This document is a reference guide to Spring Framework features. If you have any requests, comments, or questions on this document, please post them on the user mailing list or on the support forums at http://forum.springsource.org/.

1. Introduction to Spring FrameworkSpring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so you can focus on your application. Spring enables you to build applications from plain old Java objects (POJOs) and to apply enterprise services non-invasively to POJOs. This capability applies to the Java SE programming model and to full and partial Java EE. Examples of how you, as an application developer, can use the Spring platform advantage:

Make a Java method execute in a database transaction without having to deal with transaction APIs. Make a local Java method a remote procedure without having to deal with remote APIs. Make a local Java method a management operation without having to deal with JMX APIs.27

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

1.1 Dependency Injection and Inversion of ControlBackground The question is, what aspect of control are [they] inverting? Martin Fowler posed this question about Inversion of Control (IoC) on his site in 2004. Fowler suggested renaming the principle to make it more self-explanatory and came up with Dependency Injection. For insight into IoC and DI, refer to Fowler's article athttp://martinfowler.com/articles/injection.html.

Java applications -- a loose term that runs the gamut from constrained applets to n-tier server-side enterprise applications -- typically consist of objects that collaborate to form the application proper. Thus the objects in an application have dependencies on each other. Although the Java platform provides a wealth of application development functionality, it lacks the means to organize the basic building blocks into a coherent whole, leaving that task to architects and developers. True, you can use design patterns such as Factory,Abstract Factory, Builder, Decorator, and Service Locator to compose the various classes and object instances that make up an application. However, these patterns are simply that: best practices given a name, with a description of what the pattern does, where to apply it, the problems it addresses, and so forth. Patterns are formalized best practices that you must implement yourself in your application. The Spring Framework Inversion of Control (IoC) component addresses this concern by providing a formalized means of composing disparate components into a fully working application ready for use. The Spring Framework codifies formalized design patterns as first-class objects that you can integrate into your own application(s). Numerous organizations and institutions use the Spring Framework in this manner to engineer robust,maintainable applications.

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

28

Overview of the Spring Framework1.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 IoC and Dependency Injection features. TheBeanFactory is a sophisticated implementation of the factory pattern. It removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic. The Context module builds on the solid base provided by the Core and Beans modules: it is a means to access objects in a framework-style manner that is similar to a JNDI registry. The Context module inherits its features from the Beans module and adds support for internationalization (using, for example, resource bundles), event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container. The Context module also29

supports Java EE features such as EJB, JMX ,and basic remoting. The ApplicationContext interface is the focal point of the Context module. The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime. It is an extension of the unified expression language (unified EL) as specified in the JSP 2.1 specification. The language supports setting and getting property values, property assignment, method invocation, accessing the context of arrays, collections and indexers, logical and arithmetic operators, named variables, and retrieval of objects by name from Spring's IoC container. It also supports list projection and selection as well as common list aggregations.1.2.2 Data Access/Integration

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules. The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. The 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 the simple declarative transaction management feature mentioned previously. The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream. The Java Messaging Service (JMS) module contains features for producing and consuming messages. The Transaction module supports programmatic and declarative transaction management for classes 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.

30

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 webrelated parts of Spring's remoting support. The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for web applications. Spring's MVC framework provides a clean separation between domain model code and 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 tier within a Spring application. Note that this support is now deprecated as of Spring 3.0. Consider migrating 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 environment and mirrors the functionality of Web-Servlet module.1.2.4 AOP and Instrumentation

Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, methodinterceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. Using source-level metadata functionality, you can also incorporate behavioral information into your code, in a manner similar to that of .NET attributes. The separate Aspects module provides integration with AspectJ. The Instrumentation module provides class instrumentation support classloader implementations to be used in certain application servers.1.2.5 Test

and

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

31

1.3 Usage scenariosThe building blocks described previously make Spring a logical choice in many scenarios, from applets to full-fledged enterprise applications that use Spring's transaction management functionality and web framework integration.

Typical full-fledged Spring web application Spring's declarative transaction management features make the web application fully transactional, just as it would be if you used EJB container-managed transactions. All your custom business logic can be implemented with simple POJOs and managed by Spring's IoC container. Additional services include support for sending email and validation that is independent of the web layer, which lets you choose where to execute validation rules. Spring's ORM support is integrated with JPA, Hibernate, JDO and iBatis; for example, when using Hibernate, you can continue to use your existing mapping files and standard32

Hibernate SessionFactory configuration. Form controllers seamlessly integrate the web-layer with the domain model, removing the need for ActionForms or other classes that transform HTTP parameters to values for your domain model.

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

33

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 applications is not difficult.

34

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

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

35

If you are going to use Spring you need to get a copy of the jar libraries that comprise the pieces of Spring that you need. To make this easier Spring is packaged as a set of modules that separate the dependencies as much as possible, so for example if you don't want to write a web application you don't need the spring-web modules. To refer to Spring library modules in this guide we use a shorthand naming convention spring-* or spring-*.jar, where "*" represents the short name for the module (e.g. spring-core, spring-webmvc, spring-jms, etc.). The actual jar file name that you use may be in this form (see below) or it may not, and normally it also has a version number in the file name (e.g. spring-core3.0.0.RELEASE.jar). In general, Spring publishes its artifacts to four different places:

On the community download site http://www.springsource.org/downloads/community. Here you find all the Spring jars bundled together into a zip file for easy download. The names of the jars here since version 3.0 are in the form org.springframework.*.jar. Maven Central, which is the default repository that Maven queries, and does not require any special configuration to use. Many of the common libraries that Spring depends on also are available from Maven Central and a large section of the Spring community uses Maven for dependency management, so this is convenient for them. The names of the jars here are in the form spring-*-.jar and the Maven groupId is org.springframework. The Enterprise Bundle Repository (EBR), which is run by SpringSource and also hosts all the libraries that integrate with Spring. Both Maven and Ivy repositories are available here for all Spring jars and their dependencies, plus a large number of other common libraries that people use in applications with Spring. Both full releases and also milestones and development snapshots are deployed here. The names of the jar files are in the same form as the community download (org.springframework.*.jar), and the dependencies 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 and milestone releases (a copy of the final releases is also held here). The jar file names are in the same form as Maven Central, so this is a useful place to get development versions of Spring to use with other libraries depoyed in Maven Central.

36

So the first thing you need to decide is how to manage your dependencies: most people use an automated system like Maven or Ivy, but you can also do it manually by downloading all the jars yourself. When obtaining Spring with Maven or Ivy you have then to decide which place you'll get it from. In general, if you care about OSGi, use the EBR, since it houses OSGi compatible artifacts for all of Spring's dependencies, such as Hibernate and Freemarker. If OSGi does not matter to you, either place works, though there are some pros and cons between them. In general, pick one place or the other for your project; do not mix them. This is particularly important since EBR artifacts necessarily use a different naming convention than Maven Central artifacts. Table 1.1. Comparison of Maven Central and SpringSource EBR RepositoriesMaven Central Yes Hundreds; those that Spring integrates with Yes Tens of thousands; all kinds No EBR

e Not explicit

Varies. Newer artifacts often use domain name, e.g. org.slf4j. Older ones often just use the Domain name of origin or main package root, e.g. org.springframework artifact name, e.g. log4j. Bundle Symbolic Name, derived from the main package root, e.g. Varies. Generally the project or module name, org.springframework.beans. If the jar had to be patched to ensure OSGi using a hyphen "-" separator, e.g. spring-core, compliance then com.springsource is appended, e.g. logj4. com.springsource.org.apache.log4j Varies. Many new artifacts use m.m.m or m.m.m.X (with m=digit, X=text). Older ones OSGi version number m.m.m.X, e.g. 3.0.0.RC3. The text qualifier imposes use m.m. Some neither. Ordering is defined but alphabetic ordering on versions with the same numeric values. not often relied on, so not strictly reliable. Usually automatic via rsync or source control updates. Project authors can upload individual Manual (JIRA processed by SpringSource) jars to JIRA. Extensive for OSGi manifest, Maven POM and Ivy metadata. QA performe By policy. Accuracy is responsibility of authors. Spring team. Contegix. Funded by Sonatype with several S3 funded by SpringSource. mirrors. Various http://www.springsource.com/repository Integration through STS with Maven dependency management Extensive integration through STS with Maven, Roo, CloudFoundry

37

1.3.1.1 Spring Dependencies and Depending on SpringAlthough Spring provides integration and support for a huge range of enterprise and other external tools, it intentionally keeps its mandatory dependencies to an absolute minimum: you shouldn't have to locate and download (even automatically) a large number of jar libraries in order to use Spring for simple use cases. For basic dependency injection there is only one mandatory external dependency, and that is for logging (see below for a more detailed description of logging options). Next we outline the basic steps needed to configure an application that depends on Spring, first with Maven and then with Ivy. In all cases, if anything is unclear, refer to the documentation of your dependency management system, or look at some sample code - Spring itself uses Ivy to manage dependencies when it is building, and our samples mostly use Maven.

1.3.1.2 Maven Dependency ManagementIf you are using Maven for dependency management you don't even need to supply the logging dependency explicitly. For example, to create an application context and use dependency injection to configure an application, your Maven dependencies will look like this: org.springframework spring-context 3.0.0.RELEASE runtime

That's it. Note the scope can be declared as runtime if you don't need to compile against Spring APIs, which is typically the case for basic dependency injection use cases. We used the Maven Central naming conventions in the example above, so that works with Maven Central or the SpringSource S3 Maven repository. To use the S3 Maven repository (e.g. for milestones or developer snaphots), you need to specify the repository location in your Maven configuration. For full releases:

38

com.springsource.repository.maven.release http://maven.springframework.org/release/ false

For milestones: com.springsource.repository.maven.milestone http://maven.springframework.org/milestone/ false

And for snapshots: com.springsource.repository.maven.snapshot http://maven.springframework.org/snapshot/ true

To use the SpringSource EBR you would need to use a different naming convention for the dependencies. The names are usually easy to guess, e.g. in this case it is: org.springframework org.springframework.context 3.0.0.RELEASE runtime

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

39

com.springsource.repository.bundles.release http://repository.springsource.com/maven/bundles/release/

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

1.3.1.3 Ivy Dependency ManagementIf you prefer to use Ivy to manage dependencies then there are similar names and configuration options. To configure Ivy to point to the SpringSource EBR add the following resolvers to your ivysettings.xml:

The XML above is not valid because the lines are too long - if you copy-paste then remove the extra 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 details page for the bundle in question in the repository browser and40

you'll find an Ivy snippet ready for you to include in your dependencies section. For example (in ivy.xml):

1.3.2 Logging

Logging is a very important dependency for Spring because a) it is the only mandatory external dependency, b) everyone likes to see some output from the tools they are using, and c) Spring integrates with lots of other tools all of which have also made a choice of logging dependency. One of the goals of an application developer is often to have unified logging configured in a central place for the whole application, including all external components. This is more difficult than it might have been since there are so many choices of logging framework. The mandatory logging dependency in Spring is the Jakarta Commons Logging API (JCL). We compile against JCL and we also make JCL Logobjects visible for classes that extend the Spring Framework. It's important to users that all versions of Spring use the same logging library: migration is easy because backwards compatibility is preserved even with applications that extend Spring. The way we do this is to make one of the modules in Spring depend explicitly on commonslogging (the canonical implementation of JCL), and then make all the other modules depend on that at compile time. If you are using Maven for example, and wondering where you picked up the dependency on commons-logging, then it is from Spring and specifically from the central module called spring-core. The nice thing about commons-logging is that you don't need anything else to make your application work. It has a runtime discovery algorithm that looks for other logging frameworks in well known places on the classpath and uses one that it thinks is appropriate (or you can tell it which one if you need to). If nothing else is available you get pretty nice looking logs just from the JDK (java.util.logging or JUL for short). You should find that your Spring application works and logs happily to the console out of the box in most situations, and that's important.

1.3.2.1 Not Using Commons LoggingUnfortunately, the runtime discovery algorithm in commons-logging, while convenient for the end-user, is problematic. If we could turn back the clock and start Spring now as a new project it would use a different logging dependency. The first choice

41

would probably be the Simple Logging Facade for Java (SLF4J), which is also used by a lot of other tools that people use with Spring inside their applications. Switching off commons-logging is easy: just make sure it isn't on the classpath at runtime. In Maven terms you exclude the dependency, and because of the way that the Spring dependencies are declared, you only have to do that once. org.springframework spring-context 3.0.0.RELEASE runtime commons-logging commons-logging

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

1.3.2.2 Using SLF4JSLF4J is a cleaner dependency and more efficient at runtime than commonslogging because it uses compile-time bindings instead of runtime discovery of the other logging frameworks it integrates. This also means that you have to be more explicit about what you want to happen at runtime, and declare it or configure it accordingly. SLF4J provides bindings to many common logging frameworks, so you can usually choose one that you already use, and bind to that for configuration and management. SLF4J provides bindings to many common logging frameworks, including JCL, and it also does the reverse: bridges between other logging frameworks and itself. So to use SLF4J with Spring you need to replace the commons-logging dependency with the SLF4J-JCL bridge. Once you have done that then logging calls from within Spring will be translated into logging calls to the SLF4J API, so if other libraries in your application use that API, then you have a single place to configure and manage logging.

42

A common choice might be to bridge Spring to SLF4J, and then provide explicit binding from SLF4J to Log4J. You need to supply 4 dependencies (and exclude the existing commons-logging): the bridge, the SLF4J API, the binding to Log4J, and the Log4J implementation itself. In Maven you would do that like this org.springframework spring-context 3.0.0.RELEASE runtime commons-logging commons-logging org.slf4j jcl-over-slf4j 1.5.8 runtime org.slf4j slf4j-api 1.5.8 runtime org.slf4j slf4j-log4j12 1.5.8 runtime log4j log4j 1.2.14 runtime

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 vanillacommons-logging with respect to classloader issues, notably if you are in a strict container like an OSGi platform. Allegedly there is also a performance benefit because the bindings are at compile-time not runtime.

43

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

1.3.2.3 Using Log4JMany people use Log4j as a logging framework for configuration and management purposes. It's efficient and well-established, and in fact it's what we use at runtime when we build and test Spring. Spring also provides some utilities for configuring and initializing Log4j, so it has an optional compile-time dependency on Log4j in some modules. To make Log4j work with the default JCL dependency (commons-logging) all you need to do is put Log4j on the classpath, and provide it with a configuration file (log4j.properties or log4j.xml in the root of the classpath). So for Maven users this is your dependency declaration: org.springframework spring-context 3.0.0.RELEASE runtime log4j log4j 1.2.14 runtime

And here's a sample log4j.properties for logging to the console:log4j.rootCategory=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n log4j.category.org.springframework.beans.factory=DEBUG

44

Runtime Containers with Native JCL

Many people run their Spring applications in a container that itself provides an implementation of JCL. IBM Websphere Application Server (WAS) is the archetype. This often causes problems, and unfortunately there is no silver bullet solution; simply excluding commons-logging from your application is not enough in most situations. To be clear about this: the problems reported are usually not with JCL per se, or even with commons-logging: rather they are to do with bindingcommons-logging to another framework (often Log4J). This can fail because commons-logging changed the way they do the runtime discovery in between the older versions (1.0) found in some containers and the modern versions that most people use now (1.1). Spring does not use any unusual parts of the JCL API, so nothing breaks there, but as soon as Spring or your application tries to do any logging you can find that the bindings to Log4J are not working. In such cases with WAS the easiest thing to do is to invert the class loader hierarchy (IBM calls it "parent last") so that the application controls the JCL dependency, not the container. That option isn't always open, but there are plenty of other suggestions in the public domain for alternative approaches, and your mileage may vary depending on the exact version and feature set of the container.

Part II. What's New in Spring 3.02. New Features and Enhancements in Spring 3.0If you have been using the Spring Framework for some time, you will be aware that Spring has undergone two major revisions: Spring 2.0, released in October 2006, and Spring 2.5, released in November 2007. It is now time for a third overhaul resulting in Spring 3.0.Java SE and Java EE Support The Spring Framework is now based on Java 5, and Java 6 is fully supported. Furthermore, Spring is compatible with J2EE 1.4 and Java EE 5, while at the same time introducing some early support for Java EE 6.

45

2.1 Java 5The entire framework code has been revised to take advantage of Java 5 features like generics, varargs and other language improvements. We have done our best to still keep the code backwards compatible. We now have consistent use of generic Collections and Maps, consistent use of generic FactoryBeans, and also consistent resolution of bridge methods in the Spring AOP API. Generic ApplicationListeners automatically receive specific event types only. All callback interfaces such as TransactionCallback and HibernateCallback declare a generic result value 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's java.util.concurrent facilities. We provide first-class support for Callables and Futures now, as well as 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 for asynchronous method invocations through the use of the new @Async annotation (or EJB 3.1's @Asynchronous annotation).

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

2.3 New articles and tutorialsThere are many excellent articles and tutorials that show how to get started with Spring 3 features. Read them at the Spring Documentation page. The samples have been improved and updated to take advantage of the new features in Spring 3. Additionally, the samples have been moved out of the source tree into a dedicated SVN repository available at:https://anonsvn.springframework.org/svn/spring-samples/

As such, the samples are no longer distributed alongside Spring 3 and need to be downloaded separately from the repository mentioned above. However, this

46

documentation will continue to refer to some samples (in particular Petclinic) to illustrate various features.Note For more information on Subversion (or in short SVN), see the project homepage at: http://subversion.apache.org/

2.4 New module organization and build systemThe 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 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

Note: The spring.jar artifact that contained almost the entire framework is no longer provided.

We are now using a new Spring build system as known 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

47

2.5 Overview of new featuresThis is a list of new features for Spring 3.0. We will cover these features in more detail later in this section.

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 requiredType) T getBean(String name, Class requiredType) Map getBeansOfType(Class 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 ApplicationListener2.5.2 Spring Expression Language

Spring introduces an expression language which is similar to Unified EL in its syntax but offers significantly more features. The expression language can be used when defining XML and Annotation based bean definitions and also serves as the foundation for expression language support across the Spring portfolio.

48

Details of this new functionality can be found in the chapter Spring Expression Language (SpEL). The Spring Expression Language was created to provide the Spring community a single, well supported 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 based SpringSource Tool Suite. The following is an example of how the Expression Language can be used to configure some properties of a database setup

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 metadataSome 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 @Primary

49

@Lazy @Import @ImportResource @Value

Here is an example of a Java class providing basic configuration using the new JavaConfig features:package org.example.config; @Configuration public 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 minimal application context XML file.

50

Or you can bootstrap using AnnotationConfigApplicationContext:

a @Configuration class

directly

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

See Section 3.11.2, Instantiating AnnotationConfigApplicationContext for onAnnotationConfigApplicationContext.

the

Spring full

container using information

2.5.3.2 Defining bean metadata within componentsannotated methods are also supported inside Spring components. They contribute a factory bean definition to the container. See Defining bean metadata within components for more information@Bean

2.5.4 General purpose type conversion system and field formatting system

A general purpose type conversion system has been introduced. The system is currently used by SpEL for type conversion, and may also be used by a Spring Container and DataBinder when binding bean property values. In addition, a formatter SPI has been introduced for formatting field values. This SPI provides a simpler and more robust alternative to JavaBean PropertyEditors for use in client environments such as Spring MVC.2.5.5 The Data Tier

Object to XML mapping functionality (OXM) from the Spring Web Services project has been moved to the core Spring Framework now. The functionality is found in the org.springframework.oxm package. More information on the use of the OXM module can be found in 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 services and web applications. There are also some new annotations that can be used in any web application.

51

2.5.6.1 Comprehensive REST supportServer-side support for building RESTful applications has been provided as an extension of the existing annotation driven MVC web framework. Client-side support is provided by the RestTemplate class in the spirit of other template classes such as JdbcTemplate and JmsTemplate. Both server and client side REST functionality make use of HttpConverters to facilitate the conversion between objects and their representation in HTTP requests and responses. The MarshallingHttpMessageConverter uses the Object to XML mapping functionality mentioned earlier. Refer to the sections on MVC and the RestTemplate for more information.

2.5.6.2 @MVC additionsA mvc namespace has been introduced that greatly simplifies Spring MVC configuration. Additional annotations such as @CookieValue and @RequestHeaders have been added. See Mapping cookie values with the @CookieValue annotation and Mapping request header attributes with the @RequestHeader annotation for more information.2.5.7 Declarative model validation

Several validation enhancements, including JSR 303 support that uses Hibernate Validator as the default provider.2.5.8 Early support for Java EE 6

We provide support for asynchronous method invocations through the use of the new @Async annotation (or EJB 3.1's @Asynchronous annotation). JSR 303, JSF 2.0, JPA 2.0, etc2.5.9 Support for embedded databases

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

Part III. Core Technologies52

This part of the reference documentation covers all of those technologies that are absolutely integral to the Spring Framework. Foremost amongst these is the Spring Framework's Inversion of Control (IoC) container. A thorough treatment of the Spring Framework's IoC container is closely followed by comprehensive coverage of Spring's Aspect-Oriented Programming (AOP) technologies. The Spring Framework has its own AOP framework, which is conceptually easy to understand, and which successfully addresses the 80% sweet spot of AOP requirements in Java enterprise programming. Coverage of Spring's integration with AspectJ (currently the richest - in terms of features - and certainly most mature AOP implementation in the Java enterprise space) is also provided. Finally, the adoption of the test-driven-development (TDD) approach to software development is certainly advocated by the Spring team, and so coverage of Spring's support for integration testing is covered (alongside best practices for unit testing). The Spring team has found that the correct use of IoC certainly does make both unit and integration testing easier (in that the presence of setter methods and appropriate constructors on classes makes them easier to wire together in a test without having to set up service locator registries and suchlike)... the chapter dedicated solely to testing will hopefully convince you of this as well.

Chapter 3, The IoC container Chapter 4, Resources Chapter 5, Validation, Data Binding, and Type Conversion Chapter 6, Spring Expression Language (SpEL) Chapter 7, Aspect Oriented Programming with Spring Chapter 8, Spring AOP APIs Chapter 9, Testing

3. The IoC container 3.1 Introduction to the Spring IoC container and beansThis 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 objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the53

name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern. The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework's IoC container. TheBeanFactory interface provides an advanced configuration mechanism capable of managing any type of object. ApplicationContext is a sub-interface of BeanFactory. It adds easier integration with Spring's AOP features; message resource handling (for use in internationalization), event publication; and application-layer specific contexts such as the WebApplicationContext for use in web applications. In short, the BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext adds more enterprise-specific functionality. The ApplicationContext is a complete superset of the BeanFactory, and is used exclusively in this chapter in descriptions of Spring's IoC container. For more information on using the BeanFactory instead of the ApplicationContext, refer to Section 3.14, The BeanFactory. In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.

3.2 Container overviewThe interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. The configuration metadata is represented in XML, Java annotations, or Java code. It allows you to express the objects that compose your application and the rich interdependencies between such objects. Several implementations of the ApplicationContext interface are supplied out-ofthe-box with Spring. In standalone applications it is common to create an instance of ClassPathXmlApplicationContext or FileSystemXmlApplicationContext. While XML has been the traditional format for defining configuration metadata you can instruct the container to use Java annotations or code as the metadata format by providng

54

a small amount of XML configuration to declaratively enable support for these additional metadata formats. In most application scenarios, explicit user code is not required to instantiate one or more instances of a Spring IoC container. For example, in a web application scenario, a simple eight (or so) lines of boilerplate J2EE web descriptor XML in the web.xml file of the application will typically suffice (see Section 3.13.4, Convenient ApplicationContext instantiation for web applications). If you are using the SpringSource Tool SuiteEclipse-powered development environment or Spring Roo this boilerplate configuration can be easily created with few mouse clicks or keystrokes. The following diagram is a high-level view of how Spring works. Your application classes are combined with configuration metadata so that after theApplicationContext is created and initialized, you have a fully configured and executable system or application.

The Spring IoC container3.2.1 Configuration metadata

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

55

Configuration metadata is traditionally supplied in a simple and intuitive XML format, which is what most of this chapter uses to convey key concepts and features of the Spring IoC container.Note XML-based metadata is not the only allowed form of configuration metadata. The Spring IoC container itself is totallydecoupled from the format in which this 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-based configuration metadata. Java-based configuration: Starting with Spring 3.0, many features provided by the Spring JavaConfig project became part of the core Spring Framework. Thus you can define beans external to your application classes by using Java rather than XML files. To use these new features, see the @Configuration, @Bean, @Import and @DependsOn annotations.

Spring configuration consists of at least one and typically more than one bean definition that the container must manage. XML-based configuration metadata shows these beans configured as elements inside a toplevel element. These bean definitions correspond to the actual objects that make up your application. Typically you define service layer objects, data access objects (DAOs), presentation objects such as Struts Action instances, infrastructure objects such as Hibernate SessionFactories, JMS Queues, and so forth. Typically one does not configure fine-grained domain objects in the container, because it is usually the responsibility of DAOs and business logic to create and load domain objects. However, you can use Spring's integration with AspectJ to configure objects that have been created outside the control of an IoC container. See Using AspectJ to dependency-inject domain objects with Spring. The following example shows the basic structure of XML-based configuration metadata:

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

Instantiating a Spring IoC container is straightforward. The location path or paths supplied to an ApplicationContext constructor are actually resource strings that allow the container to load configuration metadata from a variety of external resources such as the local file system, from the Java CLASSPATH, and so on.ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

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

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

57

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

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

58

3.2.2.1 Composing XML-based configuration metadataIt can be useful to have bean definitions span multiple XML files. Often each individual XML configuration file represents a logical layer or module in your architecture. You can use the application context constructor to load bean definitions from all these XML fragments. This constructor takes multiple Resourcelocations, as was shown in the previous section. Alternatively, use one or more occurrences of the element to load bean definitions from another file or files. For example:

In the preceding example, external bean definitions are loaded from three files, services.xml, messageSource.xml, and themeSource.xml. All location paths are relative to the definition file doing the importing, so services.xml must be in the same directory or classpath location as the file doing the importing, while messageSource.xml and themeSource.xml must be in a resources location below the location of the importing file. As you can see, a leading slash is ignored, but given that these paths are relative, it is better form not to use the slash at all. The contents of the files being imported, including the top level element, must be valid XML bean definitions according to the Spring Schema or DTD.Note It is possible, but not recommended, to reference files in parent directories using a relative "../" path. Doing so creates a dependency on a file that is outside the current application. In particular, this reference is not recommended for "classpath:" URLs (for example, "classpath:../services.xml"), where the runtime resolution process chooses the "nearest" classpath root and then looks into its parent directory. Classpath configuration changes may lead to the choice of a different, incorrect directory. You can always use fully qualified resource locations instead of relative paths: for example, "file:C:/config/services.xml" or "classpath:/config/services.xml". However, be aware that you are coupling your application's configuration to specific absolute locations. It is generally preferable

59

to keep an indirection for such absolute locations, for example, through "${...}" placeholders that are resolved against JVM system properties at runtime.

3.2.3 Using the container

The ApplicationContext is the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. Using the method T getBean(Stringname, Class requiredType) you can retrieve instances of your beans. The ApplicationContext enables you to read bean definitions and access them as follows:// create and configure beans ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"}); // retrieve configured instance PetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.class); // use configured instance List userList service.getUsernameList();

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

3.3 Bean overviewA Spring