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.

Spring Framework

Table of Contents
I. Overview of Spring Framework ..............................................................................................1 1. Introduction to Spring Framework ..................................................................................2 1.1. Dependency Injection and Inversion of Control ....................................................2 1.2. Modules ............................................................................................................3 Core Container .................................................................................................3 Data Access/Integration ....................................................................................4 Web .................................................................................................................4 AOP and Instrumentation ..................................................................................5 Test .................................................................................................................5 1.3. Usage scenarios .................................................................................................5 Dependency Management and Naming Conventions ...........................................9 Spring Dependencies and Depending on Spring ........................................11 Maven Dependency Management ............................................................12 Ivy Dependency Management .................................................................13 Logging .........................................................................................................14 Not Using Commons Logging .................................................................14 Using SLF4J ..........................................................................................15 Using Log4J ...........................................................................................16 II. What's New in Spring 3 ......................................................................................................18 2. New Features and Enhancements in Spring 3.0 .............................................................19 2.1. Java 5 ..............................................................................................................19 2.2. Improved documentation ..................................................................................19 2.3. New articles and tutorials ..................................................................................19 2.4. New module organization and build system .......................................................20 2.5. Overview of new features .................................................................................21 Core APIs updated for Java 5 ..........................................................................22 Spring Expression Language ...........................................................................22 The Inversion of Control (IoC) container ..........................................................23 Java based bean metadata ........................................................................23 Defining bean metadata within components ..............................................24 General purpose type conversion system and field formatting system .................24 The Data Tier .................................................................................................24 The Web Tier .................................................................................................25 Comprehensive REST support .................................................................25 @MVC additions ...................................................................................25 Declarative model validation ...........................................................................25 Early support for Java EE 6 .............................................................................25 Support for embedded databases ......................................................................25 3. New Features and Enhancements in Spring 3.1 .............................................................26 3.1. Overview of new features .................................................................................26

3.1

Reference Documentation

ii

Spring Framework

Cache Abstraction ..........................................................................................26 Bean Definition Profiles ..................................................................................26 Environment Abstraction ................................................................................26 PropertySource Abstraction .............................................................................26 Code equivalents for Spring's XML namespaces ...............................................27 Support for Hibernate 4.x ................................................................................27 TestContext framework support for @Configuration classes and bean definition profiles ..........................................................................................................27 c: namespace for more concise constructor injection .........................................28 Support for injection against non-standard JavaBeans setters .............................28 Support for Servlet 3 code-based configuration of Servlet Container ..................28 Support for Servlet 3 MultipartResolver ...........................................................28 JPA EntityManagerFactory bootstrapping without persistence.xml ....................28 New HandlerMethod-based Support Classes For Annotated Controller Processing .......................................................................................................................29 "consumes" and "produces" conditions in @RequestMapping ...........................30 Flash Attributes and RedirectAttributes ............................................................30 URI Template Variable Enhancements .............................................................30 @Valid On @RequestBody Controller Method Arguments ...............................30 @RequestPart Annotation On Controller Method Arguments ............................31 UriComponentsBuilder and UriComponents .....................................................31 III. Core Technologies ............................................................................................................32 4. The IoC container .......................................................................................................33 4.1. Introduction to the Spring IoC container and beans .............................................33 4.2. Container overview ..........................................................................................33 Configuration metadata ...................................................................................34 Instantiating a container ..................................................................................36 Composing XML-based configuration metadata .......................................37 Using the container .........................................................................................38 4.3. Bean overview .................................................................................................38 Naming beans .................................................................................................40 Aliasing a bean outside the bean definition ...............................................40 Instantiating beans ..........................................................................................41 Instantiation with a constructor ................................................................42 Instantiation with a static factory method .................................................42 Instantiation using an instance factory method ..........................................43 4.4. Dependencies ...................................................................................................44 Dependency injection ......................................................................................44 Constructor-based dependency injection ...................................................44 Setter-based dependency injection ...........................................................47 Dependency resolution process ................................................................48 Examples of dependency injection ...........................................................49 Dependencies and configuration in detail .........................................................51 Straight values (primitives, Strings, and so on) .........................................51 References to other beans (collaborators) .................................................53 3.1 Reference Documentation iii

Spring Framework

Inner beans .............................................................................................54 Collections .............................................................................................54 Null and empty string values ...................................................................57 XML shortcut with the p-namespace ........................................................57 XML shortcut with the c-namespace ........................................................58 Compound property names ......................................................................59 Using depends-on ...........................................................................................59 Lazy-initialized beans .....................................................................................60 Autowiring collaborators .................................................................................61 Limitations and disadvantages of autowiring ............................................62 Excluding a bean from autowiring ...........................................................63 Method injection ............................................................................................63 Lookup method injection .........................................................................64 Arbitrary method replacement .................................................................66 4.5. Bean scopes .....................................................................................................67 The singleton scope ........................................................................................68 The prototype scope ........................................................................................69 Singleton beans with prototype-bean dependencies ...........................................70 Request, session, and global session scopes ......................................................70 Initial web configuration .........................................................................70 Request scope .........................................................................................71 Session scope .........................................................................................72 Global session scope ...............................................................................72 Scoped beans as dependencies .................................................................72 Custom scopes ...............................................................................................74 Creating a custom scope ..........................................................................75 Using a custom scope ..............................................................................75 4.6. Customizing the nature of a bean .......................................................................77 Lifecycle callbacks .........................................................................................77 Initialization callbacks ............................................................................77 Destruction callbacks ..............................................................................78 Default initialization and destroy methods ................................................79 Combining lifecycle mechanisms ............................................................80 Startup and shutdown callbacks ...............................................................80 Shutting down the Spring IoC container gracefully in non-web applications 82 ApplicationContextAware and BeanNameAware ..............................................83 Other Aware interfaces ...................................................................................84 4.7. Bean definition inheritance ...............................................................................86 4.8. Container Extension Points ...............................................................................87 Customizing beans using a BeanPostProcessor .................................................87 Example: Hello World, BeanPostProcessor-style ......................................89 Example: The RequiredAnnotationBeanPostProcessor ..............................90 Customizing configuration metadata with a BeanFactoryPostProcessor ..............90 Example: the PropertyPlaceholderConfigurer ...........................................91 Example: the PropertyOverrideConfigurer ...............................................93 3.1 Reference Documentation iv

Spring Framework

Customizing instantiation logic with a FactoryBean ..........................................94 4.9. Annotation-based container configuration ..........................................................95 @Required .....................................................................................................96 @Autowired ...................................................................................................97 Fine-tuning annotation-based autowiring with qualifiers ...................................99 CustomAutowireConfigurer .......................................................................... 104 @Resource ................................................................................................... 105 @PostConstruct and @PreDestroy ................................................................. 106 4.10. Classpath scanning and managed components ................................................ 107 @Component and further stereotype annotations ............................................ 107 Automatically detecting classes and registering bean definitions ...................... 107 Using filters to customize scanning ................................................................ 109 Defining bean metadata within components .................................................... 110 Naming autodetected components .................................................................. 111 Providing a scope for autodetected components .............................................. 112 Providing qualifier metadata with annotations ................................................ 112 4.11. Using JSR 330 Standard Annotations ............................................................. 113 Dependency Injection with @Inject and @Named .......................................... 114 @Named: a standard equivalent to the @Component annotation ...................... 114 Limitations of the standard approach .............................................................. 115 4.12. Java-based container configuration ................................................................ 116 Basic concepts: @Configuration and @Bean .................................................. 116 Instantiating the Spring container using AnnotationConfigApplicationContext . 116 Simple construction .............................................................................. 117 Building the container programmatically using register(Class<?>...) ........ 117 Enabling component scanning with scan(String...) .................................. 117 Support for web applications with AnnotationConfigWebApplicationContext ............................................................................................................. 118 Composing Java-based configurations ............................................................ 119 Using the @Import annotation ............................................................... 119 Combining Java and XML configuration ................................................ 122 Using the @Bean annotation ......................................................................... 124 Declaring a bean ................................................................................... 124 Injecting dependencies .......................................................................... 125 Receiving lifecycle callbacks ................................................................. 125 Specifying bean scope ........................................................................... 126 Customizing bean naming ..................................................................... 128 Bean aliasing ........................................................................................ 128 Further information about how Java-based configuration works internally ........ 128 4.13. Registering a LoadTimeWeaver .................................................................... 129 4.14. Additional Capabilities of the ApplicationContext .......................................... 130 Internationalization using MessageSource ...................................................... 130 Standard and Custom Events ......................................................................... 133 Convenient access to low-level resources ....................................................... 136 Convenient ApplicationContext instantiation for web applications ................... 137 3.1 Reference Documentation v

Spring Framework

Deploying a Spring ApplicationContext as a J2EE RAR file ............................ 138 4.15. The BeanFactory .......................................................................................... 138 BeanFactory or ApplicationContext? ............................................................. 139 Glue code and the evil singleton .................................................................... 140 5. Resources ................................................................................................................. 142 5.1. Introduction ................................................................................................... 142 5.2. The Resource interface ................................................................................... 142 5.3. Built-in Resource implementations .................................................................. 143 UrlResource ................................................................................................. 143 ClassPathResource ....................................................................................... 144 FileSystemResource ..................................................................................... 144 ServletContextResource ................................................................................ 144 InputStreamResource .................................................................................... 144 ByteArrayResource ...................................................................................... 145 5.4. The ResourceLoader ....................................................................................... 145 5.5. The ResourceLoaderAware interface ............................................................... 146 5.6. Resources as dependencies ............................................................................. 147 5.7. Application contexts and Resource paths ......................................................... 147 Constructing application contexts .................................................................. 147 Constructing ClassPathXmlApplicationContext instances - shortcuts ....... 148 Wildcards in application context constructor resource paths ............................ 149 Ant-style Patterns ................................................................................. 149 The classpath*: prefix ........................................................................... 150 Other notes relating to wildcards ............................................................ 150 FileSystemResource caveats .......................................................................... 151 6. Validation, Data Binding, and Type Conversion .......................................................... 153 6.1. Introduction ................................................................................................... 153 6.2. Validation using Spring's Validator interface .................................................... 153 6.3. Resolving codes to error messages .................................................................. 155 6.4. Bean manipulation and the BeanWrapper ........................................................ 155 Setting and getting basic and nested properties ............................................... 156 Built-in PropertyEditor implementations ........................................................ 157 Registering additional custom PropertyEditors ....................................... 160 6.5. Spring 3 Type Conversion .............................................................................. 163 Converter SPI ............................................................................................... 163 ConverterFactory .......................................................................................... 164 GenericConverter ......................................................................................... 165 ConditionalGenericConverter ................................................................ 165 ConversionService API ................................................................................. 166 Configuring a ConversionService .................................................................. 166 Using a ConversionService programatically ................................................... 167 6.6. Spring 3 Field Formatting ............................................................................... 167 Formatter SPI ............................................................................................... 168 Annotation-driven Formatting ....................................................................... 169 Format Annotation API ......................................................................... 170 3.1 Reference Documentation vi

Spring Framework

FormatterRegistry SPI .................................................................................. 171 FormatterRegistrar SPI ................................................................................. 171 Configuring Formatting in Spring MVC ......................................................... 172 6.7. Spring 3 Validation ........................................................................................ 173 Overview of the JSR-303 Bean Validation API ............................................... 173 Configuring a Bean Validation Implementation .............................................. 174 Injecting a Validator ............................................................................. 174 Configuring Custom Constraints ............................................................ 175 Additional Configuration Options .......................................................... 175 Configuring a DataBinder ............................................................................. 175 Spring MVC 3 Validation ............................................................................. 176 Triggering @Controller Input Validation ............................................... 176 Configuring a Validator for use by Spring MVC ..................................... 176 Configuring a JSR-303 Validator for use by Spring MVC ....................... 177 7. Spring Expression Language (SpEL) .......................................................................... 178 7.1. Introduction ................................................................................................... 178 7.2. Feature Overview ........................................................................................... 178 7.3. Expression Evaluation using Spring's Expression Interface ............................... 179 The EvaluationContext interface .................................................................... 182 Type Conversion .................................................................................. 182 7.4. Expression support for defining bean definitions .............................................. 183 XML based configuration ............................................................................. 183 Annotation-based configuration ..................................................................... 183 7.5. Language Reference ....................................................................................... 185 Literal expressions ........................................................................................ 185 Properties, Arrays, Lists, Maps, Indexers ........................................................ 185 Inline lists .................................................................................................... 186 Array construction ........................................................................................ 186 Methods ....................................................................................................... 187 Operators ..................................................................................................... 187 Relational operators .............................................................................. 187 Logical operators .................................................................................. 188 Mathematical operators ......................................................................... 188 Assignment .................................................................................................. 189 Types ........................................................................................................... 189 Constructors ................................................................................................. 189 Variables ...................................................................................................... 190 The #this and #root variables ................................................................. 190 Functions ..................................................................................................... 190 Bean references ............................................................................................ 191 Ternary Operator (If-Then-Else) .................................................................... 191 The Elvis Operator ....................................................................................... 192 Safe Navigation operator ............................................................................... 192 Collection Selection ...................................................................................... 193 Collection Projection .................................................................................... 193 3.1 Reference Documentation vii

Spring Framework

Expression templating ................................................................................... 194 7.6. Classes used in the examples ........................................................................... 194 8. Aspect Oriented Programming with Spring ................................................................. 198 8.1. Introduction ................................................................................................... 198 AOP concepts ............................................................................................... 198 Spring AOP capabilities and goals ................................................................. 200 AOP Proxies ................................................................................................ 201 8.2. @AspectJ support .......................................................................................... 202 Enabling @AspectJ Support .......................................................................... 202 Declaring an aspect ....................................................................................... 202 Declaring a pointcut ...................................................................................... 203 Supported Pointcut Designators ............................................................. 204 Combining pointcut expressions ............................................................ 206 Sharing common pointcut definitions ..................................................... 206 Examples ............................................................................................. 207 Writing good pointcuts .......................................................................... 210 Declaring advice ........................................................................................... 211 Before advice ....................................................................................... 211 After returning advice ........................................................................... 211 After throwing advice ........................................................................... 212 After (finally) advice ............................................................................ 213 Around advice ...................................................................................... 213 Advice parameters ................................................................................ 214 Advice ordering .................................................................................... 218 Introductions ................................................................................................ 218 Aspect instantiation models ........................................................................... 219 Example ....................................................................................................... 220 8.3. Schema-based AOP support ............................................................................ 221 Declaring an aspect ....................................................................................... 222 Declaring a pointcut ...................................................................................... 222 Declaring advice ........................................................................................... 224 Before advice ....................................................................................... 224 After returning advice ........................................................................... 225 After throwing advice ........................................................................... 225 After (finally) advice ............................................................................ 226 Around advice ...................................................................................... 226 Advice parameters ................................................................................ 227 Advice ordering .................................................................................... 229 Introductions ................................................................................................ 229 Aspect instantiation models ........................................................................... 230 Advisors ...................................................................................................... 230 Example ....................................................................................................... 230 8.4. Choosing which AOP declaration style to use .................................................. 232 Spring AOP or full AspectJ? ......................................................................... 232 @AspectJ or XML for Spring AOP? .............................................................. 233 3.1 Reference Documentation viii

Spring Framework

8.5. Mixing aspect types ........................................................................................ 234 8.6. Proxying mechanisms ..................................................................................... 234 Understanding AOP proxies .......................................................................... 235 8.7. Programmatic creation of @AspectJ Proxies .................................................... 238 8.8. Using AspectJ with Spring applications ........................................................... 238 Using AspectJ to dependency inject domain objects with Spring ...................... 238 Unit testing @Configurable objects ....................................................... 241 Working with multiple application contexts ............................................ 241 Other Spring aspects for AspectJ ................................................................... 242 Configuring AspectJ aspects using Spring IoC ................................................ 242 Load-time weaving with AspectJ in the Spring Framework ............................. 243 A first example ..................................................................................... 244 Aspects ................................................................................................ 247 'META-INF/aop.xml' ............................................................................ 247 Required libraries (JARS) ..................................................................... 247 Spring configuration ............................................................................. 248 Environment-specific configuration ....................................................... 250 8.9. Further Resources .......................................................................................... 253 9. Spring AOP APIs ...................................................................................................... 254 9.1. Introduction ................................................................................................... 254 9.2. Pointcut API in Spring .................................................................................... 254 Concepts ...................................................................................................... 254 Operations on pointcuts ................................................................................. 255 AspectJ expression pointcuts ......................................................................... 255 Convenience pointcut implementations .......................................................... 255 Static pointcuts ..................................................................................... 256 Dynamic pointcuts ................................................................................ 257 Pointcut superclasses .................................................................................... 257 Custom pointcuts .......................................................................................... 258 9.3. Advice API in Spring ..................................................................................... 258 Advice lifecycles .......................................................................................... 258 Advice types in Spring .................................................................................. 258 Interception around advice .................................................................... 258 Before advice ....................................................................................... 259 Throws advice ...................................................................................... 260 After Returning advice .......................................................................... 261 Introduction advice ............................................................................... 262 9.4. Advisor API in Spring .................................................................................... 265 9.5. Using the ProxyFactoryBean to create AOP proxies ......................................... 265 Basics .......................................................................................................... 265 JavaBean properties ...................................................................................... 266 JDK- and CGLIB-based proxies .................................................................... 267 Proxying interfaces ....................................................................................... 268 Proxying classes ........................................................................................... 270 Using 'global' advisors .................................................................................. 270 3.1 Reference Documentation ix

Spring Framework

9.6. Concise proxy definitions ............................................................................... 271 9.7. Creating AOP proxies programmatically with the ProxyFactory ........................ 272 9.8. Manipulating advised objects .......................................................................... 272 9.9. Using the "autoproxy" facility ......................................................................... 274 Autoproxy bean definitions ........................................................................... 274 BeanNameAutoProxyCreator ................................................................ 274 DefaultAdvisorAutoProxyCreator .......................................................... 275 AbstractAdvisorAutoProxyCreator ........................................................ 276 Using metadata-driven auto-proxying ............................................................ 276 9.10. Using TargetSources .................................................................................... 278 Hot swappable target sources ......................................................................... 279 Pooling target sources ................................................................................... 280 Prototype target sources ................................................................................ 281 ThreadLocal target sources ............................................................................ 281 9.11. Defining new Advice types ........................................................................... 282 9.12. Further resources .......................................................................................... 282 10. Testing ................................................................................................................... 283 10.1. Introduction to Spring Testing ....................................................................... 283 10.2. Unit Testing ................................................................................................. 283 Mock Objects ............................................................................................... 283 JNDI .................................................................................................... 283 Servlet API .......................................................................................... 283 Portlet API ........................................................................................... 284 Unit Testing support Classes ......................................................................... 284 General utilities .................................................................................... 284 Spring MVC ......................................................................................... 284 10.3. Integration Testing ....................................................................................... 284 Overview ..................................................................................................... 284 Goals of Integration Testing .......................................................................... 285 Context management and caching .......................................................... 286 Dependency Injection of test fixtures ..................................................... 286 Transaction management ....................................................................... 287 Support classes for integration testing .................................................... 287 JDBC Testing Support .................................................................................. 288 Annotations .................................................................................................. 288 Spring Testing Annotations ................................................................... 288 Standard Annotation Support ................................................................. 292 Spring JUnit Testing Annotations .......................................................... 292 Spring TestContext Framework ..................................................................... 294 Key abstractions ................................................................................... 294 Context management ............................................................................ 295 Dependency injection of test fixtures ..................................................... 303 Transaction management ....................................................................... 306 TestContext support classes ................................................................... 308 PetClinic Example ........................................................................................ 310 3.1 Reference Documentation x

Spring Framework

10.4. Further Resources ......................................................................................... 312 IV. Data Access .................................................................................................................... 313 11. Transaction Management ......................................................................................... 314 11.1. Introduction to Spring Framework transaction management ............................ 314 11.2. Advantages of the Spring Framework's transaction support model ................... 314 Global transactions ....................................................................................... 315 Local transactions ......................................................................................... 315 Spring Framework's consistent programming model ....................................... 315 11.3. Understanding the Spring Framework transaction abstraction .......................... 316 11.4. Synchronizing resources with transactions ..................................................... 320 High-level synchronization approach ............................................................. 320 Low-level synchronization approach .............................................................. 320 TransactionAwareDataSourceProxy ............................................................... 321 11.5. Declarative transaction management .............................................................. 321 Understanding the Spring Framework's declarative transaction implementation 323 Example of declarative transaction implementation ......................................... 324 Rolling back a declarative transaction ............................................................ 328 Configuring different transactional semantics for different beans ..................... 329 <tx:advice/> settings ..................................................................................... 331 Using @Transactional ................................................................................... 332 @Transactional settings ........................................................................ 336 Multiple Transaction Managers with @Transactional .............................. 337 Custom shortcut annotations .................................................................. 338 Transaction propagation ................................................................................ 338 Required .............................................................................................. 339 RequiresNew ........................................................................................ 339 Nested ................................................................................................. 340 Advising transactional operations .................................................................. 340 Using @Transactional with AspectJ ............................................................... 343 11.6. Programmatic transaction management .......................................................... 344 Using the TransactionTemplate ..................................................................... 344 Specifying transaction settings ............................................................... 345 Using the PlatformTransactionManager ......................................................... 346 11.7. Choosing between programmatic and declarative transaction management ....... 347 11.8. Application server-specific integration ........................................................... 347 IBM WebSphere ........................................................................................... 348 BEA WebLogic Server ................................................................................. 348 Oracle OC4J ................................................................................................. 348 11.9. Solutions to common problems ..................................................................... 348 Use of the wrong transaction manager for a specific DataSource ...................... 348 11.10. Further Resources ....................................................................................... 348 12. DAO support .......................................................................................................... 350 12.1. Introduction ................................................................................................. 350 12.2. Consistent exception hierarchy ...................................................................... 350 12.3. Annotations used for configuring DAO or Repository classes .......................... 351 3.1 Reference Documentation xi

Spring Framework

13. Data access with JDBC ............................................................................................ 353 13.1. Introduction to Spring Framework JDBC ....................................................... 353 Choosing an approach for JDBC database access ............................................ 353 Package hierarchy ......................................................................................... 354 13.2. Using the JDBC core classes to control basic JDBC processing and error handling ............................................................................................................................. 355 JdbcTemplate ............................................................................................... 355 Examples of JdbcTemplate class usage .................................................. 356 JdbcTemplate best practices .................................................................. 358 NamedParameterJdbcTemplate ...................................................................... 359 SimpleJdbcTemplate ..................................................................................... 361 SQLExceptionTranslator ............................................................................... 363 Executing statements .................................................................................... 364 Running queries ........................................................................................... 365 Updating the database ................................................................................... 366 Retrieving auto-generated keys ...................................................................... 366 13.3. Controlling database connections .................................................................. 367 DataSource .................................................................................................. 367 DataSourceUtils ........................................................................................... 368 SmartDataSource .......................................................................................... 368 AbstractDataSource ...................................................................................... 369 SingleConnectionDataSource ........................................................................ 369 DriverManagerDataSource ............................................................................ 369 TransactionAwareDataSourceProxy ............................................................... 369 DataSourceTransactionManager .................................................................... 370 NativeJdbcExtractor ..................................................................................... 370 13.4. JDBC batch operations ................................................................................. 371 Basic batch operations with the JdbcTemplate ................................................ 371 Batch operations with a List of objects ........................................................... 372 Batch operations with multiple batches .......................................................... 373 13.5. Simplifying JDBC operations with the SimpleJdbc classes .............................. 374 Inserting data using SimpleJdbcInsert ............................................................ 374 Retrieving auto-generated keys using SimpleJdbcInsert ................................... 375 Specifying columns for a SimpleJdbcInsert .................................................... 375 Using SqlParameterSource to provide parameter values .................................. 376 Calling a stored procedure with SimpleJdbcCall ............................................. 377 Explicitly declaring parameters to use for a SimpleJdbcCall ............................ 379 How to define SqlParameters ......................................................................... 380 Calling a stored function using SimpleJdbcCall .............................................. 380 Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................. 381 13.6. Modeling JDBC operations as Java objects .................................................... 382 SqlQuery ...................................................................................................... 383 MappingSqlQuery ........................................................................................ 383 SqlUpdate .................................................................................................... 384 StoredProcedure ........................................................................................... 385 3.1 Reference Documentation xii

Spring Framework

13.7. Common problems with parameter and data value handling ............................ 388 Providing SQL type information for parameters .............................................. 388 Handling BLOB and CLOB objects ............................................................... 388 Passing in lists of values for IN clause ........................................................... 390 Handling complex types for stored procedure calls ......................................... 390 13.8. Embedded database support .......................................................................... 392 Why use an embedded database? ................................................................... 392 Creating an embedded database instance using Spring XML ........................... 392 Creating an embedded database instance programmatically ............................. 392 Extending the embedded database support ...................................................... 392 Using HSQL ................................................................................................ 393 Using H2 ..................................................................................................... 393 Using Derby ................................................................................................. 393 Testing data access logic with an embedded database ...................................... 393 13.9. Initializing a DataSource ............................................................................... 394 Initializing a database instance using Spring XML .......................................... 394 Initialization of Other Components that Depend on the Database ............. 395 14. Object Relational Mapping (ORM) Data Access ....................................................... 397 14.1. Introduction to ORM with Spring .................................................................. 397 14.2. General ORM integration considerations ........................................................ 398 Resource and transaction management ........................................................... 398 Exception translation .................................................................................... 399 14.3. Hibernate ..................................................................................................... 400 SessionFactory setup in a Spring container ..................................................... 400 Implementing DAOs based on plain Hibernate 3 API ...................................... 401 Declarative transaction demarcation ............................................................... 402 Programmatic transaction demarcation ........................................................... 404 Transaction management strategies ................................................................ 405 Comparing container-managed and locally defined resources .......................... 407 Spurious application server warnings with Hibernate ...................................... 408 14.4. JDO ............................................................................................................. 409 PersistenceManagerFactory setup .................................................................. 409 Implementing DAOs based on the plain JDO API ........................................... 410 Transaction management ............................................................................... 412 JdoDialect .................................................................................................... 413 14.5. JPA ............................................................................................................. 414 Three options for JPA setup in a Spring environment ...................................... 414 LocalEntityManagerFactoryBean ........................................................... 414 Obtaining an EntityManagerFactory from JNDI ...................................... 415 LocalContainerEntityManagerFactoryBean ............................................ 415 Dealing with multiple persistence units .................................................. 418 Implementing DAOs based on plain JPA ........................................................ 418 Transaction Management .............................................................................. 421 JpaDialect .................................................................................................... 422 14.6. iBATIS SQL Maps ....................................................................................... 422 3.1 Reference Documentation xiii

Spring Framework

Setting up the SqlMapClient .......................................................................... 422 Using SqlMapClientTemplate and SqlMapClientDaoSupport .......................... 424 Implementing DAOs based on plain iBATIS API ........................................... 425 15. Marshalling XML using O/X Mappers ..................................................................... 426 15.1. Introduction ................................................................................................. 426 15.2. Marshaller and Unmarshaller ........................................................................ 426 Marshaller .................................................................................................... 426 Unmarshaller ................................................................................................ 427 XmlMappingException ................................................................................. 428 15.3. Using Marshaller and Unmarshaller ............................................................... 428 15.4. XML Schema-based Configuration ................................................................ 430 15.5. JAXB .......................................................................................................... 431 Jaxb2Marshaller ........................................................................................... 431 XML Schema-based Configuration ........................................................ 431 15.6. Castor .......................................................................................................... 432 CastorMarshaller .......................................................................................... 432 Mapping ...................................................................................................... 432 15.7. XMLBeans .................................................................................................. 433 XmlBeansMarshaller .................................................................................... 433 XML Schema-based Configuration ........................................................ 433 15.8. JiBX ............................................................................................................ 434 JibxMarshaller .............................................................................................. 434 XML Schema-based Configuration ........................................................ 434 15.9. XStream ...................................................................................................... 435 XStreamMarshaller ....................................................................................... 435 V. The Web .......................................................................................................................... 437 16. Web MVC framework ............................................................................................. 438 16.1. Introduction to Spring Web MVC framework ................................................. 438 Features of Spring Web MVC ....................................................................... 439 Pluggability of other MVC implementations ................................................... 440 16.2. The DispatcherServlet .................................................................................. 440 Special Bean Types In the WebApplicationContext ........................................ 443 Default DispatcherServlet Configuration ........................................................ 444 DispatcherServlet Processing Sequence .......................................................... 444 16.3. Implementing Controllers ............................................................................. 446 Defining a controller with @Controller .......................................................... 447 Mapping Requests With @RequestMapping ................................................... 447 New Support Classes for @RequestMapping methods in Spring MVC 3.1 449 URI Template Patterns .......................................................................... 450 URI Template Patterns with Regular Expressions ................................... 451 Path Patterns ........................................................................................ 452 Consumable Media Types ..................................................................... 452 Producible Media Types ........................................................................ 452 Request Parameters and Header Values .................................................. 453 Defining @RequestMapping handler methods ................................................ 453 3.1 Reference Documentation xiv

Spring Framework

Supported method argument types ......................................................... 454 Supported method return types .............................................................. 456 Binding request parameters to method parameters with @RequestParam .. 457 Mapping the request body with the @RequestBody annotation ................ 457 Mapping the response body with the @ResponseBody annotation ........... 458 Using HttpEntity<?> ............................................................................. 459 Using @ModelAttribute on a method ..................................................... 459 Using @ModelAttribute on a method argument ...................................... 460 Using @SessionAttributes to store model attributes in the HTTP session between requests .................................................................................. 462 Specifying redirect and flash attributes ................................................... 463 Working with "application/x-www-form-urlencoded" data ...................... 463 Mapping cookie values with the @CookieValue annotation .................... 464 Mapping request header attributes with the @RequestHeader annotation .. 465 Method Parameters And Type Conversion ............................................. 465 Customizing WebDataBinder initialization ............................................. 465 Support for the 'Last-Modified' Response Header To Facilitate Content Caching ............................................................................................... 467 16.4. Handler mappings ........................................................................................ 467 Intercepting requests with a HandlerInterceptor .............................................. 468 16.5. Resolving views ........................................................................................... 470 Resolving views with the ViewResolver interface ........................................... 470 Chaining ViewResolvers ............................................................................... 472 Redirecting to views ..................................................................................... 473 RedirectView ....................................................................................... 473 The redirect: prefix ............................................................................... 474 The forward: prefix ............................................................................... 474 ContentNegotiatingViewResolver .................................................................. 474 16.6. Using flash attributes .................................................................................... 477 16.7. Building URIs .............................................................................................. 478 16.8. Using locales ............................................................................................... 479 AcceptHeaderLocaleResolver ........................................................................ 479 CookieLocaleResolver .................................................................................. 479 SessionLocaleResolver ................................................................................. 480 LocaleChangeInterceptor .............................................................................. 480 16.9. Using themes ............................................................................................... 481 Overview of themes ...................................................................................... 481 Defining themes ........................................................................................... 481 Theme resolvers ........................................................................................... 482 16.10. Spring's multipart (file upload) support ........................................................ 482 Introduction ................................................................................................. 482 Using a MultipartResolver with Commons FileUpload .................................... 482 Using a MultipartResolver with Servlet 3.0 .................................................... 483 Handling a file upload in a form .................................................................... 483 Handling a file upload request from programmatic clients ............................... 484 3.1 Reference Documentation xv

Spring Framework

16.11. Handling exceptions ................................................................................... 485 HandlerExceptionResolver ............................................................................ 485 @ExceptionHandler ...................................................................................... 486 16.12. Convention over configuration support ........................................................ 487 The Controller ControllerClassNameHandlerMapping .................................... 487 The Model ModelMap (ModelAndView) ....................................................... 488 The View - RequestToViewNameTranslator .................................................. 490 16.13. ETag support .............................................................................................. 491 16.14. Configuring Spring MVC ............................................................................ 492 Enabling MVC Java Config or the MVC XML Namespace ............................. 492 Customizing the Provided Configuration ........................................................ 493 Configuring Interceptors ............................................................................... 494 Configuring View Controllers ....................................................................... 495 Configuring Serving of Resources ................................................................. 495 mvc:default-servlet-handler ........................................................................... 497 More Spring Web MVC Resources ................................................................ 498 Advanced Customizations with MVC Java Config .......................................... 499 Advanced Customizations with the MVC Namespace ..................................... 499 17. View technologies ................................................................................................... 501 17.1. Introduction ................................................................................................. 501 17.2. JSP & JSTL ................................................................................................. 501 View resolvers ............................................................................................. 501 'Plain-old' JSPs versus JSTL .......................................................................... 502 Additional tags facilitating development ........................................................ 502 Using Spring's form tag library ...................................................................... 502 Configuration ....................................................................................... 502 The form tag ........................................................................................ 503 The input tag ........................................................................................ 504 The checkbox tag .................................................................................. 504 The checkboxes tag .............................................................................. 506 The radiobutton tag ............................................................................... 506 The radiobuttons tag ............................................................................. 507 The password tag .................................................................................. 507 The select tag ....................................................................................... 507 The option tag ...................................................................................... 508 The options tag ..................................................................................... 508 The textarea tag .................................................................................... 509 The hidden tag ...................................................................................... 509 The errors tag ....................................................................................... 510 HTTP Method Conversion .................................................................... 512 HTML5 Tags ....................................................................................... 512 17.3. Tiles ............................................................................................................ 513 Dependencies ............................................................................................... 513 How to integrate Tiles ................................................................................... 513 UrlBasedViewResolver ......................................................................... 514 3.1 Reference Documentation xvi

... 538 3.................................. 530 Configuring the ViewResolver ................................................................. 515 Context configuration ................................ JSON Mapping View ....................................................................... 517 The bind macros ................................................................................................................................................... 534 Configuring Sub-Report Data Sources .... 516 Advanced configuration ......... 524 Bean definitions ........................................................................... 531 About Report Files ...................................................................................... 536 18........... 524 Standard MVC controller code .............. 527 Introduction ................................................................ XML Marshalling View ........................................................................................................................................................................................................ 523 17........... 530 Dependencies .... 519 HTML escaping and XHTML compliance ... Integrating with other web frameworks ............................ 524 Convert the model data to XML ........................................................... 527 Controller code ........... 532 Populating the ModelAndView ................................................................................................................................................ 518 Form input generation macros ....... JasperReports .......................... 526 Summary ............................................................................................................................................................................................................ 534 Configuring Exporter Parameters .............................................................8................ 526 Document transformation .......................................... 528 Subclassing for Excel views ........................................... 517 Bind support and form handling ................. 535 17......................................... XSLT ....... Feed Views .........................7............................................................................................................... 514 17..............................................................................4................................. 528 Subclassing for PDF views ...................................................................................... 530 Configuration ..................................... 533 Configuring Sub-Report Files ...................5....................................................................................................................................................................................................................... 517 FreeMarker .......................................................................................................................................................properties ....................................................................................................... 524 My First Words .......Spring Framework ResourceBundleViewResolver ............... 514 SimpleSpringPreparerFactory and SpringBeanPreparerFactory . 531 Configuring the Views ................. 518 Simple binding ...................... 515 Creating templates ....................................... 536 17......................................................................... 525 Defining the view properties ..................................................................................................................................................6......................................1 Reference Documentation xvii ........ 531 Using JasperReportsMultiFormatView ............................. 516 velocity........................................................ 526 17.............. 529 17...........................................10............................................. Velocity & FreeMarker ........................................................ 535 17............... 533 Working with Sub-Reports ........................ Document views (PDF/Excel) ............................. 527 Configuration and setup .9..................................................................................................... 515 Dependencies .................................................................................................................................................................................................................................................... 527 Document view definitions .

............................7.... 567 19....................................... 554 19........................................................The V in MVC ..................................................................................................................................................x and 2........................................................1................................................................................................. Portlet MVC Framework .................... 550 Dependency Injecting Spring Beans into Tapestry pages ........ Introduction .......................................................................... 539 18............................................................... 570 3................................ 542 18...............................x and 4.......................... 563 ParameterHandlerMapping ........................ Views and resolving them ................... 566 19.................................................................... Common configuration ................. 538 18........................ Further Resources ................................................... 541 SpringBeanFacesELResolver (JSF 1...........3................................................................................................................ Tapestry 3..............2........................ JavaServer Faces 1...........................................................................................................................................2) ................................................ 562 PortletModeHandlerMapping . 555 Web-scoped beans .............................................................................................................................. 559 Other simple controllers .............. Handler mappings ..2 .................................................................. 541 FacesContextUtils ................................................................................7............................................ 565 19............. 564 PortletModeParameterHandlerMapping .......................5............... 549 Adding abstract accessors ......................... The ViewRendererServlet .....................x ...................... 544 DelegatingActionProxy ............. The DispatcherPortlet . 556 19........... 565 HandlerInterceptorAdapter ............................................................... 555 Views .... 564 Adding HandlerInterceptors . 546 Injecting Spring-managed beans .Tapestry 4................................. 553 19.........................1/1.............................................................. Introduction ..............8............. Multipart (file upload) support .............................6....... 545 18............2........................................5............... 565 ParameterMappingInterceptor ..................................The C in MVC ..................................... 540 SpringBeanVariableResolver (JSF 1...................................................................................x .............................................................................................................3...................... 554 Controllers ................ 545 18.... 561 PortletWrappingController ........................................................................................ 562 19.....................................................................4......................................................... Controllers ..................................................................... 542 ContextLoaderPlugin .....1 Reference Documentation xviii ................................. 566 Using the PortletMultipartResolver ......... 547 Dependency Injecting Spring Beans into Tapestry pages ........................ 561 Command Controllers ................6..............................1.........................................................................................................x .x style ............... 548 Component definition files .................................................2) ........... Handling exceptions ................... 558 19. 556 19................................... Apache Struts 1........... 552 18.............................................................1/1................1 and 1.......................................................... WebWork 2........2+) .4...................................... 559 AbstractController and PortletContentGenerator ............................................ 544 ActionSupport Classes ........................................................ 567 Handling a file upload in a form .............. 540 DelegatingVariableResolver (JSF 1............................................................................................ 543 DelegatingRequestProcessor ....Spring Framework 18....................

... 579 20........................................................................ 588 Accessing web services using JAX-RPC .............. 583 Exposing your beans by using the HessianServiceExporter ............................................ 598 RestTemplate ............ 597 20........................................................................................................ 578 VI................................... 585 Exposing the service object ...... ............................................................ 590 Registering your own JAX-RPC Handler ..... 581 Exporting the service using the RmiServiceExporter ... 571 Mapping requests with @RequestMapping ................................................................................................ 598 Working with the URI .................................................. Exposing services using HTTP invokers ...........................1 Reference Documentation xix ...... 588 Registering JAX-RPC Bean Mappings ................. 576 Specifying attributes to store in a Session with @SessionAttributes .............................. 573 Binding request parameters to method parameters with @RequestParam ...... 577 Configuring a custom WebBindingInitializer ...................................................................9................... 572 Supported handler method arguments .... 596 20..... 591 Exporting standalone web services using JAX-WS ............................ 592 Exporting web services using the JAX-WS RI's Spring support ...............................1......................................................................................................................................................................................................................................................................................10...... Integration ......7............................................................................................... 577 19......................................................................................... 575 Providing a link to data from the model with @ModelAttribute ....................................................8............... 593 Accessing web services using JAX-WS .......................... Annotation-based controller configuration ................................ JMS ................................5............... 581 Linking in the service at the client ....9................. 583 Wiring up the DispatcherServlet for Hessian and co................................................................................ Considerations when choosing a technology ..................................................................................................... Accessing RESTful services on the Client .............................. 577 Customizing data binding with @InitBinder .................... 583 Linking in the service on the client ............... 597 20..... 586 20. Auto-detection is not implemented for remote interfaces ... 585 20. Exposing services using RMI .................... 584 Applying HTTP basic authentication to a service exposed through Hessian or Burlap ............................................................................................................... 593 20... 600 3.................................................... 584 Using Burlap .... 594 Server-side configuration ............................................Spring Framework 19......................................................3................................... 571 Setting up the dispatcher for annotation support ................................ 580 20.................................... 580 20.........6..................... Portlet application deployment ..............................4............ 582 20................. Remoting and web services using Spring .................................................... 585 Linking in the service at the client ................................ Using Hessian or Burlap to remotely call services via HTTP ..... 571 Defining a controller with @Controller .. 595 Client-side configuration ........................................................................................ 587 Exposing servlet-based web services using JAX-RPC ................................... 576 Customizing WebDataBinder initialization .......................... Web services ..........................2............................. 591 Exposing servlet-based web services using JAX-WS ..................................... Introduction .............................................................................................................................

............................................................................ 602 MappingJacksonHttpMessageConverter .......2.......... Accessing EJBs ....................................................................................................................... 611 22................................................................. 618 Synchronous Reception ................... 601 HTTP Message Conversion .........................................................................Message-Driven POJOs .................... 603 21............................................................................ 604 21............................................................................................................................................................. 618 The SessionAwareMessageListener interface ............................................................................................ 617 SessionCallback and ProducerCallback ......................1.................................................................................. 602 MarshallingHttpMessageConverter ........... 613 CachingConnectionFactory ..... Introduction ........................................................................... 618 22........................................ 614 SimpleMessageListenerContainer ......4............... 602 FormHttpMessageConverter ............................................................................................ 613 SingleConnectionFactory .................................. Using Spring JMS ..... Support for JCA Message Endpoints ........................................... 629 23....................................................................6............ Receiving a message ........ 612 Caching Messaging Resources ....... 609 22...................................................... 615 Transaction management ....... Introduction . JMS (Java Message Service) .. 603 BufferedImageHttpMessageConverter .......................................... 611 Connections ..............................................................................5.......... 615 DefaultMessageListenerContainer ...........................................................................................................................................3................................................ 619 The MessageListenerAdapter ............ 604 Accessing local SLSBs ... 619 Processing messages within transactions ................................................................. Using Spring's EJB implementation support classes .............................................. Enterprise JavaBeans (EJB) integration ...............x SLSBs versus EJB 3 SLSBs ................................................................................ 605 Accessing remote SLSBs ................................. 602 ByteArrayHttpMessageConverter .. JMS Namespace Support .......................... 607 EJB 2........................................................................................................................................................................................................................ 604 Concepts ............................. 607 21....................................1................................................................................................................................................................ 611 22.................................. 615 22.....................................................................................1 Reference Documentation xx ..................................................... Sending a Message .........x base classes ... JMX .......................................... 611 JmsTemplate ............................................................................................1......................................................... 618 Asynchronous Reception ... 624 23................. 603 SourceHttpMessageConverter ............................................. 613 Destination Management ..................2. 607 EJB 3 injection interceptor .............................................................................................................................................. 613 Message Listener Containers ..................... Introduction ........ 616 Using Message Converters .............. 604 21......................................................................Spring Framework Dealing with request and response headers ............................3................................ 601 StringHttpMessageConverter ......................... 622 22.................................... 629 3.................................. 606 Accessing EJB 2.................. 621 22...........................................................

...............................8.............. 632 23.................. 640 23...................................................................... 654 The CciTemplate .................... Accessing MBeans via Proxies .................................................. 632 Controlling the registration behavior ............................................................................................ 656 Automatic output record generation .................................................................................................. Modeling CCI access as operation objects ................................... 644 JMX over Burlap/Hessian/SOAP ............................... 641 Using the MetadataNamingStrategy ............................................ 657 Summary .............................................................................................. 651 24..................................................................... 629 Creating an MBeanServer .............................................................................................................................3....................................... 642 23......4...........7.... JSR-160 Connectors ..........................................................2............................................................................................................................. 658 Example for CciTemplate usage .................... 634 Using Source-Level Metadata (JDK 5........ 653 24.......................................................................................3......................5...................................................... 632 Automatic registration of MBeans ................. Exporting your beans to JMX ..0 annotations) ......................................................................................... 661 MappingCommAreaOperation ............................................................................................................ Controlling the ObjectNames for your beans .... 642 The <context:mbean-export/> element ............................................. Notifications .......................................................... 645 Publishing Notifications .......... 657 Using a CCI Connection and Interaction directly .............. Controlling the management interface of your beans ........................................................ 661 MappingRecordOperation . 644 23........................................................................6............................ 659 24...... 650 24............................................... 639 Using MethodNameBasedMBeanInfoAssembler ....................................................................................... JCA CCI ........ 640 Reading ObjectNames from Properties ...... 634 The MBeanInfoAssembler Interface ...........................................2..............................................................1................................................................................. 651 ConnectionFactory configuration in Spring ..................................................................................................................................................................... 643 Server-side Connectors ............................................... 649 23......... Introduction .................................................................4......................................................... 655 DAO support ............................................................ Configuring CCI .....................................1 Reference Documentation xxi ........................................... 631 Lazy-initialized MBeans ................................................... 645 23.Spring Framework 23................................... 645 Registering Listeners for Notifications ........................ 643 Client-side Connectors . 662 3..................... 653 Using a single CCI connection ................................................................................................. 652 Configuring CCI connections ..................... 651 24........... 638 Defining management interfaces using Java interfaces .................. 651 Connector configuration .................................................................................. 662 Automatic output record generation ................................................................................. 634 Source-Level Metadata Types .................................... Using Spring's CCI access support ................. Further Resources ......... 654 Record conversion .......... 630 Reusing an existing MBeanServer ................... 636 The AutodetectCapableMBeanInfoAssembler interface ................................................................................

............................................................ 675 26...........................................Spring Framework Summary .....................................................................1............................................................................................................... 680 The 'executor' element ........................................1 Reference Documentation xxii ...................................................... Introduction ........ Annotation Support for Scheduling and Asynchronous Execution . 682 The @Scheduled Annotation .......................................................................................................4.............................................. A first example ...................................... 680 The 'scheduler' element ..7........................................ 675 TaskExecutor types ... Email ................................................................ The Spring TaskExecutor abstraction ..........................5.............................................................2........................................................................................................................................... 689 27........................ 678 Trigger implementations ..................... Using the JavaMail MimeMessageHelper ......... 679 26......... 672 A Velocity-based example ................................. Usage ..2.......................... 680 The 'scheduled-tasks' element ........................... 669 Using the JavaMailSender and the MimeMessagePreparator .................................................................... Defining beans that are backed by dynamic languages ..... Introduction ............................................. 691 Common concepts ................. 665 24...........1................... Introduction ............................................... 687 Creating custom timers ................................................................................................................................................................... 683 The <annotation-driven> Element ........................................... 673 26................. 681 26.................. 679 TaskScheduler implementations ........................................................................................................................................................................................... 691 3...................................................................... Task Execution and Scheduling ............ 684 Using the JobDetailBean ... 671 Creating email content using a templating library . 670 25................................................... 682 The @Async Annotation ........................................2..... Dynamic language support .........3.......................................................................................................................................................................................... 671 Sending attachments and inline resources .................................. Using JDK Timer support ... 668 25........... The Spring TaskScheduler abstraction ....................................................................................................................................................... 662 Example for MappingRecordOperation usage ...................... 687 Wrapping up: setting up the tasks using the TimerFactoryBean ...... 689 27............................ 684 Using the MethodInvokingJobDetailFactoryBean .............................. 688 27.................................................................................................... 663 Example for MappingCommAreaOperation usage ........................................................................................................................ 685 Wiring up jobs using triggers and the SchedulerFactoryBean ............. 684 26...................3. 675 Using a TaskExecutor ...... 675 26............................................................. The Task Namespace ......... 671 Attachments .... 668 25..... Transactions ............................... 686 26................................................................................................... 678 The Trigger interface ................................................. 666 25........5............................................................................. 687 Using the MethodInvokingTimerTaskFactoryBean .........................6......... Using the Quartz Scheduler ........................ 677 26................................. 671 Inline resources ................................................................. 689 27..................................................3............. 668 Basic MailSender and SimpleMailMessage usage ........................1..

.4................................ Configuring the cache storage ....................................................................................................................................................................... 717 VII................................................ Scenarios .1 Reference Documentation xxiii ....................................6............ 710 @CacheEvict annotation . 717 28................ Bits and bobs .......................................................................... 719 Hibernate ...........................................................advising scripted beans ......... 702 Scripted Validators .......... Declarative XML-based caching .................................................................................................................................. 711 Enable caching annotations ....................................... 701 27.................................... 698 Customising Groovy objects via a callback ................. 718 A..................... 696 Groovy beans .................................................................................................................................................................................... 704 AOP ......................................5.... 692 Inline dynamic language source files .......................................................................... 706 28............................3........................................ Appendices ................................................................ Plugging-in different back-end caches ............................................................................................................................................... 710 @Caching annotation ..........................................................................7............................................................................................................5............................... 705 28................ 719 The HibernateTemplate .................... 702 Scripted Spring MVC Controllers .................................................................... 709 Available caching SpEL evaluation context .............................................................................................. 707 Default Key Generation ................ 708 Custom Key Generation Declaration .........................................................6.. Classic ORM usage ................... How can I set the TTL/TTI/Eviction policy/XXX feature? .......................................................................................... 695 Understanding Constructor Injection in the context of dynamic-language-backed beans ........ 707 @Cacheable annotation .....................1................................................................. 721 3................................... Further Resources ................... 706 28.................................. Introduction ..... Cache Abstraction ...................................................................................................................................... 704 Scoping .. Declarative annotation-based caching ............................................... 709 @CachePut annotation .......................... 719 A................................................. 715 28.................................... 704 27............... 720 JDO .... 716 Dealing with caches without a backing store .............................................................................................................................................2................................................... 708 Conditional caching ............... 716 28.......... Understanding the cache abstraction ........................... 692 Refreshable beans ....................................................................................... 706 28..........................................................1............................................... 695 JRuby beans ....................... 716 Ehcache-based Cache ..................................................... 719 Implementing Spring-based DAOs without callbacks .. 716 JDK ConcurrentMap-based Cache ................................ 714 28..................... Classic Spring Usage ............................................................................... 700 BeanShell beans .......................................................4............ 721 JdoTemplate and JdoDaoSupport ...................................................................... 711 Using custom annotations .........................................................................................................................................Spring Framework The <lang:language/> element ........................................ 703 27.................................

............ 725 B............................................................................1 Reference Documentation xxiv ........................ 748 Using metadata-driven auto-proxying ........................................... 734 B............................................... 744 B....................................................................................... JMS Usage ............................................ 730 Advice types in Spring .................................................. Concise proxy definitions ...................................... 737 JavaBean properties ......... 730 Advice lifecycles ...................................................................... 747 AbstractAdvisorAutoProxyCreator .......................... 738 JDK......................................................................................................................................................................................... 740 Proxying classes ...................... Using the ProxyFactoryBean to create AOP proxies ........................................... 751 Hot swappable target sources .......... 751 3................................................................................................................................................................................. 746 BeanNameAutoProxyCreator ............................................................................ Manipulating advised objects ................................................................................................................................................. 727 Convenience pointcut implementations .................................................................................................. 723 A................ 748 B.. 742 B..............3..................................................................................... 743 B....... 725 Transaction Management .................9.........4.. 730 B.... Using TargetSources ................... Pointcut API in Spring ........................................................................................................................................ Advice API in Spring ........................ 737 Basics ...............................................................2.................................................................................................... 739 Proxying interfaces ........ 729 Custom pointcuts .............. 726 Concepts ............ 733 Introduction advice .7..........................................................................................................................................Spring Framework JPA ................................................................ Classic Spring MVC ................................................ 737 B...................... Advisor API in Spring ............ 724 Asynchronous Message Reception .... 731 Throws advice ..........................1... 727 Static pointcuts .........................3.................................................................................................................................................................... 727 Dynamic pointcuts ........and CGLIB-based proxies .................................................................................................... Using the "autoproxy" facility .............. 732 After Returning advice ....................................................................... 744 B........................................................................................................................................................................................................... 729 Pointcut superclasses .................................................................................................................6.......... 726 B................................................................................................ 724 Connections ... Creating AOP proxies programmatically with the ProxyFactory ............................................................ 726 Operations on pointcuts ......................................................................................... 746 Autoproxy bean definitions .... 722 A................................ 724 JmsTemplate ..................................................................2.................................... 727 AspectJ expression pointcuts ...................................................................................................................................................... 730 Before advice ... 746 DefaultAdvisorAutoProxyCreator ............................................. 742 Using 'global' advisors ........................................................... Classic Spring AOP Usage ......... 722 JpaTemplate and JpaDaoSupport .. 730 Interception around advice ..................................................8.......5...

............................ 760 <util:properties/> ............................. 761 <util:list/> .................................................................... 756 C............................................................................................ 765 <jee:jndi-lookup/> (complex) ......Spring Framework Pooling target sources ........................................................................ 758 <util:property-path/> .................................................................................................................................................................................................................... 766 <jee:local-slsb/> (complex) ....................1 Reference Documentation xxv ................................................. 765 <jee:jndi-lookup/> (with multiple JNDI environment settings) ............................... 776 'META-INF/spring................................................... 770 The tool schema ...................... 764 <jee:jndi-lookup/> (simple) ............. 757 Referencing the schemas ............................................................................ 764 <jee:jndi-lookup/> (with single JNDI environment setting) ............................................ 756 C............................................................................................................................................. 771 D.......................................4...... XML Schema-based configuration ............................................... 772 D.................................................................................... 758 <util:constant/> ............................... 770 <component-scan/> ...................... Introduction .......................................................................... 766 <jee:local-slsb/> (simple) ...............................................................................................................................1................................... 775 'META-INF/spring... 770 <spring-configured/> ...............................................................handlers' ...............................................................3................................................schemas' ................................................. 768 The tx (transaction) schema ................................................... 763 The jee schema ............................................5............. 774 D........................................................................................................2................................................................ 752 Prototype target sources .......... Coding a BeanDefinitionParser ...................................................................... 767 The jms schema ................................................ 762 <util:map/> ......... Extensible XML authoring .................................................................... 771 The beans schema ............................................................................................................................................. Introduction ........................................................................................................................ 754 B............................................................................... 772 D............................................................................................. 770 <mbean-export/> ........................... 757 The util schema .......................................................................................................................... 769 The context schema .............. 767 The lang schema .......................................... Coding a NamespaceHandler ........................... Defining new Advice types .....2............. Further resources ..... 753 ThreadLocal target sources .......... 772 D....................................10.............. 774 D.............. 763 <util:set/> ............................................................................................1........................................... 768 The aop schema ............... XML Schema-based configuration ............................................................................................. 770 <load-time-weaver/> .............................................................................. 754 C............................................................................................................ 766 <jee:remote-slsb/> ....... 753 B...............................11................................. 769 <property-placeholder/> ................ 776 3............................... 770 <annotation-config/> .......................................... Authoring the schema .................................... Registering the handler and the schema ...............

........................................... 796 F.......................... 813 G........... The textarea tag ....................................................................11................. 800 G................ 804 G.............................3....tld ........................................ 800 G.................. 795 F...........................................1................................................5........................................................................................................................... The checkboxes tag ....................................... 776 D....... 798 G..... 794 F............... The option tag .............................................................................................10................................................... The radiobuttons tag .............................13...........15.................... 796 F................................................................................6........................ The eval tag .........2........8...........................12...................... The options tag .........................................................................................5.................................... The url tag .................................... The radiobutton tag ....................tld ................................ 800 G..............................8...................................................................................... 777 Custom attributes on 'normal' elements ....... 811 G............................................. 805 G.................................. 777 Nesting custom tags within custom tags ................. Further Resources ............................................................................9................................................. 794 F.............. The errors tag ........Spring Framework D....................................... 815 G........ spring..... Introduction ............... 783 F...........11......7........... The hasBindErrors tag ............7........ The input tag .................9...........6..................................0............ 780 D............................................................. 821 3...................................... 807 G........................................................10.................. 807 G..................................................................................................... The checkbox tag ........................................... The nestedPath tag ................ Using a custom extension in your Spring XML configuration ................................................................. The hidden tag .... 812 G..... 809 G......... 794 F........................................8.................... The select tag ........................................................................................ The htmlEscape tag ..... 797 F..............................................................................................4...................................................................... Introduction ................... The transform tag .................. 817 G....................................................... spring-form................ 795 F........................................14......................................... The message tag ...... The escapeBody tag .... Meatier examples .................................... 797 F.......................................................................................4........ 795 F......................................................... The bind tag .......................... 798 F........... The label tag ....................................................................2..... 782 E...............1 Reference Documentation xxvi ..................................................................... The form tag ...............dtd ...6..... 802 G..... The password tag ....... The theme tag ..... spring-beans-2..3............1..................7..................... 819 G............

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

where to apply it. Although the Java platform provides a wealth of application development functionality. Abstract Factory. leaving that task to architects and developers. you can use design patterns such as Factory.typically consist of objects that collaborate to form the application proper. For insight into IoC and DI. Decorator.Spring Framework 1. http://martinfowler. it lacks the means to organize the basic building blocks into a coherent whole. Fowler suggested renaming the principle to make it more self-explanatory and came up with Dependency Injection. • Make a local Java method a remote procedure without having to deal with remote APIs. This capability applies to the Java SE programming model and to full and partial Java EE.1 Reference Documentation 2 .com/articles/injection.a loose term that runs the gamut from constrained applets to n-tier server-side enterprise applications -. and so forth. However. Builder. and Service Locator to compose the various classes and object instances that make up an application. as an application developer. Patterns are formalized best practices that you must implement yourself in your application. Thus the objects in an application have dependencies on each other. can use the Spring platform advantage: • Make a Java method execute in a database transaction without having to deal with transaction APIs. Introduction to Spring Framework Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. • Make a local Java method a message handler without having to deal with JMS APIs.1 Dependency Injection and Inversion of Control Background “The question is. these patterns are simply that: best practices given a name. with a description of what the pattern does. Spring enables you to build applications from “plain old Java objects” (POJOs) and to apply enterprise services non-invasively to POJOs. True. Examples of how you. refer to Fowler's article at Java applications -. The Spring Framework Inversion of Control (IoC) component addresses this concern by providing a 3. • Make a local Java method a management operation without having to deal with JMX APIs. 1. the problems it addresses. what aspect of control are [they] inverting?” Martin Fowler posed this question about Inversion of Control (IoC) on his site in 2004. Spring handles the infrastructure so you can focus on your application.html.

3. Data Access/Integration. Context. 1. Overview of the Spring Framework Core Container The Core Container consists of the Core. Numerous organizations and institutions use the Spring Framework in this manner to engineer robust.2 Modules The Spring Framework consists of features organized into about 20 modules. The Spring Framework codifies formalized design patterns as first-class objects that you can integrate into your own application(s). and Test. as shown in the following diagram. AOP (Aspect Oriented Programming). These modules are grouped into Core Container. Instrumentation.1 Reference Documentation 3 . Beans. maintainable applications.Spring Framework formalized means of composing disparate components into a fully working application ready for use. Web. and Expression Language modules.

The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB. for example. JDO. method invocation. Castor. and retrieval of objects by name from Spring's IoC container. such as the simple declarative transaction management feature mentioned previously. The language supports setting and getting property values.and basic remoting. a servlet container. including JPA. Web The Web layer consists of the Web. Web-Servlet. 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. and the transparent creation of contexts by. 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. JMX . and iBatis.Spring Framework The Core and Beans modules provide the fundamental parts of the framework. accessing the context of arrays. It is an extension of the unified expression language (unified EL) as specified in the JSP 2. collections and indexers. including the IoC and Dependency Injection features. 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 3. Hibernate. The ApplicationContext interface is the focal point of the Context module. The BeanFactory is a sophisticated implementation of the factory pattern. Web-Struts. The Context module inherits its features from the Beans module and adds support for internationalization (using. property assignment. for example. The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs (plain old Java objects). Using the ORM package you can use all of these O/R-mapping frameworks in combination with all of the other features Spring offers. logical and arithmetic operators. The Context module also supports Java EE features such as EJB. It removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic. The ORM module provides integration layers for popular object-relational mapping APIs.1 Reference Documentation 4 . The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime. JiBX and XStream. ORM. resource-loading. OXM. JMS and Transaction modules. It also supports list projection and selection as well as common list aggregations. event-propagation. resource bundles). and Web-Portlet modules. named variables. XMLBeans. Data Access/Integration The Data Access/Integration layer consists of the JDBC.1 specification. The Java Messaging Service (JMS) module contains features for producing and consuming messages.

Using source-level metadata functionality.0 and its Spring integration or to a Spring MVC solution. in a manner similar to that of . Note that this support is now deprecated as of Spring 3. method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for web applications. Consider migrating your application to Struts 2. The Instrumentation module provides class instrumentation support and classloader implementations to be used in certain application servers. and integrates with all the other features of the Spring Framework. The separate Aspects module provides integration with AspectJ. you can also incorporate behavioral information into your code. It also provides mock objects that you can use to test your code in isolation. 3. The Web-Struts module contains the support classes for integrating a classic Struts web tier within a Spring application.3 Usage scenarios The building blocks described previously make Spring a logical choice in many scenarios.1 Reference Documentation 5 . It provides consistent loading of Spring ApplicationContexts and caching of those contexts. Test The Test module supports the testing of Spring components with JUnit or TestNG. from applets to full-fledged enterprise applications that use Spring's transaction management functionality and web framework integration. Spring's MVC framework provides a clean separation between domain model code and web forms. for example.Spring Framework application context.0. 1. It also contains the web-related parts of Spring's remoting support. The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module. AOP and Instrumentation Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define.NET attributes.

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

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

Enabling remote access to existing applications is not difficult. 3.Spring Framework Remoting usage scenario When you need to access existing code through web services.or JaxRpcProxyFactory classes.1 Reference Documentation 8 . Rmi. Burlap-. you can use Spring's Hessian-.

The actual jar file name that you use may be 3. spring-jms.g.Wrapping existing POJOs The Spring Framework also provides an access and abstraction layer for Enterprise JavaBeans. storing them and adding them to classpaths. etc. To make this easier Spring is packaged as a set of modules that separate the dependencies as much as possible. The indirect dependencies are also known as "transitive" and it is those dependencies that are hardest to identify and manage. so for example if you don't want to write a web application you don't need the spring-web modules. Dependencies can be direct (e. where "*" represents the short name for the module (e. The process of dependency management involves locating those resources. These dependencies are not virtual components that are injected.g. spring-core.). spring-webmvc.Spring Framework EJBs . Dependency Management and Naming Conventions Dependency management and dependency injection are different things. my application depends on commons-dbcp which depends on commons-pool). 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. or indirect (e. but physical resources in a file system (typically). fail-safe web applications that might need declarative security. To refer to Spring library modules in this guide we use a shorthand naming convention spring-* or spring-*. enabling you to reuse your existing POJOs and wrap them in stateless session beans for use in scalable.jar.1 Reference Documentation 9 .g. my application depends on Spring at runtime). 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.

jar). In general. • The Enterprise Bundle Repository (EBR). • 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). 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. Both full releases and also milestones and development snapshots are deployed here.0 are in the form org.springsource.org/downloads/community.g. The names of the jars here are in the form spring-*-<version>. Both Maven and Ivy repositories are available here for all Spring jars and their dependencies. do not mix them. plus a large number of other common libraries that people use in applications with Spring.springframework.RELEASE. If OSGi does not matter to you. Comparison of Maven Central and SpringSource EBR Repositories Feature OSGi Compatible Number of Artifacts Maven Central Not explicit Tens of thousands. since it houses OSGi compatible artifacts for all of Spring's dependencies. The names of the jars here since version 3. Table 1. those integrates with that Spring 3. In general. which is run by SpringSource and also hosts all the libraries that integrate with Spring. • Maven Central.springframework. though there are some pros and cons between them. such as Hibernate and Freemarker.springframework. with external libraries (not from SpringSource) having the prefix com. The names of the jar files are in the same form as the community download (org. all kinds EBR Yes Hundreds. and the dependencies are also in this "long" form. use the EBR.Spring Framework in this form (see below) or it may not. and normally it also has a version number in the file name (e. but you can also do it manually by downloading all the jars yourself. In general. See the FAQ for more information.1 Reference Documentation 10 . This is particularly important since EBR artifacts necessarily use a different naming convention than Maven Central artifacts.0. spring-core-3. So the first thing you need to decide is how to manage your dependencies: most people use an automated system like Maven or Ivy. Here you find all the Spring jars bundled together into a zip file for easy download.jar.0. which is the default repository that Maven queries.jar).1.*-<version>. so this is a useful place to get development versions of Spring to use with other libraries depoyed in Maven Central.springsource. Spring publishes its artifacts to four different places: • On the community download site http://www. if you care about OSGi. pick one place or the other for your project. When obtaining Spring with Maven or Ivy you have then to decide which place you'll get it from. and does not require any special configuration to use.jar and the Maven groupId is org. so this is convenient for them. The jar file names are in the same form as Maven Central.*-<version>. either place works.

springframework artifact name. logj4. Project SpringSource) authors can upload individual jars to JIRA. Various http://www. Many new artifacts use m.springsource. Ordering is defined but not often relied on. The text qualifier imposes alphabetic ordering on versions with the same numeric values. Hosting Search Utilities Contegix. Quality Assurance is Extensive for OSGi manifest. it intentionally keeps its mandatory dependencies to an absolute minimum: you shouldn't have to locate 3. spring-core.0. separator.springsource. org.m. Varies.X. e. Generally the project or Bundle Symbolic Name.m. e. If the jar had to be patched to ensure OSGi compliance then com.apache. e.g. derived module name. com. Older ones often just use the org. CloudFoundry Spring Dependencies and Depending on Spring Although Spring provides integration and support for a huge range of enterprise and other external tools. so not strictly reliable. e.org.m. Maven POM and Ivy metadata.g. using a hyphen "-" from the main package root. X=text). OSGi version number m.com/repository Integration with SpringSource Integration through STS with Extensive integration through Tools Maven dependency management STS with Maven. e.springsource is appended. package root. e.1 Reference Documentation 11 . log4j.m. with several mirrors.m.m. Funded by Sonatype S3 funded by SpringSource.m or m. By policy.Spring Framework Feature Consistent Naming Conventions Naming Convention: GroupId Maven Central No EBR Yes Varies.log4j Varies. QA performed by Spring team.g.g.g.X (with m=digit.slf4j. Newer artifacts often use Domain name of origin or main domain name. Accuracy responsibility of authors.springframework.RC3.g. Roo.beans. Some neither. org. e. 3.0. Older ones use m. processed by Naming Convention: ArtifactId Naming Convention: Version Publishing Usually automatic via rsync or Manual (JIRA source control updates.g.

org/milestone/</url> <snapshots><enabled>false</enabled></snapshots> </repository> </repositories> And for snapshots: 3. so that works with Maven Central or the SpringSource S3 Maven repository.springframework. Next we outline the basic steps needed to configure an application that depends on Spring. if anything is unclear. Note the scope can be declared as runtime if you don't need to compile against Spring APIs.g.maven. For basic dependency injection there is only one mandatory external dependency.milestone</id> <url>http://maven. To use the S3 Maven repository (e.Spring itself uses Ivy to manage dependencies when it is building. and that is for logging (see below for a more detailed description of logging options).Spring Framework and download (even automatically) a large number of jar libraries in order to use Spring for simple use cases. and our samples mostly use Maven. to create an application context and use dependency injection to configure an application.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.repository.1 Reference Documentation 12 .springsource.maven. refer to the documentation of your dependency management system.org/release/</url> <snapshots><enabled>false</enabled></snapshots> </repository> </repositories> For milestones: <repositories> <repository> <id>com.springsource. which is typically the case for basic dependency injection use cases.RELEASE</version> <scope>runtime</scope> </dependency> </dependencies> That's it. For full releases: <repositories> <repository> <id>com. your Maven dependencies will look like this: <dependencies> <dependency> <groupId>org. for milestones or developer snaphots).springframework. first with Maven and then with Ivy.release</id> <url>http://maven.0. We used the Maven Central naming conventions in the example above. you need to specify the repository location in your Maven configuration.repository.0. or look at some sample code . Maven Dependency Management If you are using Maven for dependency management you don't even need to supply the logging dependency explicitly. For example. In all cases.

release</id> <url>http://repository.springframework.[ext]" /> <artifact pattern="http://repository.repository.0.bundles. It also has handy snippets of Maven and Ivy configuration that you can copy and paste if you are using those tools.maven.g.springsource. but there is a user interface at http://www. e.springsource.bundles.springsource.springsource.springframework.[ext]" /> </url> <url name="com.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.repository.[ext]" /> <artifact pattern="http://repository.xml: <resolvers> <url name="com.com/ivy/bundles/release/ [organisation]/[module]/[revision]/[artifact]-[revision].repository.springframework</groupId> <artifactId>org.springsource.com/ivy/bundles/release/ [organisation]/[module]/[revision]/[artifact]-[revision].snapshot</id> <url>http://maven.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 the dependencies.com/ivy/bundles/external/ [organisation]/[module]/[revision]/[artifact]-[revision].com/ivy/bundles/external/ 3.com/maven/bundles/release/</url> </repository> </repositories> If you are managing your dependencies by hand.springsource. in this case it is: <dependencies> <dependency> <groupId>org.bundles. Ivy Dependency Management If you prefer to use Ivy to manage dependencies then there are similar names and configuration options.release"> <ivy pattern="http://repository.0.springsource.springsource.external"> <ivy pattern="http://repository. To configure Ivy to point to the SpringSource EBR add the following resolvers to your ivysettings. the URL in the repository declaration above is not browseable.1 Reference Documentation 13 .context</artifactId> <version>3.Spring Framework <repositories> <repository> <id>com.com/repository that can be used to search for and download dependencies. The names are usually easy to guess.springsource.repository.springsource.

The way we do this is to make one of the modules in Spring depend explicitly on commons-logging (the canonical implementation of JCL). Not Using Commons Logging Unfortunately. Simply pull up the details page for the bundle in question in the repository browser and you'll find an Ivy snippet ready for you to include in your dependencies section. including all external components.RELEASE" conf="compile->runtime"/> Logging Logging is a very important dependency for Spring because a) it is the only mandatory external dependency. The mandatory logging dependency in Spring is the Jakarta Commons Logging API (JCL). This is more difficult than it might have been since there are so many choices of logging framework. then it is from Spring and specifically from the central module called spring-core.logging or JUL for short). and wondering where you picked up the dependency on commons-logging. One of the goals of an application developer is often to have unified logging configured in a central place for the whole application.xml): <dependency org="org. and then make all the other modules depend on that at compile time.1 Reference Documentation 14 .0. 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.Spring Framework [organisation]/[module]/[revision]/[artifact]-[revision]. while convenient for the end-user. The nice thing about commons-logging is that you don't need anything else to make your application work.core" rev="3. and c) Spring integrates with lots of other tools all of which have also made a choice of logging dependency.springframework" name="org. If you are using Maven for example.springframework.util.[ext]" /> </url> </resolvers> The XML above is not valid because the lines are too long . If nothing else is available you get pretty nice looking logs just from the JDK (java. b) everyone likes to see some output from the tools they are using. and that's important.0. We compile against JCL and we also make JCL Log objects visible for classes that extend the Spring Framework. If we could turn back the clock and start Spring now as a new project it would 3. is problematic. Once Ivy is configured to look in the EBR adding a dependency is easy. For example (in ivy. 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). the runtime discovery algorithm in commons-logging. You should find that your Spring application works and logs happily to the console out of the box in most situations.if you copy-paste then remove the extra line endings in the middle of the url patterns.

and declare it or configure it accordingly. which is also used by a lot of other tools that people use with Spring inside their applications. and bind to that for configuration and management. so if other libraries in your application use that API.1 Reference Documentation 15 . In Maven you would do that like this <dependencies> <dependency> <groupId>org. Switching off commons-logging is easy: just make sure it isn't on the classpath at runtime. and the Log4J implementation itself.0. SLF4J provides bindings to many common logging frameworks. and then provide explicit binding from SLF4J to Log4J. the binding to Log4J. You need to supply 4 dependencies (and exclude the existing commons-logging): the bridge. In Maven terms you exclude the dependency. <dependencies> <dependency> <groupId>org. so you can usually choose one that you already use. SLF4J provides bindings to many common logging frameworks.springframework</groupId> <artifactId>spring-context</artifactId> <version>3. the SLF4J API. Using SLF4J SLF4J is a cleaner dependency and more efficient at runtime than commons-logging because it uses compile-time bindings instead of runtime discovery of the other logging frameworks it integrates. including JCL. and because of the way that the Spring dependencies are declared. you only have to do that once.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 on the classpath.RELEASE</version> <scope>runtime</scope> <exclusions> 3. Once you have done that then logging calls from within Spring will be translated into logging calls to the SLF4J API.0. So to use SLF4J with Spring you need to replace the commons-logging dependency with the SLF4J-JCL bridge. so to fix it a new one has to be provided.0. and it also does the reverse: bridges between other logging frameworks and itself.Spring Framework use a different logging dependency. then you have a single place to configure and manage logging. The first choice would probably be the Simple Logging Facade for Java (SLF4J). This also means that you have to be more explicit about what you want to happen at runtime.0.springframework</groupId> <artifactId>spring-context</artifactId> <version>3. In the next section we show you how to provide an alternative implementation of JCL using SLF4J as an example. A common choice might be to bridge Spring to SLF4J.

Spring also provides some utilities for configuring and initializing Log4j. notably if you are in a strict container like an OSGi platform. So for Maven users this is your dependency declaration: <dependencies> <dependency> 3. This removes the extra binding step because Logback implements SLF4J directly.5. and in fact it's what we use at runtime when we build and test Spring.8</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.properties or log4j. because you only want one version of that API on the classpath. so it has an optional compile-time dependency on Log4j in some modules.8</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1. Allegedly there is also a performance benefit because the bindings are at compile-time not runtime.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1. A more common choice amongst SLF4J users.2.Spring Framework <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.8</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1. Using Log4J Many people use Log4j as a logging framework for configuration and management purposes.14</version> <scope>runtime</scope> </dependency> </dependencies> That might seem like a lot of dependencies just to get some logging.1 Reference Documentation 16 . If you do that you might also need to exlude the slf4j-api dependency from other external dependencies (not Spring). To make Log4j work with the default JCL dependency (commons-logging) all you need to do is put Log4j on the classpath.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1. which uses fewer steps and generates fewer dependencies. It's efficient and well-established.xml in the root of the classpath). and it should behave better than the vanilla commons-logging with respect to classloader issues.5. Well it is.5. but it is optional. is to bind directly to Logback. and provide it with a configuration file (log4j. so you only need to depend on two libaries not four (jcl-over-slf4j and logback).

stdout.log4j.beans.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.rootCategory=INFO. To be clear about this: the problems reported are usually not with JCL per se. but there are plenty of other suggestions in the public domain for alternative approaches. simply excluding commons-logging from your application is not enough in most situations. IBM Websphere Application Server (WAS) is the archetype.factory=DEBUG Runtime Containers with Native JCL Many people run their Spring applications in a container that itself provides an implementation of JCL. not the container.Spring Framework <groupId>org. or even with commons-logging: rather they are to do with binding commons-logging to another framework (often Log4J).1 Reference Documentation 17 .appender. That option isn't always open.appender.layout=org. stdout log4j.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L .ConsoleAppender log4j.RELEASE</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.0) found in some containers and the modern versions that most people use now (1. but as soon as Spring or your application tries to do any logging you can find that the bindings to Log4J are not working.PatternLayout log4j. Spring does not use any unusual parts of the JCL API.apache.0. 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.layout.2. This often causes problems.org.springframework.category.%m%n log4j.properties for logging to the console: log4j.log4j. and your mileage may vary depending on the exact version and feature set of the container.stdout.0. and unfortunately there is no silver bullet solution.stdout=org. so nothing breaks there.14</version> <scope>runtime</scope> </dependency> </dependencies> And here's a sample log4j.appender.1). 3. This can fail because commons-logging changed the way they do the runtime discovery in between the older versions (1.apache.

What's New in Spring 3 .Part II.

some errors may nevertheless have crept in. Spring's TaskExecutor abstraction has been updated for close integration with Java 5's java. Generic ApplicationListeners automatically receive specific event types only. While every effort has been made to ensure that there are no errors in this documentation. ThreadFactory integration. released in November 2007.1's @Asynchronous annotation). 2.3 New articles and tutorials 3.util. This has been aligned with JSR-236 (Concurrency Utilities for Java EE 6) as far as possible.concurrent facilities. as well as ExecutorService adapters. please do bring the error to the attention of the Spring team by raising an issue. and Spring 2. the Spring core codebase is now freshly revised and optimized for Java 5.0.2 Improved documentation The Spring reference documentation has also substantially been updated to reflect all of the changes and new features for Spring 3. New Features and Enhancements in Spring 3. while at the same time introducing some early support for Java EE 6. etc. released in October 2006. varargs and other language improvements. and Java 6 is fully supported.Spring Framework 2.0.1 Reference Documentation 19 . Spring is compatible with J2EE 1.5. and also consistent resolution of bridge methods in the Spring AOP API.4 and Java EE 5. Java SE and Java EE Support The Spring Framework is now based on Java 5. 2. We now have consistent use of generic Collections and Maps. It is now time for a third overhaul resulting in Spring 3. you will be aware that Spring has undergone two major revisions: Spring 2. and you can spare a few cycles during lunch. 2.1 Java 5 The entire framework code has been revised to take advantage of Java 5 features like generics. Overall.0 If you have been using the Spring Framework for some time. Furthermore. consistent use of generic FactoryBeans.0. If you do spot any typos or even more serious errors. We have done our best to still keep the code backwards compatible. we provide support for asynchronous method invocations through the use of the new @Async annotation (or EJB 3. Furthermore. We provide first-class support for Callables and Futures now. All callback interfaces such as TransactionCallback and HibernateCallback declare a generic result value now.

springframework.springframework.springframework.beans • org.springframework.1 Reference Documentation 20 .springframework. The samples have been improved and updated to take advantage of the new features in Spring 3.oxm • org.context • org.springframework.Spring Framework There are many excellent articles and tutorials that show how to get started with Spring 3 features.springframework.test • org.apache. the samples have been moved out of the source tree into a dedicated SVN repository available at: https://anonsvn.springframework.instrument • org.expression • org. Read them at the Spring Documentation page.org/svn/spring-samples/ As such.springframework. the samples are no longer distributed alongside Spring 3 and need to be downloaded separately from the repository mentioned above. Note For more information on Subversion (or in short SVN).springframework.springframework.support • org.org/ 2.jms • org. this documentation will continue to refer to some samples (in particular Petclinic) to illustrate various features.springframework.orm • org. see the project homepage at: http://subversion.context.aop • org.springframework.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.jdbc • org. Additionally.transaction 3. However.

springframework. We are now using a new Spring build system as known from Spring Web Flow 2.1 Reference Documentation 21 . This gives us: • Ivy-based "Spring Build" system • consistent deployment procedure • consistent dependency management • consistent generation of OSGi manifests 2.servlet • org.web.5 Overview of new features This is a list of new features for Spring 3.Spring Framework • org.portlet • org.web.web.0.struts Note: The spring.springframework.0.web • org. • 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 3.jar artifact that contained almost the entire framework is no longer provided. We will cover these features in more detail later in this section.springframework.springframework.

concurrent. T> getBeansOfType(Class<T> type) Spring's TaskExecutor interface now extends java. 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.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> Spring Expression Language Spring introduces an expression language which is similar to Unified EL in its syntax but offers significantly more features. Its language features are driven by the requirements of the projects in the Spring portfolio.Spring Framework 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.databaseKeyGenerator}"/> </bean> This functionality is also available if you prefer to configure your components using annotations: @Repository public class RewardsTestDatabase { 3.databaseName}"/> <property name="keyGenerator" value="#{strategyBean.RewardsTestDatabase"> <property name="databaseName" value="#{systemProperties.1 Reference Documentation 22 . Details of this new functionality can be found in the chapter Spring Expression Language (SpEL). including tooling requirements for code completion support within the Eclipse based SpringSource Tool Suite. The Spring Expression Language was created to provide the Spring community a single. Class<T> requiredType) • Map<String.util. The following is an example of how the Expression Language can be used to configure some properties of a database setup <bean class="mycompany. well supported expression language that can be used across all the products in the Spring portfolio.

@Bean public FooService fooService() { return new FooServiceImpl(fooRepository()).databaseName}") public void setDatabaseName(String dbName) { … } @Value("#{strategyBean.1 Reference Documentation 23 . private @Value("#{jdbcProperties. This means that the following annotations are now directly supported: • @Configuration • @Bean • @DependsOn • @Primary • @Lazy • @Import • @ImportResource • @Value Here is an example of a Java class providing basic configuration using the new JavaConfig features: package org.username}") String username.config.databaseKeyGenerator}") public void setKeyGenerator(KeyGenerator kg) { … } } The Inversion of Control (IoC) container Java based bean metadata Some core features from the JavaConfig project have been added to the Spring Framework now. } @Bean public FooRepository fooRepository() { return new HibernateFooRepository(sessionFactory()). private @Value("#{jdbcProperties.url}") String jdbcUrl.Spring Framework @Value("#{systemProperties.password}") String password. @Configuration public class AppConfig { private @Value("#{jdbcProperties. } @Bean public SessionFactory sessionFactory() { // wire up a session factory AnnotationSessionFactoryBean asFactoryBean = new AnnotationSessionFactoryBean().example. 3.

and may also be used by a Spring Container and DataBinder when binding bean property values. } See the section called “Instantiating the Spring container using AnnotationConfigApplicationContext” for full information on AnnotationConfigApplicationContext. password). The system is currently used by SpEL for type conversion.example. fooService. More information on the use of the OXM module can be found in the Marshalling XML using O/X Mappers chapter.springframework. } @Bean public DataSource dataSource() { return new DriverManagerDataSource(jdbcUrl. username. FooService fooService = ctx. Defining bean metadata within components @Bean annotated methods are also supported inside Spring components.properties"/> Or you can bootstrap a @Configuration AnnotationConfigApplicationContext: class directly using public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig. 3.setDataSource(dataSource()).Spring Framework asFactoryBean. See Defining bean metadata within components for more information General purpose type conversion system and field formatting system A general purpose type conversion system has been introduced.1 Reference Documentation 24 . This SPI provides a simpler and more robust alternative to JavaBean PropertyEditors for use in client environments such as Spring MVC. <context:component-scan base-package="org. In addition.config"/> <util:properties id="jdbcProperties" location="classpath:org/example/config/jdbc. The functionality is found in the org. a formatter SPI has been introduced for formatting field values.getObject().getBean(FooService. // additional config return asFactoryBean.class).doStuff(). The Data Tier Object to XML mapping functionality (OXM) from the Spring Web Services project has been moved to the core Spring Framework now. } } To get this to work you need to add the following component scanning entry in your minimal application context XML file. They contribute a factory bean definition to the container.class).oxm package.

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. See Mapping cookie values with the @CookieValue annotation and Mapping request header attributes with the @RequestHeader annotation for more information. Comprehensive REST support Server-side support for building RESTful applications has been provided as an extension of the existing annotation driven MVC web framework. including HSQL. Early support for Java EE 6 We provide support for asynchronous method invocations through the use of the new @Async annotation (or EJB 3. including JSR 303 support that uses Hibernate Validator as the default provider. The MarshallingHttpMessageConverter uses the Object to XML mapping functionality mentioned earlier.0. H2. JSR 303.0. @MVC additions A mvc namespace has been introduced that greatly simplifies Spring MVC configuration. Refer to the sections on MVC and the RestTemplate for more information. There are also some new annotations that can be used in any web application.1 Reference Documentation 25 . Additional annotations such as @CookieValue and @RequestHeaders have been added. and Derby. Declarative model validation Several validation enhancements.1's @Asynchronous annotation). 3. JPA 2. Client-side support is provided by the RestTemplate class in the spirit of other template classes such as JdbcTemplate and JmsTemplate. etc Support for embedded databases Convenient support for embedded Java database engines. JSF 2.Spring Framework The Web Tier The most exciting new feature for the Web Tier is the support for building RESTful web services and web applications. is now provided.

Cache Abstraction • Chapter 28.Environment Javadoc PropertySource Abstraction • Unified Property Management (SpringSource Team Blog) • See org.1 RC1 is being prepared for release. Cache Abstraction • Cache Abstraction (SpringSource team blog) Bean Definition Profiles • XML profiles (SpringSource Team Blog) • Introducing @Profile (SpringSource Team Blog) • See org. 3.context.env.1 Overview of new features This is a list of new features for Spring 3.annotation.Environment Javadoc • See org.springframework.springframework.context.Spring Framework 3.annotation. Most features do not yet have dedicated reference documentation but do have Javadoc.core.PropertySource Javadoc • See org.0.1 Building on the support introduced in Spring 3.annotation.springframework. and at the time of this writing Spring 3.core.PropertySource Javadoc 3. In such cases.1 is currently under development.Profile Javadoc Environment Abstraction • Environment Abstraction (SpringSource Team Blog) • See org.env.core.springframework.springframework. Spring 3.1 Reference Documentation 26 .Configuration Javadoc • See org. New Features and Enhancements in Spring 3.env. fully-qualified class names are given.1.springframework.context.

1 M2: Testing with @Configuration Classes and Profiles (SpringSource Team Blog) • See the section called “Spring TestContext Framework” • See the section called “Context configuration with @Configuration classes” org.orm.annotation.context.context.EnableScheduling Javadoc • See org.EnableWebMvc Javadoc • See org. most in the form of @Enable annotations.springframework.springframework.springframework.context.annotation.annotation.springframework.cache. which were introduced in Spring 3. • See org.EnableAspectJAutoProxy Javadoc • See org.ComponentScan Javadoc • See org.context.EnableTransactionManagement Javadoc • See org. a new @ActiveProfiles annotation has been introduced to support declarative configuration of active bean definition profiles in ApplicationContext integration tests.web.springframework.transaction.test.EnableCaching Javadoc • See org.springframework.ContextConfiguration Javadoc and 3.EnableLoadTimeWeaving Javadoc • See org. • Spring 3.factory.hibernate4 package TestContext framework support for @Configuration classes and bean definition profiles The @ContextConfiguration annotation now supports supplying @Configuration classes for configuring the Spring TestContext.0.scheduling.annotation.config.scheduling.springframework.EnableSpringConfigured Javadoc Support for Hibernate 4. These are designed for use in conjunction with Spring's @Configuration classes.springframework. <tx:annotation-driven/> and <mvc:annotation-driven> have been developed.Configuration Javadoc • See org.context.EnableAsync Javadoc • See org. In addition.annotation.Spring Framework Code equivalents for Spring's XML namespaces Code-based equivalents to popular Spring XML namespace elements <context:component-scan/>.springframework.springframework.annotation.aspectj.servlet.springframework.beans.annotation.springframework.annotation.annotation.x • See Javadoc for classes within the new org.1 Reference Documentation 27 .

test. Support for Servlet 3 code-based configuration of Servlet Container The new WebApplicationInitializer builds atop Servlet 3.context.SmartContextLoader Javadoc • See org.AnnotationConfigContextLoader Javadoc c: namespace for more concise constructor injection • the section called “XML shortcut with the c-namespace” Support for injection against non-standard JavaBeans setters Prior to Spring 3.xml to WebApplicationInitializer Support for Servlet 3 MultipartResolver • See org.support.Spring Framework • See org.xml files in specific jar files which will in turn get searched for @Entity classes.springframework.xml 3.xml.1 Reference Documentation 28 .test.context.web.support. This is useful when considering designing APIs for method-chaining. namely that any 'setter' method must be void-returning. • See org.springframework.1. persistence.xml In standard JPA.support.springframework.test.springframework.test.0's ServletContainerInitializer support to provide a programmatic alternative to the traditional web.context. In many cases. where setter methods return a reference to 'this'.ActiveProfiles Javadoc • See org.WebApplicationInitializer Javadoc • Diff from Spring's Greenhouse reference application demonstrating migration from web.springframework.multipart. It is now possible in Spring XML to specify setter methods that return any object type. persistence units get defined through META-INF/persistence.context.DelegatingSmartContextLoader Javadoc • See org. in order to inject against a property method it had to conform strictly to JavaBeans property signature rules.StandardServletMultipartResolver Javadoc JPA EntityManagerFactory bootstrapping without persistence.springframework.web.

this allows for XML-free JPA setup at the mere expense of specifying a base package for entity scanning: a particularly fine match for Spring applications which rely on component scanning for Spring beans as well. For that reason. For example a HandlerInterceptor can cast the handler from Object to HandlerMethod and get access to the target controller method. with the new support classes you can customize the processing for any supported method argument or return value type.HandlerMethodArgumentResolver Javadoc • See org.springframework. The existing classes will continue to be available but use of the new classes is recommended going forward.1 provides an alternative: LocalContainerEntityManagerFactoryBean accepts a 'packagesToScan' property.1 Reference Documentation 29 . 3. Spring 3.method. Whereas previously you could configure a custom annotated controller method argument resolver. The new classes are enabled by default by the MVC namespace and by Java-based configuration via @EnableWebMvc.support.HandlerMethodReturnValueHandler Javadoc A second notable difference is the introduction of a HandlerMethod abstraction to represent an @RequestMapping method.web.1 introduces a new set of support classes for processing requests with annotated controllers: • 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 controller support classes more customizable and open for extension. its annotations. This abstraction is used throughout by the new support classes as the handler instance. This is analogous to AnnotationSessionFactoryBean's property of the same name for native Hibernate setup. etc). New HandlerMethod-based Support Classes For Annotated Controller Processing Spring 3. and also to Spring's component-scan feature for regular Spring beans. • See org.springframework.support.0 initializer. Effectively. specifying base packages to scan for @Entity classes.web.method. etc.Spring Framework does not contain more than a unit name and relies on defaults and/or external setup for all other concerns (such as the DataSource to use. possibly even bootstrapped using a code-based Servlet 3.

See the section called “Specifying redirect and flash attributes” for more details. @Valid On @RequestBody Controller Method Arguments An @RequestBody method argument can be annotated with @Valid to invoke automatic validation similar to the support for @ModelAttribute method arguments. • An @ModelAttribute method argument can be instantiated from a URI template variable provided there is a registered Converter or PropertyEditor to convert from a String to the target object type. an @RequestMapping method can add flash attributes by declaring a method argument of type RedirectAttributes.6.1 Reference Documentation 30 . • @PathVariable method argument values are merged into the model before rendering. 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 request to @ModelAttribute method arguments. In annotated controllers. “Using flash attributes”. "redirect:/blog/{year}/{month}").Spring Framework See the section called “New Support Classes for @RequestMapping methods in Spring MVC 3.g. For an overview of the general support for flash attributes in Spring MVC see Section 16. This method argument can now also be used to get precise control over the attributes used in a redirect scenario. • A redirect string can contain placeholders for URI variables (e. 3. A resulting MethodArgumentNotValidException is handled in the DefaultHandlerExceptionResolver and results in a 400 response code. except in views that generate content in an automated fashion such as JSON serialization or XML marshalling. "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. See the section called “Consumable Media Types” and the section called “Producible Media Types” Flash Attributes and RedirectAttributes Flash attributes can now be stored in a FlashMap and saved in the HTTP session to survive a redirect. URI template variables from the current request are automatically considered. When expanding the placeholders.1” for additional details and a list of features not available with the new support classes.

In most cases the new classes can be used as a more flexible alternative to the existing UriTemplate especially since UriTemplate relies on those same classes internally. 3. See Section 16. Together the two classes give fine-grained control over all aspects of preparing a URI including construction. “Building URIs”.10. expansion from URI template variables. UriComponentsBuilder and UriComponents A new UriComponents class has been added.1 Reference Documentation 31 .Spring Framework @RequestPart Annotation On Controller Method Arguments This new annotation provides access to the content of a "multipart/form-data" request part. “Spring's multipart (file upload) support”. A ServletUriComponentsBuilder sub-class provides static factory methods to copy information from a Servlet request. and encoding. A nenw UriComponentsBuilder class is also provided to help create UriComponents instances. which is an immutable container of URI components providing access to all contained URI components.7. See the section called “Handling a file upload request from programmatic clients” and Section 16.

which is conceptually easy to understand.. Data Binding. and which successfully addresses the 80% sweet spot of AOP requirements in Java enterprise programming. • Chapter 4. Resources • Chapter 6. Aspect Oriented Programming with Spring • Chapter 9. the chapter dedicated solely to testing will hopefully convince you of this as well. Spring AOP APIs • Chapter 10. Core Technologies This part of the reference documentation covers all of those technologies that are absolutely integral to the Spring Framework. Spring Expression Language (SpEL) • Chapter 8.in terms of features . Testing .and certainly most mature AOP implementation in the Java enterprise space) is also provided. 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). and Type Conversion • Chapter 7. Finally. The Spring Framework has its own AOP framework.. The IoC container • Chapter 5. A thorough treatment of the Spring Framework's IoC container is closely followed by comprehensive coverage of Spring's Aspect-Oriented Programming (AOP) technologies. and so coverage of Spring's support for integration testing is covered (alongside best practices for unit testing). Foremost amongst these is the Spring Framework's Inversion of Control (IoC) container.Part III. Coverage of Spring's integration with AspectJ (currently the richest . Validation. the adoption of the test-driven-development (TDD) approach to software development is certainly advocated by the Spring team.

and the dependencies among them. or properties that are set on the object instance after it is constructed or returned from a factory method.springframework. that is. a bean is simply one of many objects in your application. In short.Spring Framework 4. It is a process whereby objects define their dependencies. For more information on using the BeanFactory instead of the ApplicationContext. In Spring. and is used exclusively in this chapter in descriptions of Spring's IoC container.2 Container overview The interface org. The org. the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans.1 Reference Documentation 33 . ApplicationContext is a sub-interface of BeanFactory. The container then injects those dependencies when it creates the bean. The container gets its instructions on what objects to instantiate. the BeanFactory provides the configuration framework and basic functionality. event publication. arguments to a factory method. assembled. “The BeanFactory”. configuring. hence the name Inversion of Control (IoC).springframework.springframework.ApplicationContext represents the Spring IoC container and is responsible for instantiating. It adds easier integration with Spring's AOP features. The IoC container 4. This process is fundamentally the inverse. and otherwise managed by a Spring IoC container.1 Introduction to the Spring IoC container and beans This chapter covers the Spring Framework implementation of the Inversion of Control (IoC) 1principle. It allows you to express the objects that compose your application and the rich interdependencies 1 See Background 3. configure. Java annotations. only through constructor arguments.15. and the ApplicationContext adds more enterprise-specific functionality. The ApplicationContext is a complete superset of the BeanFactory. The configuration metadata is represented in XML. and assemble by reading configuration metadata. are reflected in the configuration metadata used by a container. or Java code. IoC is also known as dependency injection (DI). 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 other objects they work with. refer to Section 4. Beans. message resource handling (for use in internationalization).context packages are the basis for Spring Framework's IoC container. Otherwise.context.beans and org. 4. and application-layer specific contexts such as the WebApplicationContext for use in web applications. A bean is an object that is instantiated. and assembling the aforementioned beans. The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object.

In standalone applications it is common to create an instance of ClassPathXmlApplicationContext or FileSystemXmlApplicationContext. Your application classes are combined with configuration metadata so that after the ApplicationContext is created and initialized. you have a fully configured and executable system or application.xml file of the application will typically suffice (see the section called “Convenient ApplicationContext instantiation for web applications”). The Spring IoC container Configuration metadata As the preceding diagram shows. For example. In most application scenarios. 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 a small amount of XML configuration to declaratively enable support for these additional metadata formats. a simple eight (or so) lines of boilerplate J2EE web descriptor XML in the web. explicit user code is not required to instantiate one or more instances of a Spring IoC container.Spring Framework between such objects. 3. the Spring IoC container consumes a form of configuration metadata. The following diagram is a high-level view of how Spring works.1 Reference Documentation 34 . Several implementations of the ApplicationContext interface are supplied out-of-the-box with Spring. in a web application scenario. If you are using the SpringSource Tool Suite Eclipse-powered development environment or Spring Roo this boilerplate configuration can be easily created with few mouse clicks or keystrokes.

0. Typically you define service layer objects.. Typically one does not configure fine-grained domain objects in the container. See Using AspectJ to dependency-inject domain objects with Spring. see the @Configuration. Spring configuration consists of at least one and typically more than one bean definition that the container must manage. However.5 introduced support for annotation-based configuration metadata.. presentation objects such as Struts Action instances. • Java-based configuration: Starting with Spring 3. you can use Spring's integration with AspectJ to configure objects that have been created outside the control of an IoC container.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www. infrastructure objects such as Hibernate SessionFactories. data access objects (DAOs). The following example shows the basic structure of XML-based configuration metadata: <?xml version="1..springframework. XML-based configuration metadata shows these beans configured as <bean/> elements inside a top-level <beans/> element. The Spring IoC container itself is totally decoupled from the format in which this configuration metadata is actually written.Spring Framework this configuration metadata represents how you as an application developer tell the Spring container to instantiate." class=". Configuration metadata is traditionally supplied in a simple and intuitive XML format. @Bean.0" encoding="UTF-8"?> <beans xmlns="http://www. and assemble the objects in your application.springframework. These bean definitions correspond to the actual objects that make up your application. For information about using other forms of metadata with the Spring container.org/schema/beans/spring-beans-3. see: • Annotation-based configuration: Spring 2.w3. JMS Queues.xsd"> <bean id="."> <!-.org/schema/beans http://www.. because it is usually the responsibility of DAOs and business logic to create and load domain objects. many features provided by the Spring JavaConfig project became part of the core Spring Framework..collaborators and configuration for this bean go here --> </bean> <bean id=". Thus you can define beans external to your application classes by using Java rather than XML files."> <!-. configure.0." class=". and so forth.org/schema/beans" xmlns:xsi="http://www. Note XML-based metadata is not the only allowed form of configuration metadata. To use these new features.1 Reference Documentation 35 .. @Import and @DependsOn annotations...springframework.more bean definitions go here --> 3. which is what most of this chapter uses to convey key concepts and features of the Spring IoC container.collaborators and configuration for this bean go here --> </bean> <!-.

services.1 Reference Documentation 36 . and so on.more bean definitions for services go here --> </beans> The following example shows the data access objects daos.springframework.xml) configuration file: <?xml version="1. Note After you learn about Spring's IoC container.org/schema/beans" xmlns:xsi="http://www.springframework.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www. In particular.springframework.w3.xsd"> <!-.org/schema/beans http://www.7.additional collaborators and configuration for this bean go here --> </bean> <!-.springframework. The XML for referring to collaborating objects is not shown in this example.jpetstore.org/schema/beans/spring-beans-3.0" encoding="UTF-8"?> <beans xmlns="http://www. you may want to know more about Spring's Resource abstraction. Resource paths are used to construct applications contexts as described in Section 5. "daos.xsd"> 3.0" encoding="UTF-8"?> <beans xmlns="http://www. Instantiating a container Instantiating a Spring IoC container is straightforward.xml".PetStoreServiceImpl"> <property name="accountDao" ref="accountDao"/> <property name="itemDao" ref="itemDao"/> <!-.services --> <bean id="petStore" class="org. which provides a convenient mechanism for reading an InputSream from locations defined in a URI syntax. see Dependencies for more information. 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.org/schema/beans/spring-beans-3. “Application contexts and Resource paths”. The following example shows the service layer objects (services. The class attribute defines the type of the bean and uses the fully qualified classname. Resources. as described in Chapter 5.xml"}).org/schema/beans" xmlns:xsi="http://www. The value of the id attribute refers to collaborating objects.springframework.springframework. from the Java CLASSPATH.springframework.0.0.org/schema/beans http://www.w3.Spring Framework </beans> The id attribute is a string that you use to identify the individual bean definition. ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.samples.xml file: <?xml version="1.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.

xml. Composing XML-based configuration metadata It can be useful to have bean definitions span multiple XML files. but given that these paths are relative.1 Reference Documentation 37 . and themeSource.springframework. For details of configuring an object's dependencies.ibatis. You can use the application context constructor to load bean definitions from all these XML fragments.samples.additional collaborators and configuration for this bean go here --> </bean> <!-... Note 3.samples. so services.dao..SqlMapItemDao"> <!-.xml"/> <import resource="/resources/themeSource.ibatis.jpetstore. must be valid XML bean definitions according to the Spring Schema or DTD. while messageSource.xml.dao. messageSource.Spring Framework <bean id="accountDao" class="org. For example: <beans> <import resource="services. use one or more occurrences of the <import/> element to load bean definitions from another file or files. and the ref element refers to the name of another bean definition..xml must be in the same directory or classpath location as the file doing the importing. see Dependencies. As you can see.xml must be in a resources location below the location of the importing file. as was shown in the previous section. Often each individual XML configuration file represents a logical layer or module in your architecture. the service layer consists of the class PetStoreServiceImpl. including the top level <beans/> element. This constructor takes multiple Resource locations. All location paths are relative to the definition file doing the importing."/> <bean id="bean2" class=".SqlMapAccountDao"> <!-. Alternatively.xml."/> </beans> In the preceding example. The contents of the files being imported.more bean definitions for data access objects go here --> </beans> In the preceding example. a leading slash is ignored.xml and themeSource.jpetstore.xml"/> <bean id="bean1" class=". services. external bean definitions are loaded from three files. it is better form not to use the slash at all.additional collaborators and configuration for this bean go here --> </bean> <bean id="itemDao" class="org.springframework. This linkage between id and ref elements expresses the dependency between collaborating objects.xml"/> <import resource="resources/messageSource. The property name element refers to the name of the JavaBean property. and two data access objects of the type SqlMapAccountDao and SqlMapItemDao are based on the iBatis Object/Relational mapping framework.

}" placeholders that are resolved against JVM system properties at runtime. where the runtime resolution process chooses the "nearest" classpath root and then looks into its parent directory.xml"). "daos.class). incorrect directory.xml". Doing so creates a dependency on a file that is outside the current application.xml". The ApplicationContext interface has a few other methods for retrieving beans. You can always use fully qualified resource locations instead of relative paths: for example. The ApplicationContext enables you to read bean definitions and access them as follows: // create and configure beans ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services. Using the method T getBean(Stringname. this reference is not recommended for "classpath:" URLs (for example. Using the container The ApplicationContext is the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies.getBean("petStore".getUsernameList(). in the form of XML <bean/> definitions. Class<T> requiredType) you can retrieve instances of your beans./" path. these bean definitions are represented as BeanDefinition objects./services. For example. // use configured instance List userList service. "classpath:. and thus no dependency on Spring APIs at all. be aware that you are coupling your application's configuration to specific absolute locations. but ideally your application code should never use them. In particular. 4.. to reference files in parent directories using a relative ".1 Reference Documentation 38 .xml" or "classpath:/config/services. for example. but not recommended.. It is generally preferable to keep an indirection for such absolute locations. However. for example.Spring Framework It is possible. Indeed. through "${.. Spring's integration with web frameworks provides for dependency injection for various web framework classes such as controllers and JSF-managed beans. Classpath configuration changes may lead to the choice of a different.3 Bean overview A Spring IoC container manages one or more beans.. These beans are created with the configuration metadata that you supply to the container. "file:C:/config/services.xml"}). your application code should have no calls to the getBean() method at all. which contain (among other information) the following metadata: 3. // retrieve configured instance PetStoreServiceImpl service = context. You use getBean() to retrieve instances of your beans. PetStoreServiceImpl. Within the container itself.

. 3. DefaultListableBeanFactory supports this registration through the methods registerSingleton(. This metadata translates to a set of properties that make up each bean definition.5.) and registerBeanDefinition(. • Other configuration settings to set in the newly created object. lifecycle callbacks. “Bean scopes” constructor arguments the section called “Dependency injection” properties the section called “Dependency injection” autowiring mode the section called “Autowiring collaborators” lazy-initialization mode the section called “Lazy-initialized beans” initialization method the section called “Initialization callbacks” destruction method the section called “Destruction callbacks” Explained in. • References to other beans that are needed for the bean to do its work. the number of connections to use in a bean that manages a connection pool.. or the size limit of the pool.. Table 4.). However. • Bean behavioral configuration elements. these references are also called collaborators or dependencies. In addition to bean definitions that contain information on how to create a specific bean. which state how the bean should behave in the container (scope.1 Reference Documentation 39 . typical applications work solely with beans defined through metadata bean definitions. for example.Spring Framework • A package-qualified class name: typically the actual implementation class of the bean being defined. by users. the ApplicationContext implementations also permit the registration of existing objects that are created outside the container. This is done by accessing the ApplicationContext's BeanFactory via the method getBeanFactory() which returns the BeanFactory implementation DefaultListableBeanFactory. and so forth).1.. The bean definition Property class the section called “Instantiating beans” name the section called “Naming beans” scope Section 4.

These names can be equivalent aliases to the same bean. As of 3. 'fooService'. though no longer by XML parsers. If no name or id is supplied explicitly.). If you want to introduce other aliases to the bean. However.). but if it requires more than one. 'accountService'.Spring Framework Naming beans Every bean has one or more identifiers. each subsystem having its own set of object definitions. This is commonly the case in large systems where configuration is split amongst each subsystem.1 Reference Documentation 40 . Aliasing a bean outside the bean definition In a bean definition itself. through the use of the ref element or Service Locator style lookup. That is. however. Bean naming conventions The convention is to use the standard Java convention for instance field names when naming beans. and are useful for some situations. Specifying all aliases where the bean is actually defined is not always adequate. etc).1. which constrained possible characters. but may special characters as well. you must provide a name. you use the id and/or name attributes to specify the bean identifier(s). you can supply more than one name for the bean. A bean usually has only one identifier. by using a combination of up to one name specified by the id attribute. you can use the <alias/> element to accomplish this. Note that bean id uniqueness is still enforced by the container. Naming beans consistently makes your configuration easier to read and understand. the extra ones can be considered aliases. 'loginController'. it is now xsd:string. As a historical note. You are not required to supply a name or id for a bean. such as allowing each component in an application to refer to a common dependency by using a bean name that is specific to that component itself. In XML-based configuration metadata. It is sometimes desirable to introduce an alias for a bean that is defined elsewhere. the id attribute was typed as an xsd:ID. <alias name="fromName" alias="toName"/> 3. if you want to refer to that bean by name. semicolon (. or white space. In XML-based configuration metadata. Conventionally these names are alphanumeric ('myBean'. and if you are using Spring AOP it helps a lot when applying advice to a set of beans related by name. and any number of other names in the name attribute. and are camel-cased from then on. 'userDao'. bean names start with a lowercase letter. the container generates a unique name for that bean. and so forth. These identifiers must be unique within the container that hosts the bean. The id attribute allows you to specify exactly one id. in versions prior to Spring 3. separated by a comma (. Motivations for not supplying a name are related to using inner beans and autowiring collaborators.1. Examples of such names would be (without quotes) 'accountManager'. you can also specify them in the name attribute.

If you use XML-based configuration metadata. you specify the type (or class) of object that is to be instantiated in the class attribute of the <bean/> element. The object type returned from the invocation of the static factory method may be the same class or another class entirely. When composing the main application that uses both these subsystems the main application refers to the DataSource via the name 'myApp-dataSource'. somewhat equivalent to Java code using the new operator. yet they refer to the same bean. the configuration metadata for subsystem A may refer to a DataSource via the name 'subsystemA-dataSource. to specify the bean class to be constructed in the case where the container itself directly creates the bean by calling its constructor reflectively. be referred to as toName. in the less common case where the container invokes a static.. a bean in the same container which is named fromName. For example. Instantiating beans A bean definition essentially is a recipe for creating one or more objects.Spring Framework In this case. Inner class names If you want to configure a bean definition for a static nested class.) You use the Class property in one of two ways: • Typically.7. and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object. (For exceptions. see the section called “Instantiation using an instance factory method” and Section 4. • To specify the actual class containing the static factory method that will be invoked to create the object.. may also after the use of this alias definition.1 Reference Documentation 41 . factory method on a class to create the bean. This class attribute. The container looks at the recipe for a named bean when asked. the value of the 'class' attribute on a bean definition would be. if you have a class called Foo in the com.example package. To have all three names refer to the same object you add to the MyApp configuration metadata the following aliases definitions: <alias name="subsystemA-dataSource" alias="subsystemB-dataSource"/> <alias name="subsystemA-dataSource" alias="myApp-dataSource" /> Now each component and the main application can refer to the dataSource through a name that is unique and guaranteed not to clash with any other definition (effectively creating a namespace). you have to use the binary name of the inner class. 3. which internally is a Class property on a BeanDefinition instance. The configuration metadata for subsystem B may refer to a DataSource via the name 'subsystemB-dataSource'. “Bean definition inheritance”. For example. is usually mandatory. and this Foo class has a static inner class called Bar.

it is not limited to managing true JavaBeans.1 Reference Documentation 42 . If. In this example. However.ExampleBean"/> <bean name="anotherExample" class="examples. see Injecting Dependencies. all normal classes are usable by and compatible with Spring. With XML-based configuration metadata you can specify your bean class as follows: <bean id="exampleBean" class="examples. The following bean definition specifies that the bean will be created by calling a factory-method. you use the class attribute to specify the class containing the static factory method and an attribute named factory-method to specify the name of the factory method itself.ExampleBeanTwo"/> For details about the mechanism for supplying arguments to the constructor (if required) and setting object instance properties after the object is constructed. Spring can manage it as well. for example. Most Spring users prefer actual JavaBeans with only a default (no-argument) constructor and appropriate setters and getters modeled after the properties in the container. You should be able to call this method (with optional arguments as described later) and return a live object. The Spring IoC container can manage virtually any class you want it to manage. private ClientService() {} 3. you need to use a legacy connection pool that absolutely does not adhere to the JavaBean specification. One use for such a bean definition is to call static factories in legacy code. which subsequently is treated as if it had been created through a constructor. only the class containing the factory method.example. You can also have more exotic non-bean-style classes in your container. Instantiation with a static factory method When defining a bean that you create with a static factory method.Foo$Bar Notice the use of the $ character in the name to separate the inner class name from the outer class name. depending on what type of IoC you use for that specific bean.Spring Framework com. the createInstance() method must be a static method. Simply specifying the bean class should suffice. you may need a default (empty) constructor. <bean id="clientService" class="examples. the class being developed does not need to implement any specific interfaces or to be coded in a specific fashion. The definition does not specify the type (class) of the returned object. That is.ClientService" factory-method="createInstance"/> public class ClientService { private static ClientService clientService = new ClientService(). Instantiation with a constructor When you create a bean by the constructor approach.

which contains a method called createInstance() --> <bean id="serviceLocator" class="examples. <!-. instantiation with an instance factory method invokes a non-static method of an existing bean from the container to create a new bean. see Dependencies and configuration in detail.the factory bean. specify the name of a bean in the current (or parent/ancestor) container that contains the instance method that is to be invoked to create the object. To use this mechanism. } } For details about the mechanism for supplying (optional) arguments to the factory method and setting object instance properties after the object is returned from the factory. and in the factory-bean attribute.1 Reference Documentation 43 .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().DefaultServiceLocator"> <!-.DefaultServiceLocator"> <!-. leave the class attribute empty.inject any dependencies required by this locator bean --> </bean> <!-. Instantiation using an instance factory method Similar to instantiation through a static factory method.Spring Framework public static ClientService createInstance() { return clientService. private static AccountService accountService = new AccountServiceImpl(). Set the name of the factory method itself with the factory-method attribute. private DefaultServiceLocator() {} public ClientService createClientServiceInstance() { return clientService. private DefaultServiceLocator() {} public ClientService createClientServiceInstance() { 3.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(). } } One factory class can also hold more than one factory method as shown here: <bean id="serviceLocator" class="examples.

factory bean refers to a bean that is configured in the Spring container that will create objects through an instance or static factory method. This process is fundamentally the inverse.Spring Framework return clientService. or the Service Locator pattern. By contrast. which allow for stub or mock implementations to be used in unit tests. hence the name Inversion of Control (IoC). of the bean itself controlling the instantiation or location of its dependencies on its own by using direct construction of classes. Even the simplest application has a few objects that work together to present what the end-user sees as a coherent application. and does not know the location or class of the dependencies. Code is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies. arguments to a factory method.4 Dependencies A typical enterprise application does not consist of a single object (or bean in the Spring parlance). 4. in particular when the dependencies are on interfaces or abstract base classes. FactoryBean (notice the capitalization) refers to a Spring-specific FactoryBean . your classes become easier to test. the other objects they work with. Constructor-based dependency injection Constructor-based DI is accomplished by the container invoking a constructor with a number of 3. The container then injects those dependencies when it creates the bean. or properties that are set on the object instance after it is constructed or returned from a factory method. The object does not look up its dependencies. See Dependencies and configuration in detail. DI exists in two major variants.1 Reference Documentation 44 . This next section explains how you go from defining a number of bean definitions that stand alone to a fully realized application where objects collaborate to achieve a goal. only through constructor arguments. As such. Dependency injection Dependency injection (DI) is a process whereby objects define their dependencies. that is. } } This approach shows that the factory bean itself can be managed and configured through dependency injection (DI). Note In Spring documentation. } public AccountService createAccountServiceInstance() { return accountService. Constructor-based dependency injection and Setter-based dependency injection.

} // business logic that actually 'uses' the injected MovieFinder is omitted... each representing a dependency. Calling a static factory method with specific arguments to construct the bean is nearly equivalent. When a simple type is used.1 Reference Documentation 45 . base classes or annotations.Spring Framework arguments.. The following example shows a class that can only be dependency-injected with constructor injection. the type is known.Bar"/> <bean id="baz" class="x. such as <value>true<value>.. public class ExampleBean { 3. Notice that there is nothing special about this class. Spring cannot determine the type of the value. } Constructor argument resolution Constructor argument resolution matching occurs using the argument's type. Consider the following class: package x. If no potential ambiguity exists in the constructor arguments of a bean definition. assuming that Bar and Baz classes are not related by inheritance. Consider the following class: package examples. and matching can occur (as was the case with the preceding example). Thus the following configuration works fine.Baz"/> </beans> When another bean is referenced. // a constructor so that the Spring container can 'inject' a MovieFinder public SimpleMovieLister(MovieFinder movieFinder) { this. } } No potential ambiguity exists.y.y. and you do not need to specify the constructor argument indexes and/or types explicitly in the <constructor-arg/> element. public class SimpleMovieLister { // the SimpleMovieLister has a dependency on a MovieFinder private MovieFinder movieFinder. public class Foo { public Foo(Bar bar. <beans> <bean id="foo" class="x.Foo"> <constructor-arg ref="bar"/> <constructor-arg ref="baz"/> </bean> <bean id="bar" class="x.y. and so cannot match by type without help.movieFinder = movieFinder. then the order in which the constructor arguments are defined in a bean definition is the order in which those arguments are supplied to the appropriate constructor when the bean is being instantiated.y. and this discussion treats arguments to a constructor and to a static factory method similarly. Baz baz) { // . it is a POJO that has no dependencies on container specific interfaces.

ultimateAnswer = ultimateAnswer.years = years. "ultimateAnswer"}) public ExampleBean(int years.lang. specifying an index resolves ambiguity where a constructor has two arguments of the same type. } } Constructor argument type matching In the preceding scenario. Note that the index is 0 based. If you can't compile your code with debug flag (or don't want to) you can use @ConstructorProperties JDK annotation to explicitly name your constructor arguments.ExampleBean"> <constructor-arg index="0" value="7500000"/> <constructor-arg index="1" value="42"/> </bean> In addition to resolving the ambiguity of multiple simple values. Constructor argument name As of Spring 3.Spring Framework // No. The sample class would then have to look as follows: package examples.ExampleBean"> <constructor-arg type="int" value="7500000"/> <constructor-arg type="java. the container can use type matching with simple types if you explicitly specify the type of the constructor argument using the type attribute. and Everything private String ultimateAnswer. the Universe.0 you can also use the constructor parameter name for value disambiguation: <bean id="exampleBean" class="examples. For example: <bean id="exampleBean" class="examples. // The Answer to Life. String ultimateAnswer) { 3. public class ExampleBean { // Fields omitted @ConstructorProperties({"years".ExampleBean"> <constructor-arg name="years" value="7500000"/> <constructor-arg name="ultimateanswer" value="42"/> </bean> Keep in mind that to make this work out of the box your code must be compiled with the debug flag enabled so that Spring can look up the parameter name from the constructor. For example: <bean id="exampleBean" class="examples.String" value="42"/> </bean> Constructor argument index Use the index attribute to specify explicitly the index of constructor arguments.1 Reference Documentation 46 . String ultimateAnswer) { this. public ExampleBean(int years. of years to the calculate the Ultimate Answer private int years. this.

1 Reference Documentation 47 . most Spring users do not work with these classes directly (programmatically). Management through JMX MBeans is a compelling use case. and used to load an entire Spring IoC container instance. The Spring team generally advocates setter injection. It is a POJO that has no dependencies on container specific interfaces. You configure the dependencies in the form of a BeanDefinition.. especially when properties are optional. // a setter method so that the Spring container can 'inject' a MovieFinder public void setMovieFinder(MovieFinder movieFinder) { this. However. because large numbers of constructor arguments can get unwieldy. base classes or annotations. Constructor-based or setter-based DI? Since you can mix both.and Setter-based DI.years = years. The following example shows a class that can only be dependency-injected using pure setter injection.and setter-based DI for the beans it manages.Spring Framework this.ultimateAnswer = ultimateAnswer. public class SimpleMovieLister { // the SimpleMovieLister has a dependency on the MovieFinder private MovieFinder movieFinder. Setter methods also make objects of that class amenable to reconfiguration or re-injection later. } } Setter-based dependency injection Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. Some purists favor constructor-based injection.movieFinder = movieFinder. 3. This class is conventional Java. Constructor. which you use with PropertyEditor instances to convert properties from one format to another. this. Note that the use of a @Required annotation on a setter can be used to make setters required dependencies.. but rather with an XML definition file that is then converted internally into instances of these classes. it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. } // business logic that actually 'uses' the injected MovieFinder is omitted. The disadvantage is that the object becomes less amenable to reconfiguration and re-injection. Supplying all object dependencies means that the object is always returned to client (calling) code in a totally initialized state. It also supports setter-based DI after some dependencies are already injected through the constructor approach. } The ApplicationContext supports constructor.

For each bean. However. One possible solution is to edit the source code of some classes to be configured by setters rather than constructors. as the bean's dependencies and its dependencies' dependencies (and so on) are created and assigned. its dependencies are expressed in the form of properties. avoid constructor injection and use setter injection only. Configuration metadata can be specified via XML. Alternatively. it is possible to create an unresolvable circular dependency scenario. including the validation of whether bean reference properties refer to valid beans.5. when dealing with third-party classes to which you do not have the source. 4. Circular dependencies If you use predominantly constructor injection. In other words. Beans that are singleton-scoped and set to be pre-instantiated (the default) are created when the container is created. String. These dependencies are provided to the bean. and throws a BeanCurrentlyInCreationException. Creation of a bean potentially causes a graph of beans to be created. the choice is made for you. the bean is created only when it is requested. the Spring IoC container detects this circular reference at runtime. The ApplicationContext is created and initialized with configuration metadata that describes all the beans. 3. boolean. etc. and class B requires an instance of class A through constructor injection. you can configure circular dependencies with setter 3. long. and so constructor injection is the only available DI. constructor arguments. the bean properties themselves are not set until the bean is actually created. or arguments to the static-factory method if you are using that instead of a normal constructor. such as int. or a reference to another bean in the container. If you configure beans for classes A and B to be injected into each other. Dependency resolution process The container performs bean dependency resolution as follows: 1. Each property or constructor argument which is a value is converted from its specified format to the actual type of that property or constructor argument. By default Spring can convert a value supplied in string format to all built-in types. Sometimes. 2. For example: Class A requires an instance of class B through constructor injection. “Bean scopes” Otherwise. when the bean is actually created. A legacy class may not expose any setter methods. Java code or annotations. although it is not recommended. Each property or constructor argument is an actual definition of the value to set.Spring Framework Use the DI that makes the most sense for a particular class.1 Reference Documentation 48 . Scopes are defined in Section 4. The Spring container validates the configuration of each bean as the container is created.

You can still override this default behavior so that singleton beans will lazy-initialize. not later.beanOne = beanOne. Examples of dependency injection The following example uses XML-based configuration metadata for setter-based DI.ExampleBean"> <!-. rather than be pre-instantiated. its dependencies are set. At the cost of some upfront time and memory to create these beans before they are actually needed.Spring Framework injection.setter injection using the neater 'ref' attribute --> <property name="beanTwo" ref="yetAnotherBean"/> <property name="integerProperty" value="1"/> </bean> <bean id="anotherExampleBean" class="examples. when the bean is actually created. You can generally trust Spring to do the right thing. If no circular dependencies exist. public void setBeanOne(AnotherBean beanOne) { this. Unlike the typical case (with no circular dependencies). at container load-time. For example. the Spring IoC container completely configures bean B prior to invoking the setter method on bean A.1 Reference Documentation 49 .setter injection using the nested <ref/> element --> <property name="beanOne"><ref bean="anotherExampleBean"/></property> <!-. each collaborating bean is totally configured prior to being injected into the dependent bean. and the relevant lifecycle methods (such as a configured init method or the InitializingBean callback method) are invoked. It detects configuration problems. Spring sets properties and resolves dependencies as late as possible. In other words.AnotherBean"/> <bean id="yetAnotherBean" class="examples. such as references to non-existent beans and circular dependencies. A small part of a Spring XML configuration file specifies some bean definitions: <bean id="exampleBean" class="examples. you discover configuration issues when the ApplicationContext is created. This means that a Spring container which has loaded correctly can later generate an exception when you request an object if there is a problem creating that object or one of its dependencies. private int i. 3. the bean throws an exception as a result of a missing or invalid property. private YetAnotherBean beanTwo. a circular dependency between bean A and bean B forces one of the beans to be injected into the other prior to being fully initialized itself (a classic chicken/egg scenario). This means that if bean A has a dependency on bean B. when one or more collaborating beans are being injected into a dependent bean.YetAnotherBean"/> public class ExampleBean { private AnotherBean beanOne. the bean is instantiated (if not a pre-instantiated singleton). This potentially delayed visibility of some configuration issues is why ApplicationContext implementations by default pre-instantiate singleton beans.

where instead of using a constructor. YetAnotherBean yetAnotherBean. int i) { this. this.constructor injection using the nested <ref/> element --> <constructor-arg> <ref bean="anotherExampleBean"/> </constructor-arg> <!-. setters are declared to match against the properties specified in the XML file.i = i. Spring is told to call a static factory method to return an instance of the object: <bean id="exampleBean" class="examples.ExampleBean" factory-method="createInstance"> <constructor-arg ref="anotherExampleBean"/> <constructor-arg ref="yetAnotherBean"/> <constructor-arg value="1"/> </bean> <bean id="anotherExampleBean" class="examples. } } The constructor arguments specified in the bean definition will be used as arguments to the constructor of the ExampleBean.constructor injection using the neater 'ref' attribute --> <constructor-arg ref="yetAnotherBean"/> <constructor-arg type="int" value="1"/> </bean> <bean id="anotherExampleBean" class="examples. The following example uses constructor-based DI: <bean id="exampleBean" class="examples. public ExampleBean( AnotherBean anotherBean.Spring Framework } public void setBeanTwo(YetAnotherBean beanTwo) { this. private YetAnotherBean beanTwo. this. } public void setIntegerProperty(int i) { this.beanTwo = yetAnotherBean.i = i.AnotherBean"/> <bean id="yetAnotherBean" class="examples. Now consider a variant of this example.AnotherBean"/> <bean id="yetAnotherBean" class="examples.beanOne = anotherBean.beanTwo = beanTwo.1 Reference Documentation 50 . } } In the preceding example.YetAnotherBean"/> public class ExampleBean { private AnotherBean beanOne.ExampleBean"> <!-. private int i.YetAnotherBean"/> public class ExampleBean { 3.

you can define bean properties and constructor arguments as references to other managed beans (collaborators).1 Reference Documentation 51 . // regardless of how those arguments are actually used. int i) { ExampleBean eb = new ExampleBean (.dbcp. return eb.org/schema/beans http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.. Straight values (primitives. YetAnotherBean yetAnotherBean. An instance (non-static) factory method would be used in an essentially identical fashion (aside from the use of the factory-bean attribute instead of the class attribute). } // a static factory method.) { .BasicDataSource" destroy-method="close"> <!-..jdbc.springframework.commons.. so details will not be discussed here. although in this example it is.springframework..org/2001/XMLSchema-instance" xmlns:p="http://www. <beans xmlns="http://www.Spring Framework // a private constructor private ExampleBean(.org/schema/beans" xmlns:xsi="http://www. exactly the same as if a constructor had actually been used..).springframework. or as values defined inline. As mentioned previously. // some other operations. the arguments to this method can be // considered the dependencies of the bean that is returned. Strings.xsd"> 3. } } Arguments to the static factory method are supplied via <constructor-arg/> elements.org/schema/beans/spring-beans-3.. JavaBeans PropertyEditors are used to convert these string values from a String to the actual type of the property or argument. Dependencies and configuration in detail As mentioned in the previous section.results in a setDriverClassName(String) call --> <property name="driverClassName" value="com. <bean id="myDataSource" class="org. public static ExampleBean createInstance ( AnotherBean anotherBean. and so on) The value attribute of the <property/> element specifies a property or constructor argument as a human-readable string representation. The type of the class being returned by the factory method does not have to be of the same type as the class that contains the static factory method. Spring's XML-based configuration metadata supports sub-element types within its <property/> and <constructor-arg/> elements for this purpose.mysql.apache.w3.0.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...

mysql.. <bean id="theTargetBean" class=".commons."> <property name="targetName"> <idref bean="theTargetBean" /> </property> </bean> The above bean definition snippet is exactly equivalent (at runtime) to the following snippet: <bean id="theTargetBean" class=". because using the idref tag allows the container to validate at deployment time that the referenced.. In the second variation. no validation is 3.config..Driver" p:url="jdbc:mysql://localhost:3306/mydb" p:username="root" p:password="masterkaoli"/> </beans> The preceding XML is more succinct.url=jdbc:mysql://localhost:3306/mydb </value> </property> </bean> The Spring container converts the text inside the <value/> element into a java..PropertyPlaceholderConfigurer"> <!-. You can also configure a java.. Such IDE assistance is highly recommended. named bean actually exists. however..util.jdbc.className=com.jdbc.Properties instance as: <bean id="mappings" class="org. and is one of a few places where the Spring team do favor the use of the nested <value/> element over the value attribute style.util.util.mysql.factory." /> <bean id="client" class=".dbcp.typed as a java.BasicDataSource" destroy-method="close" p:driverClassName="com.1 Reference Documentation 52 ..springframework.apache.Spring Framework <bean id="myDataSource" class="org.beans.."> <property name="targetName" value="theTargetBean" /> </bean> The first form is preferable to the second.not a reference) of another bean in the container to a <constructor-arg/> or <property/> element. typos are discovered at runtime rather than design time.Driver jdbc. The idref element The idref element is simply an error-proof way to pass the id (string value .Properties --> <property name="properties"> <value> jdbc. 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. This is a nice shortcut.driver."/> <bean id="theClientBean" class=".Properties instance by using the JavaBeans PropertyEditor mechanism.

or as one of the values in the name attribute of the target bean. it may be initialized already by the container. Here you set the value of the specified property of a bean to be a reference to another bean (a collaborator) managed by the container. <ref bean="someBean"/> Specifying the target bean through the local attribute leverages the ability of the XML parser to validate XML id references within the same file.) All references are ultimately a reference to another object. Using <idref/> elements when you specify the interceptor names prevents you from misspelling an interceptor id. <ref local="someBean"/> Specifying the target bean through the parent attribute creates a reference to a bean that is in a parent container of the current container.local. Additionally. Scoping and validation depend on whether you specify the id/name of the other object through the bean. at XML document parse time. and it is initialized on demand as needed before the property is set.0) where the <idref/> element brings value is in the configuration of AOP interceptors in a ProxyFactoryBean bean definition. The value of the bean attribute may be the same as the id attribute of the target bean. and the bean name is the bean id. The value of the local attribute must be the same as the id attribute of the target bean. The XML parser issues an error if no matching element is found in the same file. regardless of whether it is in the same XML file. and allows creation of a reference to any bean in the same container or parent container. or one of the values in the name attribute of the target bean. The value of the parent attribute may be the same as either the id attribute of the target bean.1 Reference Documentation 53 . (If the collaborator is a singleton bean. this typo and the resulting exception may only be discovered long after the container is deployed. and the target bean must be in a parent container of the current one. <property name="targetName"> <!-.a bean with id 'theTargetBean' must exist. References to other beans (collaborators) The ref element is the final element inside a <constructor-arg/> or <property/> definition element. otherwise an exception will be thrown --> <idref local="theTargetBean"/> </property> A common place (at least in versions earlier than Spring 2. if the referenced bean is in the same XML unit. or parent attributes. Specifying the target bean through the bean attribute of the <ref/> tag is the most general form. which allows the XML parser itself to validate the bean id earlier. The referenced bean is a dependency of the bean whose property will be set. If the client bean is a prototype bean. As such. you can use the local attribute. using the local variant is the best choice (in order to know about errors as early as possible) if the target bean is in the same XML file. Typos are only discovered (with most likely fatal results) when the client bean is actually instantiated.Spring Framework performed on the value that is passed to the targetName property of the client bean. You use this bean reference variant mainly when you have a hierarchy of containers and you want to wrap an existing bean in a parent container with a 3.

It also ignores the scope flag. you set the properties and arguments of the Java Collection types List.example.foo.1 Reference Documentation 54 . <map/>. <bean id="moreComplexObject" class="example.framework.Person"> <!-.Map) call --> <property name="someMap"> <map> 3.org</prop> <prop key="development">development@example. Collections In the <list/>.. It is not possible to inject inner beans into collaborating beans other than into the enclosing bean. and Properties.notice how we refer to the parent bean --> </property> <!-.util.bean name is the same as the parent bean --> class="org.org</prop> <prop key="support">support@example. respectively. Inner beans are always anonymous and they are always scoped as prototypes. Set. and <props/> elements.ProxyFactoryBean"> <property name="target"> <ref parent="accountService"/> <!-.results in a setSomeMap(java. Map. <!-. simply define the target bean inline --> <property name="target"> <bean class="com.SimpleAccountService"> <!-..ComplexObject"> <!-.util."> <!-.aop.results in a setSomeList(java.in the parent context --> <bean id="accountService" class="com.results in a setAdminEmails(java.insert other configuration and dependencies as required here --> </bean> Inner beans A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean.insert dependencies as required as here --> </bean> <!-.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.Properties) call --> <property name="adminEmails"> <props> <prop key="administrator">administrator@example.org</prop> </props> </property> <!-.springframework.in the child (descendant) context --> <bean id="accountService" <-. the container ignores these values.instead of using a reference to a target bean. <set/>.Spring Framework proxy that will have the same name as the parent bean.List) call --> <property name="someList"> <list> <value>a list element followed by a reference</value> <ref bean="myDataSource" /> </list> </property> <!-. <bean id="outer" class=".util.

the container supports the merging of collections. This section on merging discusses the parent-child bean mechanism. That is.Set) call --> <property name="someSet"> <set> <value>just some string</value> <ref bean="myDataSource" /> </set> </property> </bean> The value of a map key or value.ComplexObject"> <property name="adminEmails"> <props> <prop key="administrator">administrator@example.com sales=sales@example.0.com</prop> </props> </property> </bean> <bean id="child" parent="parent"> <property name="adminEmails"> <!-. When the child bean is resolved and instantiated by the container.com</prop> <prop key="support">support@example. with the child's collection elements overriding values specified in the parent collection. The following example demonstrates collection merging: <beans> <bean id="parent" abstract="true" class="example. can also again be any of the following elements: bean | ref | idref | list | set | map | props | value | null Collection merging As of Spring 2.results in a setSomeSet(java. <map/>.co.Spring Framework <entry key="an entry" value="just some string"/> <entry key ="a ref" value-ref="myDataSource"/> </map> </property> <!-.com 3. administrator=administrator@example. and have child-style <list/>. <set/> or <props/> elements inherit and override values from the parent collection. or a set value.1 Reference Documentation 55 . <set/> or <props/> element. Readers unfamiliar with parent and child bean definitions may wish to read the relevant section before continuing.util. <map/>.the merge is specified on the *child* collection definition --> <props merge="true"> <prop key="sales">sales@example. An application developer can define a parent-style <list/>. the resulting instance has an adminEmails Properties collection that contains the result of the merging of the child's adminEmails collection with the parent's adminEmails collection. the child collection's values are the result of merging the elements of the parent and child collections.com</prop> <prop key="support">support@example.uk</prop> </props> </property> </bean> <beans> Notice the use of the merge=true attribute on the <props/> element of the adminEmails property of the child bean definition.

Float> is available by reflection. and Properties implementation types that the container uses internally. the generics information about the element type of the strongly-typed Map<String. no ordering exists. you can use strongly typed collections (using generic types). Set.uk The child Properties collection's value set inherits all property elements from the parent <props/>. This merging behavior applies similarly to the <list/>. If you are using Spring to dependency-inject a strongly-typed Collection into a bean.0 and later. that is.Spring Framework support=support@example. and Properties collection types. the semantics associated with the List collection type. Thus Spring's type conversion infrastructure recognizes the various value elements as being of type Float. and the 3. Float> accounts) { this.Foo"> <property name="accounts"> <map> <entry key="one" value="9. child definition. public class Foo { private Map<String. and if you do attempt to do so an appropriate Exception is thrown. the parent's values precede all of the child list's values. inherited. it is possible to declare a Collection type such that it can only contain String elements (for example). Strongly-typed collection (Java 5+ only) In Java 5 and later. Set.1 Reference Documentation 56 . That is. and the child's value for the support value overrides the value in the parent collection.99"/> </map> </property> </bean> </beans> When the accounts property of the foo bean is prepared for injection. The merge attribute must be specified on the lower. In the case of the Map.co. is maintained. Hence no ordering semantics are in effect for the collection types that underlie the associated Map.accounts = accounts. In the specific case of the <list/> element. Limitations of collection merging You cannot merge different collection types (such as a Map and a List). the notion of an ordered collection of values. and <set/> collection types. public void setAccounts(Map<String. Float> accounts. you can take advantage of Spring's type-conversion support such that the elements of your strongly-typed Collection instances are converted to the appropriate type prior to being added to the Collection.99"/> <entry key="two" value="2. <map/>.y.75"/> <entry key="six" value="3. specifying the merge attribute on a parent collection definition is redundant and will not result in the desired merging. } } <beans> <bean id="foo" class="x. The merging feature is available only in Spring 2.

org/schema/beans/spring-beans-3.xsd"> <bean name="classic" class="com.Spring Framework string values 9.example. This tells Spring to include a property declaration. XML shortcut with the p-namespace The p-namespace enables you to use the bean element's attributes. and 3. Null and empty string values Spring treats empty arguments for properties and the like as empty Strings. to describe your property values and/or collaborating beans.0.springframework. so you can set the name of the attribute to the property name.springframework.org/2001/XMLSchema-instance" xmlns:p="http://www. For example: <bean class="ExampleBean"> <property name="email"><null/></property> </bean> The above configuration is equivalent to the following Java code: exampleBean.org/schema/beans http://www. However. 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. As previously mentioned. Spring 2. instead of nested <property/> elements.ExampleBean" p:email="foo@bar.example.springframework. The <null/> element handles null values.1 Reference Documentation 57 .com"/> </bean> <bean name="p-namespace" class="com. <beans xmlns="http://www.org/schema/p" xsi:schemaLocation="http://www.99. This next example includes two more bean definitions that both have a reference to another bean: 3.0 and later supports extensible configuration formats with namespaces.setEmail(""). which are based on an XML Schema definition.setEmail(null). The following example shows two XML snippets that resolve to the same result: The first uses standard XML format and the second uses the p-namespace. The beans configuration format discussed in this chapter is defined in an XML Schema document. the p-namespace does not have a schema definition.75.springframework. 2.org/schema/beans" xmlns:xsi="http://www.ExampleBean"> <property name="email" value="foo@bar.w3. the p-namespace is not defined in an XSD file and exists only in the core of Spring.com"/> </beans> The example shows an attribute in the p-namespace called email in the bean definition.99 are converted into an actual Float type.

springframework. Note The p-namespace is not as flexible as the standard XML format. newly introduced in Spring 3.w3.y.Person"> <property name="name" value="Jane Doe"/> </bean> </beans> As you can see. allows usage of inlined attributes for configuring the constructor arguments rather then nested constructor-arg elements.Spring Framework <beans xmlns="http://www.org/2001/XMLSchema-instance" xmlns:c="http://www. Whereas the first bean definition uses <property name="spouse" ref="jane"/> to create a reference from bean john to bean jane. For example.springframework.org/schema/p" xsi:schemaLocation="http://www.Bar"/> <bean id="baz" class="x.springframework. In this case spouse is the property name. the c-namespace.org/2001/XMLSchema-instance" xmlns:p="http://www.1 Reference Documentation 58 . XML shortcut with the c-namespace Similar to the the section called “XML shortcut with the p-namespace”.org/schema/beans/spring-beans-3.Person" p:name="John Doe" p:spouse-ref="jane"/> <bean name="jane" class="com.org/schema/c" xsi:schemaLocation="http://www.1.org/schema/beans http://www.example. whereas the standard XML format does not.Baz"/> 3. We recommend that you choose your approach carefully and communicate this to your team members.example.org/schema/beans" xmlns:xsi="http://www.w3. but also uses a special format to declare property references. the format for declaring property references clashes with properties that end in Ref.org/schema/beans/spring-beans.springframework.springframework.springframework. the second bean definition uses p:spouse-ref="jane" as an attribute to do the exact same thing. this example includes not only a property value using the p-namespace.xsd"> <bean name="john-classic" class="com.y.springframework.springframework.xsd"> <bean id="bar" class="x.example. to avoid producing XML documents that use all three approaches at the same time.org/schema/beans" xmlns:xsi="http://www.org/schema/beans http://www. whereas the -ref part indicates that this is not a straight value but rather a reference to another bean.0. Let's review the examples from the section called “Constructor-based dependency injection” with the c namespace: <beans xmlns="http://www.Person"> <property name="name" value="John Doe"/> <property name="spouse" ref="jane"/> </bean> <bean name="john-modern" class="com.

y. which has a sammy property. <bean id="foo" class="foo. In order for this to work.y. one can use fallback to the argument indexes: <-. Compound property names You can use compound or nested property names when you set bean properties. The depends-on attribute can 3. Consider the following bean definition.Bar"> <property name="fred. the fred property of foo.y. Using depends-on If a bean is a dependency of another that usually means that one bean is set as a property of another.sammy" value="123" /> </bean> The foo bean has a fred property. and that final sammy property is being set to the value 123. for example. or a NullPointerException is thrown.1 Reference Documentation 59 . such as database driver registration. it needs to be declared even though it is not defined in an XSD schema (but it exists inside the Spring core).com"/> </bean> <-. the index notation requires the presence of the leading _ as XML attribute names cannot start with a number (even though some IDE allow it). For the rare cases where the constructor argument names are not available (usually if the bytecode was compiled without debugging information).Foo" c:_0-ref="bar" c:_1-ref="baz"> Note Due to the XML grammar.Foo" c:bar-ref="bar" c:baz-ref="baz" c:email="foo@bar. which has a bob property. a static initializer in a class needs to be triggered.'traditional' declaration --> <bean id="foo" class="x. However.'c-namespace' declaration --> <bean id="foo" class="x. sometimes dependencies between beans are less direct.Foo"> <constructor-arg ref="bar"/> <constructor-arg ref="baz"/> <constructor-arg value="foo@bar.Spring Framework <-. In practice.com"> </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. and the bob property of fred must not be null after the bean is constructed. Typically you accomplish this with the <ref/> element in XML-based configuration metadata.bob. as long as all components of the path except the final property name are not null. we recommend using the name notation through-out your configuration.'c-namespace' index declaration --> <bean id="foo" class="x. the constructor resolution mechanism is quite efficient in matching arguments so unless one really needs to.

because it must satisfy the singleton's dependencies. The following example uses the depends-on attribute to express a dependency on a single bean: <bean id="beanOne" class="ExampleBean" depends-on="manager"/> <bean id="manager" class="ManagerBean" /> To express a dependency on multiple beans.accountDao"> <property name="manager" ref="manager" /> </bean> <bean id="manager" class="ManagerBean" /> <bean id="accountDao" class="x.AnotherBean"/> When the preceding configuration is consumed by an ApplicationContext. Generally. you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. Thus depends-on can also control shutdown order.Spring Framework explicitly force one or more beans to be initialized before the bean using this element is initialized. 3. used as valid delimiters: <bean id="beanOne" class="ExampleBean" depends-on="manager.ExpensiveToCreateBean" lazy-init="true"/> <bean name="not. this pre-instantiation is desirable.lazy" class="com. the ApplicationContext creates the lazy-initialized bean at startup.JdbcAccountDao" /> Note The depends-on attribute in the bean definition can specify both an initialization time dependency and. as opposed to hours or even days later. when a lazy-initialized bean is a dependency of a singleton bean that is not lazy-initialized. rather than at startup. in the case of singleton beans only.foo. this behavior is controlled by the lazy-init attribute on the <bean/> element.foo. In XML.1 Reference Documentation 60 . a corresponding destroy time dependency. When this behavior is not desirable. with commas. ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. supply a list of bean names as the value of the depends-on attribute.lazy bean is eagerly pre-instantiated.y. The lazy-initialized bean is injected into a singleton bean elsewhere that is not lazy-initialized. prior to the given bean itself being destroyed. Dependent beans that define a depends-on relationship with a given bean are destroyed first.jdbc. whereas the not. Lazy-initialized beans By default. whitespace and semicolons. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested. the bean named lazy is not eagerly pre-instantiated when the ApplicationContext is starting up. However. for example: <bean id="lazy" class="com. because errors in the configuration or surrounding environment are discovered immediately.

If more than one exists. a fatal exception is thrown. Autowiring modes Mode no (Default) No autowiring. and it contains a master property (that is. you specify autowire mode for a bean definition with the autowire attribute of the <bean/> element. if a bean definition is set to autowire by name. Changing the default setting is not recommended for larger deployments. if you need to add a dependency to a class. because specifying collaborators explicitly gives greater control and clarity. --> </beans> Autowiring collaborators The Spring container can autowire relationships between collaborating beans. Spring looks for a bean definition named master. it has a setMaster(. Autowiring has the following advantages: • Autowiring can significantly reduce the need to specify properties or constructor arguments.. For example.) method). and uses it to set the property. Bean references must be defined via a ref element.Spring Framework You can also control lazy-initialization at the container level by using the default-lazy-init attribute on the <beans/> element. When using XML-based configuration metadata2. The autowiring functionality has five modes. Thus autowiring can be especially useful during development.. For example. for example: <beans default-lazy-init="true"> <!-. (Other mechanisms such as a bean template discussed elsewhere in this chapter are also valuable in this regard. To some extent. byType Allows a property to be autowired if exactly one bean of the property type exists in the container. You can allow Spring to resolve collaborators (other beans) automatically for your bean by inspecting the contents of the ApplicationContext. without negating the option of switching to explicit wiring when the code base becomes more stable. Spring looks for a bean with the same name as the property that needs to be autowired. Table 4.no beans will be pre-instantiated.2. that dependency can be satisfied automatically without you needing to modify the configuration.1 Reference Documentation 61 . which indicates that 2 Explanation See the section called “Dependency injection” 3. byName Autowiring by property name. it documents the structure of a system.) • Autowiring can update a configuration as your objects evolve. You specify autowiring per bean and thus can choose which ones to autowire..

This limitation is by-design. which is performed after autowiring completes. If there are no matching beans. • Multiple bean definitions within the container may match the type specified by the setter method or constructor argument to be autowired. collections. • Avoid autowiring for a bean definition by setting its autowire-candidate attributes to false as 3. this is not necessarily a problem. this ambiguity is not arbitrarily resolved. For arrays. In such cases all autowire candidates within the container that match the expected type are provided to satisfy the dependency. With byType or constructor autowiring mode. you have several options: • Abandon autowiring in favor of explicit wiring. If autowiring is not used in general. Consider the limitations and disadvantages of autowiring: • Explicit dependencies in property and constructor-arg settings always override autowiring. an exception is thrown. and the Maps keys will contain the corresponding bean names. nothing happens. If no unique bean definition is available. as noted in the above table. but applies to constructor arguments. 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.Spring Framework Mode Explanation you may not use byType autowiring for that bean. Although. • Autowiring is less exact than explicit wiring.1 Reference Documentation 62 . You can combine autowire behavior with dependency checking. you can wire arrays and typed-collections. Spring is careful to avoid guessing in case of ambiguity that might have unexpected results. the relationships between your Spring-managed objects are no longer documented explicitly. • Wiring information may not be available to tools that may generate documentation from a Spring container. Limitations and disadvantages of autowiring Autowiring works best when it is used consistently across a project. or Maps. Strings. In the latter scenario. and Classes (and arrays of such simple properties). it might be confusing to developers to use it to wire only one or two bean definitions. the property is not set. However for dependencies that expect a single value. If there is not exactly one bean of the constructor argument type in the container. a fatal error is raised. You cannot autowire so-called simple properties such as primitives. constructor Analogous to byType.

3.9. implement the more fine-grained control available with annotation-based configuration. Method injection In most application scenarios. A solution is to forego some inversion of control. The container cannot provide bean A with a new instance of bean B every time one is needed. // Spring-API imports import org. “Annotation-based container configuration”. provide a value of *Repository. • Designate a single bean definition as the primary candidate by setting the primary attribute of its <bean/> element to true. The container only creates the singleton bean A once. • If you are using Java 5 or later. In Spring's XML format.beans. The following is an example of this approach: // a class that uses a stateful Command-style class to perform some processing package fiona. most beans in the container are singletons.Spring Framework described in the next section. You can make bean A aware of the container by implementing the ApplicationContextAware interface. When a singleton bean needs to collaborate with another singleton bean. These techniques are useful for beans that you never want to be injected into other beans by autowiring. or a non-singleton bean needs to collaborate with another non-singleton bean. Suppose singleton bean A needs to use non-singleton (prototype) bean B. perhaps on each method invocation on A.apple. the bean itself is not a candidate for autowiring other beans. to limit autowire candidate status to any bean whose name ends with Repository. A problem arises when the bean lifecycles are different. you typically handle the dependency by defining one bean as a property of the other.1 Reference Documentation 63 . as described in Section 4. To provide multiple patterns. and by making a getBean("B") call to the container ask for (a typically new) bean B instance every time bean A needs it. Excluding a bean from autowiring On a per-bean basis. The top-level <beans/> element accepts one or more patterns within its default-autowire-candidates attribute. It does not mean that an excluded bean cannot itself be configured using autowiring. you can exclude a bean from autowiring.BeansException. set the autowire-candidate attribute of the <bean/> element to false. and for such beans. the pattern matching rules do not apply. the container makes that specific bean definition unavailable to the autowiring infrastructure (including annotation style configurations such as @Autowired). Rather. You can also limit autowire candidates based on pattern-matching against bean names. define them in a comma-separated list. For example.springframework. An explicit value of true or false for a bean definitions autowire-candidate attribute always takes precedence. and thus only gets one opportunity to set the properties.

Note For this dynamic subclassing to work. The lookup typically involves a prototype bean as in the scenario described in the preceding section. you see that the Spring container 3.springframework. Looking at the CommandManager class in the previous code snippet. Lookup method injection Lookup method injection is the ability of the container to override methods on container managed beans. } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this. objects that have been the target of method injection cannot be serialized. a somewhat advanced feature of the Spring IoC container. public Object process(Map commandState) { // grab a new instance of the appropriate Command Command command = createCommand(). Method Injection.Spring Framework import org.applicationContext. return command.context.execute().setState(commandState). Also. } } The preceding is not desirable. allows this use case to be handled in a clean fashion. The Spring Framework implements this method injection by using bytecode generation from the CGLIB library to generate dynamically a subclass that overrides the method. } protected Command createCommand() { // notice the Spring API dependency! return this. because the business code is aware of and coupled to the Spring Framework. testing a class that has an abstract method requires you to subclass the class yourself and to supply a stub implementation of the abstract method.applicationContext = applicationContext.class). You can read more about the motivation for Method Injection in this blog entry. Command. // set the state on the (hopefully brand new) Command instance command. to return the lookup result for another named bean in the container.context. and the method to be overridden cannot be final either. The class that the Spring container will subclass cannot be final. import org.ApplicationContext.springframework.getBean("command". public class CommandManager implements ApplicationContextAware { private ApplicationContext applicationContext. you must have the CGLIB jar(s) in your classpath. Finally.ApplicationContextAware.1 Reference Documentation 64 .

apple. Your CommandManager class will not have any Spring dependencies. } In the client class containing the method to be injected (the CommandManager in this case). 3.config package) to be of use. ObjectFactoryCreatingFactoryBean.commandProcessor uses statefulCommandHelper --> <bean id="commandManager" class="fiona.a stateful bean deployed as a prototype (non-singleton) --> <bean id="command" class="fiona.execute(). If it is deployed as a singleton.setState(commandState). You must be careful to deploy the command bean as a prototype.Spring Framework will dynamically override the implementation of the createCommand() method. Consult the JavaDocs for these classes as well as this blog entry for additional information ServiceLocatorFactoryBean. The approach used in ServiceLocatorFactoryBean is similar to that of another utility class.. the same instance of the command bean is returned each time.beans. For example: <!-. Tip The interested reader may also find the ServiceLocatorFactoryBean (in the org. as can be seen in the reworked example: package fiona. the dynamically-generated subclass implements the method.AsyncCommand" scope="prototype"> <!-. if that is actually what is needed.CommandManager"> <lookup-method name="createCommand" bean="command"/> </bean> The bean identified as commandManager calls its own method createCommand() whenever it needs a new instance of the command bean.apple.. but where is the implementation of this method? protected abstract Command createCommand(). the method to be injected requires a signature of the following form: <public|protected> [abstract] <return-type> theMethodName(no-arguments). Otherwise. // 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().factory. the dynamically-generated subclass overrides the concrete method defined in the original class.inject dependencies here as required --> </bean> <!-.springframework.apple. } // okay. If the method is abstract.1 Reference Documentation 65 . but it allows you to specify your own lookup interface as opposed to a Spring-specific lookup interface. return command. // set the state on the (hopefully brand new) Command instance command.

The signature for the arguments is necessary only if the method is overloaded and multiple variants exist within the class.c.MethodReplacer interface provides the new method definition.. you can use the replaced-method element to replace an existing method implementation with another.. For convenience. which we want to override: public class MyValueCalculator { public String computeValue(String input) { // some real code.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. and return a computed result String input = (String) args[0]. } A class implementing the org.factory.String: 3. Method m.Spring Framework Arbitrary method replacement A less useful form of method injection than lookup method Injection is the ability to replace arbitrary methods in a managed bean with another method implementation.1 Reference Documentation 66 ..beans..y.arbitrary method replacement --> <replaced-method name="computeValue" replacer="replacementComputeValue"> <arg-type>String</arg-type> </replaced-method> </bean> <bean id="replacementComputeValue" class="a...z. /** meant to be used to override the existing computeValue(String) implementation in MyValueCalculator */ public class ReplacementComputeValue implements MethodReplacer { public Object reimplement(Object o. With XML-based configuration metadata. Consider the following class. For example. with a method computeValue.. return . the following all match java.MyValueCalculator"> <!-.b..springframework. Object[] args) throws Throwable { // get the input value. } // some other methods.lang. . Users may safely skip the rest of this section until the functionality is actually needed. } } The bean definition to deploy the original class and specify the method override would look like this: <bean id="myValueCalculator" class="x.support. for a deployed bean.. work with it. the type string for an argument may be a substring of the fully qualified type name.

Only valid in the context of a web-aware Spring ApplicationContext. 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.5 Bean scopes When you create a bean definition. that is. Scopes a single bean definition to the lifecycle of a single HTTP request. 4. You can also create a custom scope. This approach is powerful and flexible in that you can choose the scope of the objects you create through configuration instead of having to bake in the scope of an object at the Java class level. you create a recipe for creating actual instances of the class defined by that bean definition. Scopes a single bean definition to any number of object instances. The following scopes are supported out of the box. three of which are available only if you use a web-aware ApplicationContext. The idea that a bean definition is a recipe is important. but also the scope of the objects created from a particular bean definition. Beans can be defined to be deployed in one of a number of scopes: out of the box. Reference Documentation 67 prototype request session 3.String String Str Because the number of arguments is often enough to distinguish between each possible choice. the Spring Framework supports five scopes. as with a class. Bean scopes Scope singleton Description (Default) Scopes a single bean definition to a single object instance per Spring IoC container.lang. Scopes a single bean definition to the lifecycle of an HTTP Session.1 . Table 4. each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.Spring Framework java. you can create many object instances from a single recipe.3. because it means that. this shortcut can save a lot of typing. by allowing you to type only the shortest string that will match an argument type.

a thread scope is available. For instructions on how to register this or any other custom scope.Spring Framework Scope global session Description Scopes a single bean definition to the lifecycle of a global HTTP Session. For more information. and all requests for beans with an id or ids matching that bean definition result in that one specific bean instance being returned by the Spring container. see the documentation for SimpleThreadScope. see the section called “Using a custom scope”. the Spring IoC container creates exactly one instance of the object defined by that bean definition. but is not registered by default. Only valid in the context of a web-aware Spring ApplicationContext. Thread-scoped beans As of Spring 3. when you define a bean definition and it is scoped as a singleton. Typically only valid when used in a portlet context.1 Reference Documentation 68 . To put it another way. This single instance is stored in a cache of such singleton beans. 3. The singleton scope Only one shared instance of a singleton bean is managed. and all subsequent requests and references for that named bean return the cached object.0.

That is. The singleton scope is the default scope in Spring.using spring-beans-2.foo. This means that if you define one bean for a particular class in a single Spring container.foo. The following diagram illustrates the Spring prototype scope. the bean is injected into another bean or you request it through a getBean() method call on the container. use the prototype scope for all stateful beans and the singleton scope for stateless beans. To define a bean as a singleton in XML. for example: <bean id="accountService" class="com.foo. because a typical DAO does not hold any conversational state.DefaultAccountService" scope="prototype"/> 3.dtd --> <bean id="accountService" class="com.DefaultAccountService"/> <!-.0. The GoF Singleton hard-codes the scope of an object such that one and only one instance of a particular class is created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean.DefaultAccountService" scope="singleton"/> The prototype scope The non-singleton. A data access object (DAO) is not typically configured as a prototype. though redundant (singleton scope is the default) --> <bean id="accountService" class="com. it was just easier for this author to reuse the core of the singleton diagram. then the Spring container creates one and only one instance of the class defined by that bean definition. The following example defines a bean as a prototype in XML: <!-. you would write.the following is equivalent.1 Reference Documentation 69 .Spring Framework Spring's concept of a singleton bean differs from the Singleton pattern as defined in the Gang of Four (GoF) patterns book. prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made. As a rule.

If you use these scopes with regular Spring IoC containers such as the ClassPathXmlApplicationContext. in effect. and otherwise assembles a prototype object. you get an IllegalStateException complaining about an unknown bean scope. when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies. within a request that is processed by the 3. You cannot dependency-inject a prototype-scoped bean into your singleton bean. In some respects. Spring does not manage the complete lifecycle of a prototype bean: the container instantiates. with no further record of that prototype instance. configures. some minor initial configuration is required before you define your beans. If you need a new instance of a prototype bean at runtime more than once. in the case of prototypes. and hands it to the client.Spring Framework In contrast to the other scopes. If you access scoped beans within Spring Web MVC. a new prototype bean is instantiated and then dependency-injected into the singleton bean. and global session scopes The request. see the section called “Lifecycle callbacks”. session.) Singleton beans with prototype-bean dependencies When you use singleton-scoped beans with dependencies on prototype beans. Initial web configuration To support the scoping of beans at the request. (This initial setup is not required for the standard scopes. the Spring container's role in regard to a prototype-scoped bean is a replacement for the Java new operator. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean. although initialization lifecycle callback methods are called on all objects regardless of scope. which holds a reference to beans that need to be cleaned up.1 Reference Documentation 70 . and global session scopes are only available if you use a web-aware Spring ApplicationContext implementation (such as XmlWebApplicationContext). because that injection occurs only once. be aware that dependencies are resolved at instantiation time. All lifecycle management past that point must be handled by the client.. and global session levels (web-scoped beans). session. (For details on the lifecycle of a bean in the Spring container. suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime.) How you accomplish this initial setup depends on your particular Servlet environment. try using a custom bean post-processor. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean. see the section called “Method injection” Request. singleton and prototype. Thus. configured destruction lifecycle callbacks are not called. To get the Spring container to release resources held by prototype-scoped beans. However. session.

. the loginAction bean is scoped at the HTTP request level. <filter> <filter-name>requestContextFilter</filter-name> <filter-class>org.and session-scoped available further down the call chain.Spring Framework Spring DispatcherServlet. That is. you need to add the following javax. they are particular to an individual request.RequestContextFilter</filter-class> </filter> <filter-mapping> <filter-name>requestContextFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> . namely bind the HTTP request object to the Thread that is servicing that request. the bean that 3.context. then no special setup is necessary: DispatcherServlet and DispatcherPortlet already expose all relevant state. </web-app> If you use an older web container (Servlet 2. with requests processed outside of Spring's DispatcherServlet (for example.) <web-app> .RequestContextListener </listener-class> </listener> . because other instances created from the same loginAction bean definition will not see these changes in state. RequestContextListener and RequestContextFilter all do exactly the same thing.LoginAction" scope="request"/> The Spring container creates a new instance of the LoginAction bean by using the loginAction bean definition for each and every HTTP request.4+ web container. so you must change it as appropriate.web.1 Reference Documentation 71 ..3 container..3)...springframework.request. when using JSF or Struts).springframework. When the request completes processing.foo.Filter implementation. <listener> <listener-class> org.servlet. If you use a Servlet 2. You can change the internal state of the instance that is created as much as you want. The following snippet of XML configuration must be included in the web..filter.servlet. use the provided javax. Request scope Consider the following bean definition: <bean id="loginAction" class="com.ServletRequestListener to the declarations in your web applications web.xml file: <web-app> .xml file of your web application if you want to access web-scoped beans in requests outside of Spring's DispatcherServlet on a Servlet 2. </web-app> DispatcherServlet.. (The filter mapping depends on the surrounding web application configuration. or DispatcherPortlet.web. This makes beans that are request.

Spring Framework is scoped to the request is discarded. you need to inject a proxy object that exposes the same public interface as the scoped object but that can also retrieve the real. you can change the internal state of the instance that is created as much as you want. and applies only in the context of portlet-based web applications. When the HTTP Session is eventually discarded.UserPreferences" scope="globalSession"/> The global session scope is similar to the standard HTTP Session scope (described above). That is. target object from the relevant scope (for example. If you try to create a scoped proxy for a singleton bean.1 Reference Documentation 72 . the standard HTTP Session scope is used.UserPreferences" scope="session"/> The Spring container creates a new instance of the UserPreferences bean by using the userPreferences bean definition for the lifetime of a single HTTP Session. an HTTP request) and delegate method calls onto the real object. the bean that is scoped to that particular HTTP Session is also discarded. because they are particular to an individual HTTP Session. knowing that other HTTP Session instances that are also using instances created from the same userPreferences bean definition do not see these changes in state. If you want to inject (for example) an HTTP request scoped bean into another bean.foo. the userPreferences bean is effectively scoped at the HTTP Session level. 3. Beans defined at the global session scope are scoped (or bound) to the lifetime of the global portlet Session. If you write a standard Servlet-based web application and you define one or more beans as having global session scope. As with request-scoped beans. the BeanCreationException is raised. Global session scope Consider the following bean definition: <bean id="userPreferences" class="com. In other words. Session scope Consider the following bean definition: <bean id="userPreferences" class="com. you must inject an AOP proxy in place of the scoped bean.foo. and no error is raised. The portlet specification defines the notion of a global Session that is shared among all portlets that make up a single portlet web application. Note You do not need to use the <aop:scoped-proxy/> in conjunction with beans that are scoped as singletons or prototypes. Scoped beans as dependencies The Spring IoC container manages not only the instantiation of your objects (beans). but also the wiring up of collaborators (or dependencies).

org/schema/aop/spring-aop-3.w3. you need a single userManager object.springframework.xsd http://www. The salient point here is that the userManager bean is a singleton: it will be instantiated exactly once per container. the userPreferences bean) are also injected only once. (The following userPreferences bean definition as it stands is incomplete.) <bean id="userPreferences" class="com. the singleton bean userManager is injected with a reference to the HTTP Session-scoped bean userPreferences.springframework.springframework.org/schema/aop" xsi:schemaLocation="http://www. and its dependencies (in this case only one.org/schema/beans" xmlns:xsi="http://www.a singleton-scoped bean injected with a proxy to the above bean --> <bean id="userService" class="com.org/schema/aop http://www.UserPreferences" scope="session"> <!-.a reference to the proxied userPreferences bean --> <property name="userPreferences" ref="userPreferences"/> </bean> </beans> To create such a proxy.springframework.SimpleUserService"> <!-. <?xml version="1. globalSession and custom-scope levels require the <aop:scoped-proxy/> element ? Let's examine the following singleton bean definition and contrast it with what you need to define for the aforementioned scopes.) Why do definitions of beans scoped at the request.an HTTP Session-scoped bean exposed as a proxy --> <bean id="userPreferences" class="com.0. you insert a child <aop:scoped-proxy/> element into a scoped bean definition. See the section called “Choosing the type of proxy to create” and Appendix C. XML Schema-based configuration.0.org/2001/XMLSchema-instance" xmlns:aop="http://www.0" encoding="UTF-8"?> <beans xmlns="http://www. (If you choose class-based proxying.foo. This is not the behavior you want when injecting a shorter-lived scoped bean into a longer-lived scoped bean. and for the lifetime of an HTTP Session.foo.UserManager"> <property name="userPreferences" ref="userPreferences"/> </bean> In the preceding example. Rather.org/schema/beans/spring-beans-3. you also need the CGLIB library in your classpath.UserPreferences" scope="session"/> <bean id="userManager" class="com.1 Reference Documentation 73 .Spring Framework The configuration in the following example is only one line. you need a userPreferences object that is specific to said HTTP Session. This means that the userManager bean will only operate on the exact same userPreferences object.foo. session. for example injecting an HTTP Session-scoped collaborating bean as a dependency into singleton bean.xsd"> <!-. the one that it was originally injected with.instructs the container to proxy the surrounding bean --> <aop:scoped-proxy/> </bean> <!-. Thus the container creates an object that exposes the exact same public interface as the UserPreferences class 3. but it is important to understand the “why” as well as the “how” behind it.foo.org/schema/beans http://www. that is.springframework.springframework.

configuration when injecting request-. or even 3. Note: CGLIB proxies only intercept public method calls! Do not call non-public methods on such a proxy. <!-.1 Reference Documentation 74 . In this example.DefaultUserPreferences implements the UserPreferences interface --> <bean id="userPreferences" class="com.0. The container injects this proxy object into the userManager bean. Thus you need the following. they will not be delegated to the scoped target object.foo. by specifying false for the value of the proxy-target-class attribute of the <aop:scoped-proxy/> element.foo.UserManager"> <property name="userPreferences" ref="userPreferences"/> </bean> Choosing the type of proxy to create By default. when a UserManager instance invokes a method on the dependency-injected UserPreferences object.UserPreferences" scope="session"> <aop:scoped-proxy/> </bean> <bean id="userManager" class="com. it also means that the class of the scoped bean must implement at least one interface. However. see Section 8. when the Spring container creates a proxy for a bean that is marked up with the <aop:scoped-proxy/> element. it actually is invoking a method on the proxy.foo. Session.UserManager"> <property name="userPreferences" ref="userPreferences"/> </bean> For more detailed information about choosing class-based or interface-based proxying.). session-. You can define your own scopes.Spring Framework (ideally an object that is a UserPreferences instance) which can fetch the real UserPreferences object from the scoping mechanism (HTTP request. Custom scopes As of Spring 2. the bean scoping mechanism is extensible.DefaultUserPreferences" scope="session"> <aop:scoped-proxy proxy-target-class="false"/> </bean> <bean id="userManager" class="com. Alternatively. “Proxying mechanisms”. and delegates the method invocation onto the retrieved real UserPreferences object. and globalSession-scoped beans into collaborating objects: <bean id="userPreferences" class="com. you can configure the Spring container to create standard JDK interface-based proxies for such scoped beans. which is unaware that this UserPreferences reference is a proxy. and that all collaborators into which the scoped bean is injected must reference the bean through one of its interfaces.6. correct and complete. etc. This means that you need to have the CGLIB library in the classpath of your application. Using JDK interface-based proxies means that you do not need additional libraries in your application classpath to effect such proxying. a CGLIB-based class proxy is created. The proxy then fetches the real UserPreferences object from (in this case) the HTTP Session.foo.

which is described in this section. the method returns a new instance of the bean. returns the session-scoped bean (and if it does not exist. The session scope implementation. Runnable destructionCallback) The following method obtains the conversation identifier for the underlying scope. Scope scope). after having bound it to the session for future reference). This identifier is different for each scope. you need to make the Spring container aware of your new scope(s). For a session scoped implementation.config. although the latter is considered bad practice and you cannot override the built-in singleton and prototype scopes.Scope interface. see the Scope implementations that are supplied with the Spring Framework itself and the Scope Javadoc. but you can return null if the object with the specified name is not found. void registerDestructionCallback(String name. for example. remove them from the scope. The Scope interface has four methods to get objects from the scope. The following method returns the object from the underlying scope. Object get(String name. this identifier can be the session identifier. and allow them to be destroyed. The object should be returned.factory.springframework. Creating a custom scope To integrate your custom scope(s) into the Spring container. String getConversationId() Using a custom scope After you write and test one or more custom Scope implementations. removes the session-scoped bean from the underlying session. This method is declared on the ConfigurableBeanFactory interface. For an idea of how to implement your own scopes. which is available on most of 3.1 Reference Documentation 75 .Spring Framework redefine existing scopes. ObjectFactory objectFactory) The following method removes the object from the underlying scope. The following method is the central method to register a new Scope with the Spring container: void registerScope(String scopeName. which explains the methods you need to implement in more detail. Object remove(String name) The following method registers the callbacks the scope should execute when it is destroyed or when the specified object in the scope is destroyed. The session scope implementation for example. you need to implement the org.beans. Refer to the Javadoc or a Spring scope implementation for more information on destruction callbacks.

1 Reference Documentation 76 .w3.springframework. beanFactory.SimpleThreadScope"/> </entry> </map> </property> </bean> <bean id="bar" class="x.org/schema/aop" xsi:schemaLocation="http://www. The second argument to the registerScope(.config.org/schema/beans http://www. but not registered by default.springframework.support.. The first argument to the registerScope(.springframework. You then create bean definitions that adhere to the scoping rules of your custom Scope: <bean id=".Spring Framework the concrete ApplicationContext implementations that ship with Spring via the BeanFactory property. Scope threadScope = new SimpleThreadScope().springframework.org/2001/XMLSchema-instance" xmlns:aop="http://www." scope="thread"> With a custom Scope implementation.beans.org/schema/aop http://www.org/schema/beans" xmlns:xsi="http://www.y..0. and then register it as below...springframework.registerScope("thread".org/schema/beans/spring-beans-3. You can also do the Scope registration declaratively. examples of such names in the Spring container itself are singleton and prototype. Suppose that you write your custom Scope implementation.springframework.0" encoding="UTF-8"?> <beans xmlns="http://www.y..factory. threadScope).) method is an actual instance of the custom Scope implementation that you wish to register and use. you are not limited to programmatic registration of the scope.springframework. Note The example below uses SimpleThreadScope which is included with Spring. using the CustomScopeConfigurer class: <?xml version="1.xsd"> <bean class="org.0.springframework.org/schema/aop/spring-aop-3..Foo"> <property name="bar" ref="bar"/> </bean> </beans> 3.Bar" scope="thread"> <property name="name" value="Rick"/> <aop:scoped-proxy/> </bean> <bean id="foo" class="x.context.CustomScopeConfigurer"> <property name="scopes"> <map> <entry key="thread"> <bean class="org. The instructions would be the same for your own custom Scope implementations." class=".) method is the unique name associated with a scope.xsd http://www.

you use the init-method attribute to specify the name of the method that has a void no-argument signature.Spring Framework Note When you place <aop:scoped-proxy/> in a FactoryBean implementation. Internally. The InitializingBean interface specifies a single method: void afterPropertiesSet() throws Exception.factory.8. 4. the Spring Framework uses BeanPostProcessor implementations to process any callback interfaces it can find and call the appropriate methods. In addition to the initialization and destruction callbacks. see Section 4. not the object returned from getObject(). It is recommended that you do not use the InitializingBean interface because it unnecessarily couples the code to Spring. The lifecycle callback interfaces are described in this section. it is the factory bean itself that is scoped.ExampleBean" init-method="init"/> public class ExampleBean { 3. you can implement the Spring InitializingBean and DisposableBean interfaces.beans.6 Customizing the nature of a bean Lifecycle callbacks To interact with the container's management of the bean lifecycle.springframework.1 Reference Documentation 77 . Alternatively. For example. In the case of XML-based configuration metadata. you can implement a BeanPostProcessor yourself. “Container Extension Points”. You can also achieve the same integration with the container without coupling your classes to Spring interfaces through the use of init-method and destroy method object definition metadata. For more information. Spring-managed objects may also implement the Lifecycle interface so that those objects can participate in the startup and shutdown process as driven by the container's own lifecycle. The container calls afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction of your beans. If you need custom features or other lifecycle behavior Spring does not offer out-of-the-box. Initialization callbacks The org.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container. specify a POJO initialization method. the following definition: <bean id="exampleInitBean" class="examples.

is exactly the same as. you use the destroy-method attribute on the <bean/>. The DisposableBean interface specifies a single method: void destroy() throws Exception. With XML-based configuration metadata.... It is recommended that you do not use the DisposableBean callback interface because it unnecessarily couples the code to Spring.. the following definition: <bean id="exampleInitBean" class="examples..ExampleBean" destroy-method="cleanup"/> public class ExampleBean { public void cleanup() { // do some destruction work (like releasing pooled connections) } } . For example. Alternatively.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed. 3. but does not couple the code to Spring....springframework..1 Reference Documentation 78 . <bean id="exampleInitBean" class="examples.AnotherExampleBean"/> public class AnotherExampleBean implements DisposableBean { public void destroy() { // do some destruction work (like releasing pooled connections) } } ...AnotherExampleBean"/> public class AnotherExampleBean implements InitializingBean { public void afterPropertiesSet() { // do some initialization work } } .is exactly the same as.. but does not couple the code to Spring.Spring Framework public void init() { // do some initialization work } } .factory. specify a generic method that is supported by bean definitions.beans. <bean id="exampleInitBean" class="examples. Destruction callbacks Implementing the org.

").DefaultBlogService"> <property name="blogDao" ref="blogDao" /> </bean> </beans> The presence of the default-init-method attribute on the top-level <beans/> element attribute causes the Spring IoC container to recognize a method called init on beans as the initialization method callback. the names of such lifecycle callback methods are standardized across a project so that all developers use the same method names and ensure consistency. This means that you. When a bean is created and assembled. is) by using the Where existing bean classes already have callback methods that are named at variance with the 3. if the bean class has such a method. The Spring IoC container calls that method when the bean is created (and in accordance with the standard lifecycle callback contract described previously). public void setBlogDao(BlogDao blogDao) { this.blogDao == null) { throw new IllegalStateException("The [blogDao] property must be set. can write your application classes and use an initialization callback called init(). You configure destroy method callbacks similarly (in XML. without having to configure an init-method="init" attribute with each bean definition. Ideally.blogDao = blogDao. as an application developer. you typically write methods with names such as init(). public class DefaultBlogService implements BlogService { private BlogDao blogDao. that default-destroy-method attribute on the top-level <beans/> element. Your class will resemble the class in the following example. it is invoked at the appropriate time. You can configure the Spring container to look for named initialization and destroy callback method names on every bean. initialize(). Suppose that your initialization callback methods are named init() and destroy callback methods are named destroy().Spring Framework Default initialization and destroy methods When you write initialization and destroy method callbacks that do not use the Spring-specific InitializingBean and DisposableBean callback interfaces. dispose(). and so on.1 Reference Documentation 79 . This feature also enforces a consistent naming convention for initialization and destroy method callbacks. } // this is (unsurprisingly) the initialization callback method public void init() { if (this. } } } <beans default-init-method="init"> <bean id="blogService" class="com.foo.

are called as follows: • Methods annotated with @PostConstruct • afterPropertiesSet() as defined by the InitializingBean callback interface • A custom configured init() method Destroy methods are called in the same order: • Methods annotated with @PreDestroy • destroy() as defined by the DisposableBean callback interface • A custom configured destroy() method Startup and shutdown callbacks 3. You can combine these mechanisms to control a given bean. bypassing the proxy.Spring Framework convention. then an AOP proxy (for example) with its interceptor chain is applied. init() for an initialization method . Note If multiple lifecycle mechanisms are configured for a bean. custom init() and destroy() methods. Combining lifecycle mechanisms As of Spring 2. then each configured method is executed in the order listed below. A target bean is fully created first. which means that AOP interceptors and so forth are not yet applied to the bean. and the @PostConstruct and @PreDestroy annotations. it would be inconsistent to apply the interceptors to the init method. However. The Spring container guarantees that a configured initialization callback is called immediately after a bean is supplied with all dependencies.for more than one of these lifecycle mechanisms.5. Thus the initialization callback is called on the raw bean reference. and each mechanism is configured with a different method name. Multiple lifecycle mechanisms configured for the same bean. as explained in the preceding section. your code can even interact with the raw target bean.for example. if the same method name is configured .1 Reference Documentation 80 . Hence. with different initialization methods. you can override the default by specifying (in XML. If the target bean and the proxy are defined separately. because doing so would couple the lifecycle of the target bean with its proxy/interceptors and leave strange semantics when your code interacts directly to the raw target bean. that method is executed once. that is) the method name using the init-method and destroy-method attributes of the <bean/> itself. you have three options for controlling bean lifecycle behavior: the InitializingBean and DisposableBean callback interfaces.

It does this by delegating to a LifecycleProcessor: public interface LifecycleProcessor extends Lifecycle { void onRefresh(). and it will stop before its dependency. boolean isRunning(). void onClose(). } Notice that the LifecycleProcessor is itself an extension of the Lifecycle interface. Phased. However.Spring Framework The Lifecycle interface defines the essential methods for any object that has its own lifecycle requirements (e. Then.g.1 Reference Documentation 81 . } When starting. it will cascade those calls to all Lifecycle implementations defined within that context. The order of startup and shutdown invocations can be important. When considering the 3. when the ApplicationContext itself starts and stops. the SmartLifecycle interface defines another option. Therefore. namely the getPhase() method as defined on its super-interface. In those cases. the dependent side will start after its dependency. } Any Spring-managed object may implement that interface.MIN_VALUE would be among the first to start and the last to stop. void stop().MAX_VALUE would indicate that the object should be started last and stopped first (likely because it depends on other processes to be running). It also adds two other methods for reacting to the context being refreshed and closed. void stop(Runnable callback). } public interface SmartLifecycle extends Lifecycle. the reverse order is followed. You may only know that objects of a certain type should start prior to objects of another type. an object that implements SmartLifecycle and whose getPhase() method returns Integer. at times the direct dependencies are unknown. Phased { boolean isAutoStartup(). At the other end of the spectrum. the objects with the lowest phase start first. If a "depends-on" relationship exists between any two objects. starts and stops some background process): public interface Lifecycle { void start(). a phase value of Integer. public interface Phased { int getPhase(). and when stopping.

The default per-phase timeout is 30 seconds. you register a shutdown hook with the JVM. You can override the default lifecycle processor instance by defining a bean named "lifecycleProcessor" within the context. If you are using Spring's IoC container in a non-web application environment. If you only want to modify the timeout.support. then defining the following would be sufficient: <bean id="lifecycleProcessor" class="org. If "true". will wait up to its timeout value for the group of objects within each phase to invoke that callback. The 'refresh' callback on the other hand enables another feature of SmartLifecycle beans. that callback will be invoked.AbstractApplicationContext. That enables asynchronous shutdown where necessary since the default implementation of the LifecycleProcessor interface. The "phase" value as well as any "depends-on" relationships will determine the startup order in the same way as described above. any negative phase value would indicate that an object should start before those standard components (and stop after them). 3. for example. Any implementation must invoke that callback's run() method after that implementation's shutdown process is complete. and at that point the default lifecycle processor will check the boolean value returned by each SmartLifecycle object's isAutoStartup() method. Of course. Shutting down the Spring IoC container gracefully in non-web applications Note This section applies only to non-web applications. When the context is refreshed (after all objects have been instantiated and initialized). then that object will be started at that point rather than waiting for an explicit invocation of the context's or its own start() method (unlike the context refresh. Therefore. The latter will simply drive the shutdown process as if stop() had been called explicitly.timeout value in milliseconds --> <property name="timeoutPerShutdownPhase" value="10000"/> </bean> As mentioned. but it will happen when the context is closing.springframework. To register a shutdown hook. and vice versa for any positive phase value. As you can see the stop method defined by SmartLifecycle accepts a callback. the LifecycleProcessor interface defines callback methods for the refreshing and closing of the context as well.context. it's also important to know that the default phase for any "normal" Lifecycle object that does not implement SmartLifecycle would be 0.context.springframework. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released. you must still configure and implement these destroy callbacks correctly. the context start does not happen automatically for a standard context implementation). you call the registerShutdownHook() method that is declared on the AbstractApplicationContext class: import org. DefaultLifecycleProcessor.Spring Framework phase value.1 Reference Documentation 82 .support. in a rich client desktop environment. Spring's web-based ApplicationContext implementations already have code in place to shut down the Spring IoC container gracefully when the relevant web application is shut down.DefaultLifecycleProcessor"> <!-.

through the ApplicationContext interface. Other methods of the ApplicationContext provide access to file resources.. or by casting the reference to a known subclass of this interface. the class is provided with a reference to that ApplicationContext.Spring Framework import org. or method parameter that is expecting the BeanFactory type if the field. constructor argument.BeanNameAware interface. // main method exits.14. Sometimes this capability is useful. If you do.. the ApplicationFactory is autowired into a field.xml"}). ctx. // app runs here.5. respectively.. When an ApplicationContext creates a class that implements the org.context. see the section called “@Autowired”.ApplicationContextAware interface. For more information. which exposes additional functionality. however. public interface BeanNameAware { 3.registerShutdownHook().springframework. public final class Boot { public static void main(final String[] args) throws Exception { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(new String []{"beans. These additional features are described in Section 4. where collaborators are provided to beans as properties. hook is called prior to the app shutting down. constructor. One use would be the programmatic retrieval of other beans. } } ApplicationContextAware and BeanNameAware When an ApplicationContext creates a class that implements the org. such as ConfigurableApplicationContext. // add a shutdown hook for the above context. or method in question carries the @Autowired annotation.factory. autowiring is another alternative to obtain reference to the ApplicationContext.. } Thus beans can manipulate programmatically the ApplicationContext that created them. and accessing a MessageSource. including the ability to autowire fields and multiple parameter methods.1 Reference Documentation 83 . “Additional Capabilities of the ApplicationContext” As of Spring 2.springframework.. in general you should avoid it.ClassPathXmlApplicationContext. because it couples the code to Spring and does not follow the Inversion of Control style.springframework. For more flexibility. The "traditional" constructor and byType autowiring modes (as described in the section called “Autowiring collaborators”) can provide a dependency of type ApplicationContext for a constructor argument or setter method parameter.beans..support. public interface ApplicationContextAware { void setApplicationContext(ApplicationContext applicationContext) throws BeansException.context. the class is provided with a reference to the name defined in its associated object definition. use the new annotation-based autowiring features. publishing application events.

as a general rule. Aware interfaces Name Injected Dependency Explained in. the section called “ApplicationContextAware and BeanNameAware” ApplicationContextAware Declaring ApplicationContext ApplicationEventPublisherAware Event publisher of the enclosing Section 4.. beans” Declaring BeanFactory the section called “ApplicationContextAware and BeanNameAware” the section called “ApplicationContextAware and BeanNameAware” BeanFactoryAware BeanNameAware Name of the declaring bean BootstrapContextAware Resource adapter Chapter 24..Spring Framework void setBeanName(string name) throws BeansException. } The callback is invoked after population of normal bean properties but before an initialization callback such as InitializingBeans afterPropertiesSet or a custom init-method. JCA CCI BootstrapContext the container runs in. Other Aware interfaces Besides ApplicationContextAware and BeanNameAware discussed above. The most important Aware interfaces are summarized below . the name is a good indication of the dependency type: Table 4.4.14. Spring offers a range of Aware interfaces that allow beans to indicate to the container that they require a certain infrastructure dependency. “Additional ApplicationContext Capabilities of the ApplicationContext” BeanClassLoaderAware Class loader used to load the the section called “Instantiating bean classes. Typically available only in JCA aware ApplicationContexts 3.1 Reference Documentation 84 .

Defined weaver for processing the section called “Load-time class definition at load time weaving with AspectJ in the Spring Framework” Configured strategy for resolving Section 4.14. container runs in. “Notifications” MessageSourceAware NotificationPublisherAware Spring publisher PortletConfigAware Current PortletConfig the Chapter 19. Resources access to resources Current ServletConfig the Chapter 16. they are recommended for infrastructure beans that require programmatic access to the container. Valid only in a framework web-aware Spring ApplicationContext Web MVC ServletConfigAware ServletContextAware Web MVC Note again that usage of these interfaces ties your code to the Spring API and does not follow the Inversion of Control style.1 Reference Documentation 85 . container runs in. Valid only in a framework web-aware Spring ApplicationContext Current ServletContext the Chapter 16..Spring Framework Name LoadTimeWeaverAware Injected Dependency Explained in. 3. container runs in.. As such. container runs in. Valid only in a Framework web-aware Spring ApplicationContext Current PortletContext the Chapter 19. “Additional messages (with support for Capabilities of the parametrization and ApplicationContext” internationalization) JMX notification Section 23. Valid only in a Framework web-aware Spring ApplicationContext Portlet MVC PortletContextAware Portlet MVC ResourceLoaderAware Configured loader for low-level Chapter 5.7.

springframework. as follows: <bean id="inheritedTestBeanWithoutClass" abstract="true"> <property name="name" value="parent"/> <property name="age" value="1"/> </bean> <bean id="inheritsWithClass" class="org. scope.the age property value of 1 will be inherited from </bean> parent --> A child bean definition uses the bean class from the parent definition if none is specified. A child bean definition inherits configuration data from a parent definition.beans.springframework. lazy init.DerivedTestBean" parent="inheritedTestBeanWithoutClass" init-method="initialize"> 3. destroy method. The remaining settings are always taken from the child definition: depends on.beans. <bean id="inheritedTestBean" abstract="true" class="org.1 Reference Documentation 86 . static factory method name.Spring Framework 4. including constructor arguments. If you work with an ApplicationContext interface programmatically. that is. Any initialization method. and method overrides from the parent. and so on. it must accept the parent's property values. When you use XML-based configuration metadata. property values. with the option to add new values. or add others. autowire mode. child bean definitions are represented by the ChildBeanDefinition class. this is a form of templating. Most users do not work with them on this level. specifying the parent bean as the value of this attribute. A child bean definition inherits constructor argument values. The preceding example explicitly marks the parent bean definition as abstract by using the abstract attribute. but can also override it.7 Bean definition inheritance A bean definition can contain a lot of configuration information. and/or static factory method settings that you specify will override the corresponding parent settings. explicitly marking the parent bean definition as abstract is required. dependency check.DerivedTestBean" parent="inheritedTestBean" init-method="initialize"> <property name="name" value="override"/> <!-. you indicate a child bean definition by using the parent attribute. property values. In the latter case. If the parent definition does not specify a class. Effectively. instead configuring bean definitions declaratively in something like the ClassPathXmlApplicationContext.beans. The child definition can override some values. Using parent and child bean definitions can save a lot of typing. and container-specific information such as initialization method. the child bean class must be compatible with the parent.springframework. as needed.TestBean"> <property name="name" value="parent"/> <property name="age" value="1"/> </bean> <bean id="inheritsWithDifferentClass" class="org. singleton.

the Spring IoC container can be extended by plugging in implementations of special integration interfaces. and you can control the order in which these BeanPostProcessors execute by setting the order property. you must make sure to set the abstract attribute to true. Customizing beans using a BeanPostProcessor The BeanPostProcessor interface defines callback methods that you can implement to provide your own (or override the container's default) instantiation logic. dependency-resolution logic.Spring Framework <property name="name" value="override"/> <!-. 3. an application developer does not need to subclass ApplicationContext implementation classes. When a definition is abstract like this. you can plug in one or more BeanPostProcessor implementations.8 Container Extension Points Typically. Note ApplicationContext pre-instantiates all singletons by default. returns an error. Instead. If you want to implement some custom logic after the Spring container finishes instantiating. and so forth. See also the note below on programmatic registration of BeanPostProcessors Note BeanPostProcessors operate on bean (or object) instances. You can configure multiple BeanPostProcessor instances.1 Reference Documentation 87 . 4. it is important (at least for singleton beans) that if you have a (parent) bean definition which you intend to use only as a template. by referring to it as a ref property of another bean or doing an explicit getBean() call with the parent bean id. Similarly. configuring. otherwise the application context will actually (attempt to) pre-instantiate the abstract bean. the Spring IoC container instantiates a bean instance and then BeanPostProcessors do their work. and this definition specifies a class. consult the Javadoc for the BeanPostProcessor and Ordered interfaces. if you write your own BeanPostProcessor you should consider implementing the Ordered interface too. Trying to use such an abstract parent bean on its own.age will inherit the value of 1 from the parent bean definition--> </bean> The parent bean cannot be instantiated on its own because it is incomplete. You can set this property only if the BeanPostProcessor implements the Ordered interface. The next few sections describe these integration interfaces. that is to say. the container's internal preInstantiateSingletons() method ignores bean definitions that are defined as abstract. Therefore. it is usable only as a pure template bean definition that serves as a parent definition for child definitions. For further details. and initializing a bean. and it is also explicitly marked as abstract.

All BeanPostProcessors and beans that they reference directly are instantiated on startup.e. as part of the special startup phase of the ApplicationContext.Spring Framework BeanPostProcessors are scoped per-container. The ApplicationContext registers these beans as post-processors so that they can be called later upon bean creation.springframework. BeanPostProcessors and AOP auto-proxying Classes that implement the BeanPostProcessor interface are special and are treated differently by the container. it will only post-process the beans in that container. regardless of any explicit ordering. This can be useful when needing to evaluate conditional logic before registration. beans that are defined in one container are not post-processed by a BeanPostProcessor defined in another container. Here it is the order of registration that dictates the order of execution. even if both containers are part of the same hierarchy.BeanPostProcessor interface consists of exactly two callback methods. Some Spring AOP infrastructure classes are implemented as bean post-processors in order to provide proxy-wrapping logic. you instead need to use a BeanFactoryPostProcessor as described in the section called “Customizing configuration metadata with a BeanFactoryPostProcessor”. This is only relevant if you are using container hierarchies. or even for copying bean post processors across contexts in a hierarchy. all BeanPostProcessors are registered in a sorted 3. Programmatically registering BeanPostProcessors While the recommended approach for BeanPostProcessor registration is through ApplicationContext auto-detection (as described above).beans. An ApplicationContext automatically detects any beans that are defined in the configuration metadata which implement the BeanPostProcessor interface. Next. the post-processor gets a callback from the container both before container initialization methods (such as InitializingBean's afterPropertiesSet() and any declared init method) are called as well as after any bean initialization callbacks.1 Reference Documentation 88 . The post-processor can take any action with the bean instance. it is also possible to register them programmatically against a ConfigurableBeanFactory using the addBeanPostProcessor method. the blueprint that defines the bean). Bean post-processors can be deployed in the container just like any other beans. A bean post-processor typically checks for callback interfaces or may wrap a bean with a proxy. for each bean instance that is created by the container.config.factory. Note also that BeanPostProcessors registered programmatically are always processed before those registered through auto-detection. The org. To change the actual bean definition (i. If you define a BeanPostProcessor in one container. Note however that BeanPostProcessors added programmatically do not respect the Ordered interface.. In other words. including ignoring the callback completely. When such a class is registered as a post-processor with the container.

org/schema/beans" xmlns:xsi="http://www.beans. Find below the custom BeanPostProcessor implementation class definition: package scripting. public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor { // simply return the instantiated bean as-is public Object postProcessBeforeInitialization(Object bean.beans..Spring Framework fashion and applied to all further beans in the container.org/schema/beans/spring-beans-3.xsd"> <lang:groovy id="messenger" script-source="classpath:org/springframework/scripting/groovy/Messenger. import org.org/2001/XMLSchema-instance" xmlns:lang="http://www. // we could potentially return any object reference here. neither BeanPostProcessors nor the beans they reference directly are eligible for auto-proxying..springframework.org/schema/beans http://www. The following examples show how to write. register.factory.org/schema/lang/spring-lang-3. String beanName) throws BeansException { System.xsd http://www. and thus do not have aspects woven into them.BeanPostProcessor. } public Object postProcessAfterInitialization(Object bean.org/schema/lang http://www.springframework. and use BeanPostProcessors in an ApplicationContext."/> </lang:groovy> <!-when the above bean (messenger) is instantiated. Because AOP auto-proxying is implemented as a BeanPostProcessor itself.0.config.springframework.toString()).out. return bean. For any such bean.0. BeanPostProcessor-style This first example illustrates basic usage. import org.springframework.springframework. you should see an informational log message: “Bean foo is not eligible for getting processed by all BeanPostProcessor interfaces (for example: not eligible for auto-proxying)”. Example: Hello World.springframework.springframework.BeansException.org/schema/lang" xsi:schemaLocation="http://www. String beanName) throws BeansException { return bean.println("Bean '" + beanName + "' created : " + bean.springframework. } } <?xml version="1. this custom 3.1 Reference Documentation 89 .groovy"> <lang:property name="message" value="Fiona Apple Is Just So Dreamy.0" encoding="UTF-8"?> <beans xmlns="http://www. The example shows a custom BeanPostProcessor implementation that invokes the toString() method of each bean as it is created by the container and prints the resulting string to the system console.w3.

context.scripting. import org.BeanFactoryPostProcessor.support.springframework.springframework.InstantiationTracingBeanPostProcessor"/> </beans> Notice how the InstantiationTracingBeanPostProcessor is simply defined.getBean("messenger").) The following simple Java application executes the preceding code and configuration: import org.GroovyMessenger@272961 org. and because it is a bean it can be dependency-injected just like any other bean.xml"). public final class Boot { public static void main(final String[] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("scripting/beans.ApplicationContext.GroovyMessenger@272961 Example: The RequiredAnnotationBeanPostProcessor Using callback interfaces or annotations in conjunction with a custom BeanPostProcessor implementation is a common means of extending the Spring IoC container.groovy. import org.config.springframework. and you can control the order in which these BeanFactoryPostProcessors execute by setting the order property. Customizing configuration metadata with a BeanFactoryPostProcessor The next extension point that we will look at is the org. } } The output of the preceding application resembles the following: Bean 'messenger' created : org.beans.factory.ClassPathXmlApplicationContext.scripting. You can configure multiple BeanFactoryPostProcessors. The semantics of this interface are similar to those of the BeanPostProcessor. you can 3.groovy.context. System.println(messenger). that is.Messenger. with one major difference: BeanFactoryPostProcessors operate on the bean configuration metadata.0 dynamic language support is detailed in the chapter entitled Chapter 27. However. Dynamic language support. (The preceding configuration also defines a bean that is backed by a Groovy script.out.Spring Framework BeanPostProcessor implementation will output the fact to the system console --> <bean class="scripting.springframework. It does not even have a name. An example is Spring's RequiredAnnotationBeanPostProcessor — a BeanPostProcessor implementation that ships with the Spring distribution which ensures that JavaBean properties on beans that are marked with an (arbitrary) annotation are actually (configured to be) dependency-injected with a value. Messenger messenger = (Messenger) ctx. The Spring 2.scripting. the Spring IoC container allows BeanFactoryPostProcessors to read the configuration metadata and potentially change it before the container instantiates any beans other than BeanFactoryPostProcessors.springframework.springframework.1 Reference Documentation 90 .

violating the standard container lifecycle. and the Bean(Factory)PostProcessor will be instantiated eagerly even if you set the default-lazy-init attribute to true on the declaration of your <beans /> element.g. Bean definitions in one container will not be post-processed by BeanFactoryPostProcessors in another container.Spring Framework only set this property if the BeanFactoryPostProcessor implements the Ordered interface. the objects that are created from the configuration metadata). then you instead need to use a BeanPostProcessor (described above in the section called “Customizing beans using a BeanPostProcessor”). Example: the PropertyPlaceholderConfigurer You use the PropertyPlaceholderConfigurer to externalize property values from a bean definition in a separate file using the standard Java Properties format. Note If you want to change the actual bean instances (i.e. If you define a BeanFactoryPostProcessor in one container. If you write your own BeanFactoryPostProcessor. you should consider implementing the Ordered interface too.. Also. it will only be applied to the bean definitions in that container. doing so causes premature bean instantiation. A bean factory post-processor is executed automatically when it is declared inside an ApplicationContext. A custom BeanFactoryPostProcessor can also be used. You can deploy these post-processor beans as you would any other bean. to register custom property editors. at the appropriate time. An ApplicationContext automatically detects any beans that are deployed into it that implement the BeanFactoryPostProcessor interface. This may cause negative side effects such as bypassing bean post processing. Note As with BeanPostProcessors. you typically do not want to configure BeanFactoryPostProcessors for lazy initialization. Consult the Javadoc for the BeanFactoryPostProcessor and Ordered interfaces for more details. BeanFactoryPostProcessors are scoped per-container. If no other bean references a Bean(Factory)PostProcessor.getBean()). using BeanFactory. Thus. While it is technically possible to work with bean instances within a BeanFactoryPostProcessor (e. It uses these beans as bean factory post-processors.. This is only relevant if you are using container hierarchies. that post-processor will not get instantiated at all. for example. marking it for lazy initialization will be ignored. such as PropertyOverrideConfigurer and PropertyPlaceholderConfigurer. even if both containers are part of the same hierarchy. in order to apply changes to the configuration metadata that define the container. Doing so enables the person deploying an application to customize environment-specific properties such as database URLs and 3.1 Reference Documentation 91 . Spring includes a number of predefined bean factory post-processors.

The PropertyPlaceholderConfigurer checks for placeholders in most properties and attributes of a bean definition.driverClassName=org. • override (2): Check system properties first. <bean class="org. The values to replace are specified as placeholders of the form ${property-name} which follows the Ant / log4j / JSP EL style.dbcp.url}"/> <property name="username" value="${jdbc.factory.springframework.Spring Framework passwords.password}"/> </bean> The actual values come from another file in the standard Java Properties format: jdbc. where a DataSource with placeholder values is defined. the string ${jdbc. You can customize this behavior by setting the systemPropertiesMode property of the configurer with one of the following three supported integer values: • never (0): Never check system properties • fallback (1): Check system properties if not resolvable in the specified properties files.username=sa jdbc.beans. Consider the following XML-based configuration metadata fragment. it is possible to configure property placeholders with a dedicated configuration element. One or more locations can be provided as a comma-separated list in the location attribute.commons.driverClassName}"/> <property name="url" value="${jdbc.1 Reference Documentation 92 . before trying the specified properties files. the placeholder prefix and suffix can be customized.username} is replaced at runtime with the value 'sa'.username}"/> <property name="password" value="${jdbc.properties"/> </bean> <bean id="dataSource" destroy-method="close" class="org. This is the default. a PropertyPlaceholderConfigurer is applied to the metadata that will replace some properties of the DataSource.config.jdbcDriver jdbc.apache. By default it also checks against the Java System properties if it cannot find a property in the specified properties files.5. With the context namespace introduced in Spring 2.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:com/foo/jdbc. without the complexity or risk of modifying the main XML definition file or files for the container. and the same applies for other placeholder values that match keys in the properties file.properties"/> The PropertyPlaceholderConfigurer not only looks for properties in the Properties file you specify. The example shows properties configured from an external Properties file. This allows 3. Furthermore.BasicDataSource"> <property name="driverClassName" value="${jdbc.hsqldb. At runtime.password=root Therefore.url=jdbc:hsqldb:hsql://production:9002 jdbc. <context:property-placeholder location="classpath:com/foo/jdbc.

foo.1 Reference Documentation 93 . Class name substitution You can use the PropertyPlaceholderConfigurer to substitute class names. which is sometimes useful when you have to pick a particular implementation class at runtime. resembles the PropertyPlaceholderConfigurer.springframework.mysql. due to the overriding mechanism.class}"/> If the class cannot be resolved at runtime to a valid class.driverClassName=com. so it is not immediately obvious from the XML definition file that the override configurer is being used. Properties file configuration lines take this format: beanName.class=com. resolution of the bean fails when it is about to be created. but unlike the latter.beans.DefaultStrategy</value> </property> </bean> <bean id="serviceStrategy" class="${custom. which is during the preInstantiateSingletons() phase of an ApplicationContext for a non-lazy-init bean. In case of multiple PropertyOverrideConfigurer instances that define different values for the same bean property. If an overriding Properties file does not have an entry for a certain bean property. Note that the bean definition is not aware of being overridden.Driver dataSource. 3. Example: the PropertyOverrideConfigurer The PropertyOverrideConfigurer.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:com/foo/strategy. the original definitions can have default values or no values at all for bean properties.properties</value> </property> <property name="properties"> <value>custom.factory. which has driver and url properties.jdbc. the last one wins.property=value For example: dataSource.config. the default context definition is used. another bean factory post-processor.strategy.Spring Framework system properties to override any other property source.strategy. For example: <bean class="org.url=jdbc:mysql:mydb This example file can be used with a container definition that contains a bean called dataSource. Consult the Javadoc for the PropertyPlaceholderConfigurer for more information.

they are not translated into bean references..springframework.fred. depending on whether this factory returns singletons or prototypes.beans. • Class getObjectType(): returns the object type returned by the getObject() method or null if the type is not known in advance. The instance can possibly be shared. In this example. and then plug your custom FactoryBean into the container. foo. the sammy property of the bob property of the fred property of the foo bean is set to the scalar value 123.. With the context namespace introduced in Spring 2. • boolean isSingleton(): returns true if this FactoryBean returns singletons.Spring Framework Compound property names are also supported. Note Specified override values are always literal values. you can create your own FactoryBean..properties"/> Customizing instantiation logic with a FactoryBean Implement the org. it is possible to configure property overriding with a dedicated configuration element: <context:property-override location="classpath:override. The FactoryBean interface is a point of pluggability into the Spring IoC container's instantiation logic.sammy=123 .. This convention also applies when the original value in the XML bean definition specifies a bean reference. If you have complex initialization code that is better expressed in Java as opposed to a (potentially) verbose amount of XML. false otherwise. more than 50 implementations of the FactoryBean interface ship with Spring itself. When you need to ask a container for an actual FactoryBean instance itself instead of the bean it 3.1 Reference Documentation 94 . The FactoryBean interface provides three methods: • Object getObject(): returns an instance of the object this factory creates. as long as every component of the path except the final property being overridden is already non-null (presumably initialized by the constructors).factory.5.bob. The FactoryBean concept and interface is used in a number of places within the Spring Framework.FactoryBean interface for objects that are themselves factories. write the complex initialization inside that class.

Spring 2. For example. The short answer is it depends. furthermore.9 Annotation-based container configuration Are annotations better than XML for configuring Spring? The introduction of annotation-based configurations raised the question of whether this approach is 'better' than XML. Essentially. all configuration styles are supported by the SpringSource Tool Suite. So for a given FactoryBean with an id of myBean. It's worth pointing out that through its JavaConfig option. Spring can accommodate both styles and even mix them together. No matter the choice. whereas. thus the latter configuration will override the former for properties wired through both approaches. or field declaration.0 introduced the possibility of enforcing required properties with the @Required annotation. that the configuration becomes decentralized and harder to control. preface the bean's id with the ampersand symbol (&) when calling the getBean() method of the ApplicationContext. without touching the target components source code and that in terms of tooling. Instead of using XML to describe a bean wiring. However. but they can also be implicitly registered 3.0 added support for JSR-330 (Dependency Injection for Java) annotations contained in the javax. you can register them as individual bean definitions. Spring 2. leading to shorter and more concise configuration. using a BeanPostProcessor in conjunction with annotations is a common means of extending the Spring IoC container. Spring 3. Due to the way they are defined. the @Autowired annotation provides the same capabilities as described in the section called “Autowiring collaborators” but with more fine-grained control and wider applicability.5 made it possible to follow that same general approach to drive Spring's dependency injection. As always.1 Reference Documentation 95 . Some developers prefer having the wiring close to the source while others argue that annotated classes are no longer POJOs and. The long answer is that each approach has its pros and cons. Spring allows annotations to be used in a non-invasive way.Spring Framework produces. An alternative to XML setups is provided by annotation-based configuration which rely on the bytecode metadata for wiring up components instead of angle-bracket declarations. annotations provide a lot of context in their declaration. invoking getBean("&myBean") returns the FactoryBean instance itself. invoking getBean("myBean") on the container returns the product of the FactoryBean. As mentioned in the section called “Example: The RequiredAnnotationBeanPostProcessor”. 4. method. Spring 2. and @PreDestroy.5 also added support for JSR-250 annotations such as @PostConstruct. Note Annotation injection is performed before XML injection. XML excels at wiring up components without touching their source code or recompiling them. the developer moves the configuration into the component class itself by using annotations on the relevant class.inject package such as @Inject and @Named. and usually it is up to the developer to decide which strategy suits her better. Details about those annotations can be found in the relevant section.

“The DispatcherServlet” for more information.2. 3. PersistenceAnnotationBeanPostProcessor.org/schema/beans/spring-beans-3.springframework. CommonAnnotationBeanPostProcessor.w3.. as in the following example: public class SimpleMovieLister { private MovieFinder movieFinder.) Note <context:annotation-config/> only looks for annotations on beans in the same application context in which it is defined.1 Reference Documentation 96 .org/schema/context http://www. } This annotation simply indicates that the affected bean property must be populated at configuration time. it only checks for @Autowired beans in your controllers.springframework.springframework. avoiding NullPointerExceptions or the like later on.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.0" encoding="UTF-8"?> <beans xmlns="http://www. The container throws an exception if the affected bean property has not been populated.springframework. It is still recommended that you put assertions into the bean class itself. See Section 16.movieFinder = movieFinder.org/schema/beans" xmlns:xsi="http://www. through an explicit property value in a bean definition or through autowiring. Doing so enforces those required references and values even when you use the class outside of a container. @Required public void setMovieFinder(MovieFinder movieFinder) { this. and not your services.xsd"> <context:annotation-config/> </beans> (The implicitly registered post-processors include AutowiredAnnotationBeanPostProcessor. if you put <context:annotation-config/> in a WebApplicationContext for a DispatcherServlet. This means that.org/schema/beans http://www. this allows for eager and explicit failure. for example. } // .org/schema/context/spring-context-3.0.xsd http://www. as well as the aforementioned RequiredAnnotationBeanPostProcessor.0..org/schema/context" xsi:schemaLocation="http://www.Spring Framework by including the following tag in an XML-based Spring configuration (notice the inclusion of the context namespace): <?xml version="1.springframework. @Required The @Required annotation applies to bean property setter methods. into an init method.

@Autowired public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) { this. this. } // ....customerPreferenceDao = customerPreferenceDao.1 Reference Documentation 97 . private CustomerPreferenceDao customerPreferenceDao. CustomerPreferenceDao customerPreferenceDao) { this. } Note JSR 330's @Inject annotation can be used in place of Spring's @Autowired annotation in the examples below...movieCatalog = movieCatalog. } You can apply @Autowired to constructors and fields: public class MovieRecommender { @Autowired private MovieCatalog movieCatalog. you can apply the @Autowired annotation to "traditional" setter methods: public class SimpleMovieLister { private MovieFinder movieFinder. } // .movieFinder = movieFinder. } // . private CustomerPreferenceDao customerPreferenceDao.Spring Framework @Autowired As expected. See here for more details You can also apply the annotation to methods with arbitrary names and/or multiple arguments: public class MovieRecommender { private MovieCatalog movieCatalog. } It is also possible to provide all beans of a particular type from the ApplicationContext by adding 3. @Autowired public void prepare(MovieCatalog movieCatalog.customerPreferenceDao = customerPreferenceDao.. @Autowired public void setMovieFinder(MovieFinder movieFinder) { this.

@Autowired(required=false) public void setMovieFinder(MovieFinder movieFinder) { this. MovieCatalog> movieCatalogs) { this.movieCatalogs = movieCatalogs.movieFinder = movieFinder. public class SimpleMovieLister { private MovieFinder movieFinder. } The same applies for typed collections: public class MovieRecommender { private Set<MovieCatalog> movieCatalogs. In that case..... This behavior can be changed as demonstrated below. } Note Only one annotated constructor per-class can be marked as required. the default behavior is to treat annotated methods. } // . // .1 Reference Documentation 98 .movieCatalogs = movieCatalogs.. each is considered among the 3. @Autowired public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) { this. constructors. } By default. } // . } Even typed Maps can be autowired as long as the expected key type is String. the autowiring fails whenever zero candidate beans are available. } // . @Autowired public void setMovieCatalogs(Map<String. MovieCatalog> movieCatalogs. and the keys will contain the corresponding bean names: public class MovieRecommender { private Map<String...Spring Framework the annotation to a field or method that expects an array of that type: public class MovieRecommender { @Autowired private MovieCatalog[] movieCatalogs. The Map values will contain all beans of the expected type. but multiple non-required constructors can be annotated. and fields as indicating required dependencies..

public class MovieRecommender { @Autowired private ApplicationContext context. These types must be 'wired up' explicitly via XML or using a Spring @Bean method. on the other hand. In the simplest case. ResourceLoader.. These interfaces and their extended interfaces. } Note @Autowired. with no special setup necessary. and @Value annotations are handled by a Spring BeanPostProcessor implementations which in turn means that you cannot apply these annotations within your own BeanPostProcessor or BeanFactoryPostProcessor types (if any). this can be a plain descriptive value: public class MovieRecommender { @Autowired @Qualifier("main") private MovieCatalog movieCatalog. are automatically resolved. and MessageSource. The required attribute indicates that the property is not required for autowiring purposes. is stronger in that it enforces the property that was set by any means supported by the container. If no value is injected. it is often necessary to have more control over the selection process. @Resource.1 Reference Documentation 99 . narrowing the set of type matches so that a specific bean is chosen for each argument. You can associate qualifier values with specific arguments. public MovieRecommender() { } // . @Autowired's required attribute is recommended over the @Required annotation. You can also use @Autowired for interfaces that are well-known resolvable dependencies: BeanFactory. @Inject. @Required. } 3. that is the constructor that has the largest number of arguments. Fine-tuning annotation-based autowiring with qualifiers Because autowiring by type may lead to multiple candidates.. ApplicationContext. Environment.Spring Framework candidates and Spring uses the greediest constructor whose dependencies can be satisfied. such as ConfigurableApplicationContext or ResourcePatternResolver... a corresponding exception is raised. // . One way to accomplish this is with Spring's @Qualifier annotation. ApplicationEventPublisher. the property is ignored if it cannot be autowired.

Good qualifier values are "main" or "EMEA" or "persistent".org/schema/context/spring-context-3.org/schema/context http://www.springframework.springframework..Spring Framework The @Qualifier annotation can also be specified on individual constructor arguments or method parameters: public class MovieRecommender { private MovieCatalog movieCatalog. The bean with qualifier value "main" is wired with the constructor argument that is qualified with the same value. the bean name is considered a default qualifier value.xsd http://www. @Autowired public void prepare(@Qualifier("main") MovieCatalog movieCatalog. this.customerPreferenceDao = customerPreferenceDao.0. @Autowired is fundamentally about type-driven injection with optional semantic qualifiers.org/schema/beans/spring-beans-3. they do not semantically express a reference to a unique bean id. } The corresponding bean definitions appear as follows.springframework.w3. <?xml version="1. to Set<MovieCatalog>. private CustomerPreferenceDao customerPreferenceDao. leading to the same matching result.MovieRecommender"/> </beans> For a fallback match.. Thus you can define the bean with an id "main" instead of the nested qualifier element.movieCatalog = movieCatalog.org/schema/beans http://www.springframework. even with the bean name fallback.org/2001/XMLSchema-instance" xmlns:context="http://www.inject any dependencies required by this bean --> </bean> <bean class="example.org/schema/context" xsi:schemaLocation="http://www.org/schema/beans" xmlns:xsi="http://www.inject any dependencies required by this bean --> </bean> <bean id="movieRecommender" class="example. expressing characteristics of a specific component that are independent from the bean id.xsd"> <context:annotation-config/> <bean class="example. for example. although you can use this convention to refer to specific beans by name. CustomerPreferenceDao customerPreferenceDao) { this.springframework.SimpleMovieCatalog"> <qualifier value="action"/> <!-. 3. Qualifiers also apply to typed collections.1 Reference Documentation 100 .0" encoding="UTF-8"?> <beans xmlns="http://www.SimpleMovieCatalog"> <qualifier value="main"/> <!-. as discussed above. This means that qualifier values. always have narrowing semantics within the set of type matches.springframework.0. which may be auto-generated in case of an anonymous bean definition like the one in the preceding example. } // . However.

@Autowired public void setComedyCatalog(@Genre("Comedy") MovieCatalog comedyCatalog) { this. Tip If you intend to express annotation-driven injection by name.comedyCatalog = comedyCatalog. referring to the specific collection or map bean by unique name. This implies that qualifiers do not have to be unique. all matching beans according to the declared qualifiers are injected as a collection. ElementType.. By contrast.. As a specific consequence of this semantic difference. they rather simply constitute filtering criteria. because type matching is not properly applicable to them. @Autowired applies to fields. all of which would be injected into a Set<MovieCatalog> annotated with @Qualifier("action"). } // . As a consequence.RUNTIME) @Qualifier public @interface Genre { String value(). } 3. } Then you can provide the custom qualifier on autowired fields and parameters: public class MovieRecommender { @Autowired @Genre("Action") private MovieCatalog actionCatalog. do not primarily use @Autowired. You can create your own custom qualifier annotations. you can define multiple MovieCatalog beans with the same qualifier value "action".1 Reference Documentation 101 . Simply define an annotation and provide the @Qualifier annotation within your definition: @Target({ElementType. use the JSR-250 @Resource annotation.FIELD. with the declared type being irrelevant for the matching process. @Resource is supported only for fields and bean property setter methods with a single argument. which is semantically defined to identify a specific target component by its unique name. even if is technically capable of referring to a bean name through @Qualifier values. and multi-argument methods. constructors. private MovieCatalog comedyCatalog. allowing for narrowing through qualifier annotations at the parameter level.PARAMETER}) @Retention(RetentionPolicy. Use @Resource for such beans. beans that are themselves defined as a collection or map type cannot be injected through @Autowired. Instead. stick with qualifiers if your injection target is a constructor or a multi-argument method. For example.Spring Framework In this case.

org/schema/beans/spring-beans-3.SimpleMovieCatalog"> <qualifier type="example. Specifically. see the section called “Providing qualifier metadata with annotations”.org/schema/context http://www.MovieRecommender"/> </beans> In Section 4.FIELD. “Classpath scanning and managed components”.springframework. it may be sufficient to use an annotation without a value.springframework.RUNTIME) @Qualifier public @interface Offline { } Then add the annotation to the field or property to be autowired: public class MovieRecommender { @Autowired @Offline private MovieCatalog offlineCatalog.springframework. } 3.SimpleMovieCatalog"> <qualifier type="Genre" value="Action"/> <!-.springframework.inject any dependencies required by this bean --> </bean> <bean id="movieRecommender" class="example.xsd"> <context:annotation-config/> <bean class="example.0" encoding="UTF-8"?> <beans xmlns="http://www.1 Reference Documentation 102 .10.org/schema/beans http://www.org/2001/XMLSchema-instance" xmlns:context="http://www.Spring Framework Next.springframework.org/schema/beans" xmlns:xsi="http://www. In some cases. For example.0.. you can use the short class name. you may provide an offline catalog that would be searched when no Internet connection is available. The type is matched against the fully-qualified class name of the annotation.springframework.org/schema/context" xsi:schemaLocation="http://www. Both approaches are demonstrated in the following example.org/schema/context/spring-context-3. // . provide the information for the candidate bean definitions. ElementType. <?xml version="1. First define the simple annotation: @Target({ElementType. Or. You can add <qualifier/> tags as sub-elements of the <bean/> tag and then specify the type and value to match your custom qualifier annotations.inject any dependencies required by this bean --> </bean> <bean class="example.w3.xsd http://www.. This may be useful when the annotation serves a more generic purpose and can be applied across several different types of dependencies. as a convenience if no risk of conflicting names exists.PARAMETER}) @Retention(RetentionPolicy. you will see an annotation-based alternative to providing the qualifier metadata in XML.0.Genre" value="Comedy"/> <!-.

@Autowired @MovieQualifier(format=Format. This example also demonstrates that bean meta attributes may be used instead of the <qualifier/> sub-elements. // . a bean definition must match all such attribute values to be considered an autowire candidate.SimpleMovieCatalog"> <qualifier type="Offline"/> <!-. @Autowired @MovieQualifier(format=Format. genre="Action") private MovieCatalog actionDvdCatalog. public class MovieRecommender { @Autowired @MovieQualifier(format=Format. the <qualifier/> and its attributes take precedence. genre="Comedy") private MovieCatalog comedyVhsCatalog. genre="Comedy") private MovieCatalog comedyBluRayCatalog.inject any dependencies required by this bean --> </bean> You can also define custom qualifier annotations that accept named attributes in addition to or instead of the simple value attribute. @Autowired @MovieQualifier(format=Format.. genre="Action") private MovieCatalog actionVhsCatalog.DVD. ElementType. As an example.Spring Framework Now the bean definition only needs a qualifier type: <bean class="example. If available.PARAMETER}) @Retention(RetentionPolicy. DVD. } Finally.VHS.FIELD. but the autowiring mechanism falls back on the values provided within the <meta/> tags if no such qualifier is present..1 Reference Documentation 103 . consider the following annotation definition: @Target({ElementType. as in the last two bean 3.RUNTIME) @Qualifier public @interface MovieQualifier { String genre(). If multiple attribute values are then specified on a field or parameter to be autowired. the bean definitions should contain matching qualifier values. } In this case Format is an enum: public enum Format { VHS.BLURAY. Format format(). BLURAY } The fields to be autowired are annotated with the custom qualifier and include values for both attributes: genre and format.VHS.

Spring Framework definitions in the following example.xsd"> <context:annotation-config/> <bean class="example.inject any dependencies required by this bean --> </bean> <bean class="example. In versions earlier than Java 5.springframework.org/schema/context/spring-context-3.inject any dependencies required by this bean --> </bean> <bean class="example.inject any dependencies required by this bean --> </bean> </beans> CustomAutowireConfigurer The CustomAutowireConfigurer is a BeanFactoryPostProcessor that enables you to register your own custom qualifier annotation types even if they are not annotated with Spring's @Qualifier annotation.inject any dependencies required by this bean --> </bean> <bean class="example.org/schema/beans/spring-beans-3.org/schema/context" xsi:schemaLocation="http://www. <?xml version="1.xsd http://www.CustomQualifier</value> </set> </property> </bean> The particular implementation of AutowireCandidateResolver that is activated for the application context depends on the Java version.w3.org/schema/context http://www.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans http://www.factory.annotation.SimpleMovieCatalog"> <meta key="format" value="DVD"/> <meta key="genre" value="Action"/> <!-.SimpleMovieCatalog"> <qualifier type="MovieQualifier"> <attribute key="format" value="VHS"/> <attribute key="genre" value="Action"/> </qualifier> <!-.SimpleMovieCatalog"> <qualifier type="MovieQualifier"> <attribute key="format" value="VHS"/> <attribute key="genre" value="Comedy"/> </qualifier> <!-.org/schema/beans" xmlns:xsi="http://www.0.springframework.beans. the qualifier annotations 3.springframework.SimpleMovieCatalog"> <meta key="format" value="BLURAY"/> <meta key="genre" value="Comedy"/> <!-.springframework. <bean id="customAutowireConfigurer" class="org.1 Reference Documentation 104 .CustomAutowireConfigurer"> <property name="customQualifierTypes"> <set> <value>example.springframework.0.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.

2 managed beans or JAX-WS 2. it follows by-name semantics. @Resource Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods.Spring Framework are not supported.1 Reference Documentation 105 . it takes the bean property name. for example in JSF 1.movieFinder = movieFinder. the determination of a "primary" candidate is the same: if exactly one bean definition among the candidates has a primary attribute set to true. This is a common pattern in Java EE 5 and 6. } } If no name is specified explicitly.0 endpoints. the default name is derived from the field name or setter method. @Resource(name="myMovieFinder") public void setMovieFinder(MovieFinder movieFinder) { this. it takes the field name. it is recommended that you rely on the default behavior and simply use Spring's JNDI lookup capabilities to preserve the level of indirection. In other words. as demonstrated in this example: public class SimpleMovieLister { private MovieFinder movieFinder. In case of a field. The names can be resolved through JNDI if you configure Spring's SimpleJndiBeanFactory explicitly. @Resource takes a name attribute. the presence of @Qualifier annotations and any custom annotations registered with the CustomAutowireConfigurer will also play a role. So the following example is going to have the bean with name "movieFinder" injected into its setter method: public class SimpleMovieLister { private MovieFinder movieFinder. when multiple beans qualify as autowire candidates. in case of a setter method. 3. Spring supports this pattern for Spring-managed objects as well. However. and by default Spring interprets that value as the bean name to be injected. } } Note The name provided with the annotation is resolved as a bean name by the ApplicationContext of which the CommonAnnotationBeanPostProcessor is aware.movieFinder = movieFinder. and therefore autowire candidates are solely determined by the autowire-candidate value of each bean definition as well as by any default-autowire-candidates pattern(s) available on the <beans/> element. @Resource public void setMovieFinder(MovieFinder movieFinder) { this. Regardless of the Java version. In Java 5 or later. it will be selected.

} @PreDestroy public void clearMovieCache() { // clears the movie cache upon destruction. the support for these annotations offers yet another alternative to those described in initialization callbacks and destruction callbacks.Spring Framework In the exclusive case of @Resource usage with no explicit name specified. Introduced in Spring 2.. @Resource finds a primary type match instead of a specific named bean and resolves well-known resolvable dependencies: the BeanFactory. The "context" field is injected based on the known resolvable dependency type ApplicationContext. and similar to @Autowired. a method carrying one of these annotations is invoked at the same point in the lifecycle as the corresponding Spring lifecycle interface method or explicitly declared callback method. public class CachingMovieLister { @PostConstruct public void populateMovieCache() { // populates the movie cache upon initialization. and MessageSource interfaces. public MovieRecommender() { } // . ApplicationEventPublisher.5. the customerPreferenceDao field first looks for a bean named customerPreferenceDao. see the section called “Combining lifecycle mechanisms”. ApplicationContext.. the cache will be pre-populated upon initialization and cleared upon destruction.. then falls back to a primary type match for the type CustomerPreferenceDao. } } Note For details about the effects of combining various lifecycle mechanisms. @Resource private ApplicationContext context.1 Reference Documentation 106 . Provided that the CommonAnnotationBeanPostProcessor is registered within the Spring ApplicationContext. } @PostConstruct and @PreDestroy The CommonAnnotationBeanPostProcessor not only recognizes the @Resource annotation but also the JSR-250 lifecycle annotations.. In the example below. public class MovieRecommender { @Resource private CustomerPreferenceDao customerPreferenceDao.. Thus in the following example.. ResourceLoader. 3.

@Service. Similarly. and @Controller may carry additional semantics in future releases of the Spring Framework. @Service. while the annotations only drive the dependency injection. Note Starting with Spring 3. respectively. @Service. service. in the persistence. Therefore. for example. however. AspectJ type expressions. Spring 2. as stated above. these stereotype annotations make ideal targets for pointcuts.10 Classpath scanning and managed components Most examples in this chapter use XML to specify the configuration metadata that produces each BeanDefinition within the Spring container. Automatically detecting classes and registering bean definitions Spring can automatically detect stereotyped classes and register corresponding BeanDefinitions with the ApplicationContext. @Repository is already supported as a marker for automatic exception translation in your persistence layer. your classes are more properly suited for processing by tools or associating with aspects. “Annotation-based container configuration”) demonstrates how to provide a lot of the configuration metadata through source-level annotations. The previous section (Section 4. This section describes an option for implicitly detecting the candidate components by scanning the classpath. but by annotating them with @Repository.1 Reference Documentation 107 . For example. Among the uses of this marker is the automatic translation of exceptions as described in the section called “Exception translation”. the "base" bean definitions are explicitly defined in the XML file. and presentation layers. Candidate components are classes that match against a filter criteria and have a corresponding bean definition registered with the container.0. Take a look at the @Configuration.Spring Framework 4.0 and later. if you are choosing between using @Component or @Service for your service layer. and @Controller. the following two classes are eligible for such 3. This removes the need to use XML to perform bean registration. instead you can use annotations (for example @Component).5 introduces further stereotype annotations: @Component. many features provided by the Spring JavaConfig project are part of the core Spring Framework.9. It is also possible that @Repository. Thus. @Component is a generic stereotype for any Spring-managed component. @Component and further stereotype annotations In Spring 2. @Service. Even in those examples. This allows you to define beans using Java rather than using the traditional XML files. and @DependsOn annotations for examples of how to use these new features. @Bean. @Repository. or @Controller instead. you can annotate your component classes with @Component. @Import. or your own custom filter criteria to select which classes will have bean definitions registered with the container. @Service is clearly the better choice. For example. the @Repository annotation is a marker for any class that fulfills the role or stereotype (also known as Data Access Object or DAO) of a repository. and @Controller are specializations of @Component for more specific use cases.

the AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor are both included implicitly when you use the component-scan element.springframework. That means that the two components are autodetected and wired together .1 Reference Documentation 108 .org/schema/beans/spring-beans-3.org/schema/beans" xmlns:xsi="http://www.Spring Framework autodetection: @Service public class SimpleMovieLister { private MovieFinder movieFinder.0. make sure that you do not activate the files-only switch of the JAR task.springframework.movieFinder = movieFinder.) <?xml version="1.example"/> </beans> Note The scanning of classpath packages requires the presence of corresponding directory entries in the classpath.org/2001/XMLSchema-instance" xmlns:context="http://www. you need to include the following element in XML.springframework.org/schema/beans http://www.org/schema/context" xsi:schemaLocation="http://www.org/schema/context http://www.0" encoding="UTF-8"?> <beans xmlns="http://www.xsd http://www. 3.springframework. @Autowired public SimpleMovieLister(MovieFinder movieFinder) { this.xsd"> <context:component-scan base-package="org. (Alternatively.all without any bean configuration metadata provided in XML.org/schema/context/spring-context-3. } } @Repository public class JpaMovieFinder implements MovieFinder { // implementation elided for clarity } To autodetect these classes and register the corresponding beans.w3.springframework. Note You can disable the registration of AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor by including the annotation-config attribute with a value of false.0. When you build JARs with Ant. Furthermore. where the base-package element is a common parent package for the two classes. you can specify a comma-separated list that includes the parent package of each class.springframework.

example\. @Controller. The following table describes the filtering options. you can modify and extend this behavior simply by applying custom filters. org.springframework. A custom implementation of org.stereotype.*Stub. However. A regex expression to be matched by the target components class names.MyTypeFilter The following example shows the XML configuration ignoring all @Repository annotations and using "stub" repositories instead.Spring Framework Using filters to customize scanning By default.* org.Default. Filter Types Filter Type annotation assignable aspectj regex custom Example Expression Description org.core.example. This will in effect disable automatic detection of classes annotated with @Component. @Repository.example.SomeAnnotation An annotation to be present at the type level in target components. or @Controller. Table 4..TypeFilter interface.*Repository"/> <context:exclude-filter type="annotation" expression="org. @Repository.5. @Service.type .SomeClass A class (or interface) that the target components are assignable to (extend/implement). An AspectJ type expression to be matched by the target components.example"> <context:include-filter type="regex" expression=". Each filter element requires the type and expression attributes. @Service.Repository"/> </context:component-scan> </beans> Note You can also disable the default filters by providing use-default-filters="false" as an attribute of the <component-scan/> element. <beans> <context:component-scan base-package="org.example. or a custom annotation that itself is annotated with @Component are the only detected candidate components.1 Reference Documentation 109 . the org.example.springframework.*Service+ org\. classes annotated with @Component. 3. Add them as include-filter or exclude-filter sub-elements of the component-scan element.

3). Autowired fields and methods are supported as previously discussed. return tb. with additional support for autowiring of @Bean methods: @Component public class FactoryMethodComponent { private static int i.SCOPE_SESSION. such as a qualifier value through the @Qualifier annotation. } } 3. proxyMode = ScopedProxyMode. } public void doWork() { // Component method implementation omitted } } This class is a Spring component that has application-specific code contained in its doWork() method.setCountry(country). tb. i++). The @Bean annotation identifies the factory method and other bean definition properties. @Lazy. @Value("#{privateInstance. and custom qualifier annotations. Other method level annotations that can be specified are @Scope. it also contributes a bean definition that has a factory method referring to the method publicInstance(). Here is a simple example: @Component public class FactoryMethodComponent { @Bean @Qualifier("public") public TestBean publicInstance() { return new TestBean("publicInstance").setSpouse(tb). 1). } // use of a custom qualifier and autowiring of method parameters @Bean protected TestBean protectedInstance(@Qualifier("public") TestBean spouse. @Bean @Qualifier("public") public TestBean publicInstance() { return new TestBean("publicInstance").1 Reference Documentation 110 . } @Bean @Scope(value = WebApplicationContext.age}") String country) { TestBean tb = new TestBean("protectedInstance".TARGET_CLASS) public TestBean requestScopedInstance() { return new TestBean("requestScopedInstance". tb.Spring Framework Defining bean metadata within components Spring components can also contribute bean definition metadata to the container. } @Bean @Scope(BeanDefinition. You do this with the same @Bean annotation used to define bean metadata within @Configuration annotated classes.SCOPE_SINGLETON) private TestBean privateInstance() { return new TestBean("privateInstance". However.

@Service. and @Controller) that contains a name value will thereby provide that name to the corresponding bean definition. @Repository. any Spring stereotype annotation (@Component. If such an annotation contains no name value or for any other detected component (such as those discovered by custom filters). Then. you can provide a custom bean-naming strategy.MyNameGenerator" /> </beans> 3.Spring Framework The example autowires the String method parameter country to the value of the Age property on another bean named privateInstance. CGLIB proxying is the means by which invoking methods or fields within @Configuration classes @Bean methods create bean metadata references to collaborating objects. the names would be myMovieLister and movieFinderImpl: @Service("myMovieLister") public class SimpleMovieLister { // .1 Reference Documentation 111 . Naming autodetected components When a component is autodetected as part of the scanning process. if the following two components were detected. Methods are not invoked with normal Java semantics... its bean name is generated by the BeanNameGenerator strategy known to that scanner. } @Repository public class MovieFinderImpl implements MovieFinder { // . calling a method or field within a @Component classes @Bean method has standard Java semantics.. an expression resolver is preconfigured to look for bean names when resolving expression text.example. provide the fully-qualified class name when configuring the scanner: <beans> <context:component-scan base-package="org. By default. For example.example" name-generator="org. In contrast. and be sure to include a default no-arg constructor. the default bean name generator returns the uncapitalized non-qualified class name. The @Bean methods in a Spring component are processed differently than their counterparts inside a Spring @Configuration class. } Note If you do not want to rely on the default bean-naming strategy. implement the BeanNameGenerator interface. The difference is that @Component classes are not enhanced with CGLIB to intercept the invocation of methods and fields. For @Value annotations. A Spring Expression Language element defines the value of the property through the notation #{ <expression> }. First..

Spring Framework As a general rule. sometimes you need other scopes. it may be necessary to generate proxies for the scoped objects. the auto-generated names are adequate whenever the container is responsible for wiring. and targetClass. For this purpose. However.1 Reference Documentation 112 . Providing a scope for autodetected components As with Spring-managed components in general. The reasoning is described in the section called “Scoped beans as dependencies”. a scoped-proxy attribute is available on the component-scan element.example" scoped-proxy="interfaces" /> </beans> Providing qualifier metadata with annotations The @Qualifier annotation is discussed in the section called “Fine-tuning annotation-based autowiring with qualifiers”.. For example. the following configuration will result in standard JDK dynamic proxies: <beans> <context:component-scan base-package="org. provide the fully-qualified class name when configuring the scanner: <beans> <context:component-scan base-package="org. Then. } Note To provide a custom strategy for scope resolution rather than relying on the annotation-based approach.example" scope-resolver="org.MyScopeResolver" /> </beans> When using certain non-singleton scopes.. The examples in that section demonstrate the use of the @Qualifier annotation and custom qualifier annotations to provide fine-grained control when you resolve autowire candidates.example. 3. and be sure to include a default no-arg constructor. the default and most common scope for autodetected components is singleton. On the other hand. which Spring 2. interfaces. implement the ScopeMetadataResolver interface. Simply provide the name of the scope within the annotation: @Scope("prototype") @Repository public class MovieFinderImpl implements MovieFinder { // . consider specifying the name with the annotation whenever other components may be making explicit references to it. The three possible values are: no.5 provides with a new @Scope annotation.

1 Reference Documentation 113 . } Note As with most annotation-based alternatives. The following three examples demonstrate this technique: @Component @Qualifier("Action") public class ActionMovieCatalog implements MovieCatalog { // .inject artifact is available in the standard Maven repository (http://repo1. keep in mind that the annotation metadata is bound to the class definition itself. Note If you are using Maven. When relying upon classpath scanning for autodetection of components.org/maven2/javax/inject/javax.maven...11 Using JSR 330 Standard Annotations Starting with Spring 3. Those annotations are scanned in the same way as the Spring annotations. Spring offers support for JSR-330 standard annotations (Dependency Injection).inject/1/). you provide the qualifier metadata with type-level annotations on the candidate class. You just need to have the relevant jars in your classpath... } @Component @Genre("Action") public class ActionMovieCatalog implements MovieCatalog { // .xml: <dependency> <groupId>javax. because that metadata is provided per-instance rather than per-class..inject</artifactId> <version>1</version> </dependency> 3. } @Component @Offline public class CachingMovieCatalog implements MovieCatalog { // .inject</groupId> <artifactId>javax. the qualifier metadata was provided on the candidate bean definitions using the qualifier or meta sub-elements of the bean element in the XML.0. the javax. 4..Spring Framework Because those examples were based on XML bean definitions. while the use of XML allows for multiple beans of the same type to provide variations in their qualifier metadata. You can add the following dependency to your file pom.

Named. } As with @Autowired. } It is very common to use @Component without specifying a name for the component.Inject.. If you would like to use a qualified name for the dependency that should be injected.Named. @javax. field-level. } // .movieFinder = movieFinder. @Inject public void setMovieFinder(@Named("main") MovieFinder movieFinder) { this.Named may be used as follows: import javax.Inject. you should use the @Named annotation as follows: import javax. @Named("movieListener") public class SimpleMovieLister { private MovieFinder movieFinder.inject.movieFinder = movieFinder.inject.. public class SimpleMovieLister { private MovieFinder movieFinder.Inject.. } // .1 Reference Documentation 114 ...inject. } @Named: a standard equivalent to the @Component annotation Instead of @Component. @Inject public void setMovieFinder(MovieFinder movieFinder) { this. public class SimpleMovieLister { private MovieFinder movieFinder. method-level and constructor-argument level.inject.Inject may be used as follows: import javax.Spring Framework Dependency Injection with @Inject and @Named Instead of @Autowired. import javax.movieFinder = movieFinder. @Inject public void setMovieFinder(MovieFinder movieFinder) { this.. } // .inject.inject.inject. @Named can be used in a similar fashion: 3. it is possible to use @Inject at the class-level. import javax. @javax.

In order to use a scope other than singleton.6. import javax.example"/> </beans> Limitations of the standard approach When working with standard annotations.inject restrictions / comments @Inject has no 'required' attribute — 3. Nevertheless. it is possible to use component-scanning in the exact same way as when using Spring annotations: <beans> <context:component-scan base-package="org..1 Reference Documentation 115 . it is important to know that some significant features are not available as shown in the table below: Table 4. However. in order to keep it consistent with Spring's general defaults. Spring annotations vs. @Named public class SimpleMovieLister { private MovieFinder movieFinder.* @Inject @Named @Singleton The JSR-330 default scope is like Spring's prototype. a JSR-330 bean declared in the Spring container is a singleton by default.inject also provides a @Scope annotation.Spring Framework import javax.movieFinder = movieFinder. you should use Spring's @Scope annotation.inject. this one is only intended to be used for creating your own annotations. } // .inject. @Inject public void setMovieFinder(MovieFinder movieFinder) { this.inject. } When using @Named.Inject. javax. standard annotations Spring @Autowired @Component @Scope("singleton") javax.Named. @Qualifier @Value @Named — — no equivalent javax..

Instantiating the Spring container using AnnotationConfigApplicationContext The sections below document Spring's AnnotationConfigApplicationContext. The simplest possible @Configuration class would read as follows: @Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl().* — — javax.acme.0. These classes consist principally of @Bean-annotated methods that define instantiation. and initialization logic for objects to be managed by the Spring IoC container. however.12 Java-based container configuration Basic concepts: @Configuration and @Bean The central artifact in Spring's new Java-configuration support is the @Configuration-annotated class. new in Spring 3. we'll cover the various ways of creating a spring container using Java-based configuration. The @Bean annotation will be discussed in depth in the sections below.inject. Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. } } For those more familiar with Spring <beans/> XML. but also plain @Component classes and classes annotated with JSR-330 metadata. When @Configuration classes are provided as input. the @Bean annotation plays the same role as the <bean/> element. First. configuration. the @Configuration class itself is 3.Spring Framework Spring @Required @Lazy javax.services.MyServiceImpl"/> </beans> As you can see. This versatile ApplicationContext implementation is capable of accepting not only @Configuration classes as input. the AppConfig class above would be equivalent to: <beans> <bean id="myService" class="com.1 Reference Documentation 116 .inject restrictions / comments no equivalent no equivalent 4.

class).) Experienced Spring users will be familiar with the following commonly-used XML declaration from Spring's context: namespace <beans> 3. } As mentioned above.class). Dependency1.getBean(MyService.. Simple construction In much the same way that Spring XML files are used as input when instantiating a ClassPathXmlApplicationContext.. myService. This approach is particularly useful when programmatically building an AnnotationConfigApplicationContext. myService. myService.class).getBean(MyService.1 Reference Documentation 117 . MyService myService = ctx.class.class).doStuff(). Building the container programmatically using register(Class<?>. OtherConfig. public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext().doStuff()..) An AnnotationConfigApplicationContext may be instantiated using a no-arg constructor and then configured using the register() method.Spring Framework registered as a bean definition. Depen MyService myService = ctx.register(AppConfig.getBean(MyService. and it is assumed that DI metadata such as @Autowired or @Inject are used within those classes where necessary. ctx.refresh(). } The above assumes that MyServiceImpl. When @Component and JSR-330 classes are provided.register(AdditionalConfig.class). ctx.doStuff(). and all declared @Bean methods within the class are also registered as bean definitions. they are registered as bean definitions.class. @Configuration classes may be used as input when instantiating an AnnotationConfigApplicationContext. AnnotationConfigApplicationContext is not limited to working only with @Configuration classes. For example: public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl. ctx. } Enabling component scanning with scan(String. MyService myService = ctx.. Any @Component or JSR-330 annotated class may be supplied as input to the constructor. This allows for completely XML-free usage of the Spring container: public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class. Dependency1 and Dependency2 use Spring dependency injection annotations such as @Autowired.class).

refresh().AnnotationConfigWebApplicationContext </param-value> </context-param> <!-.or space-delimited fully-qualified @Configuration classes.Spring Framework <context:component-scan base-package="com.support.springframework.acme. Support for web applications with AnnotationConfigWebApplicationContext A WebApplicationContext variant of AnnotationConfigApplicationContext is available with AnnotationConfigWebApplicationContext.web.class).AppConfig</param-value> </context-param> <!-. etc.scan("com.web.context. } Note Remember that @Configuration classes are meta-annotated with @Component.Declare a Spring MVC DispatcherServlet as usual --> 3.xml snippet that configures a typical Spring MVC web application.) method to allow for the same component-scanning functionality: public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext().acme package (or any package underneath). ctx. the com.. This implementation may be used when configuring the Spring ContextLoaderListener servlet listener.Bootstrap the root application context as usual using ContextLoaderListener --> <listener> <listener-class>org.acme"/> </beans> In the example above. and those classes will be registered as Spring bean definitions within the container.getBean(MyService. Spring MVC DispatcherServlet. Note the use of the contextClass context-param and init-param: <web-app> <!-. What follows is a web. MyService myService = ctx.Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext --> <context-param> <param-name>contextClass</param-name> <param-value> org. looking for any @Component-annotated classes. AnnotationConfigApplicationContext exposes the scan(String. it will be picked up during the call to scan(). and upon refresh() all its @Bean methods will be processed and registered as bean definitions within the container.ContextLoaderListener</listener-class> </listener> <!-.1 Reference Documentation 118 . so they are candidates for component-scanning! In the example above.Configuration locations must consist of one or more comma.acme").. Fully-qualified packages may also be specified for component-scanning --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>com.context.acme package will be scanned.springframework. ctx. assuming that AppConfig is declared within the com.

AnnotationConfigWebApplicationContext </param-value> </init-param> <!-. rather than requiring the developer to remember a potentially large number of @Configuration classes during construction.class when instantiating the context.MvcConfig</param-value> </init-param> </servlet> <!-. 3. } } Now.1 Reference Documentation 119 . A a = ctx.web.servlet..acme.DispatcherServlet</servlet-class> <!-.Again.support.or space-delimited and fully-qualified @Configuration classes --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>com.web.getBean(B. // now both beans A and B will be available.Configure DispatcherServlet to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext --> <init-param> <param-name>contextClass</param-name> <param-value> org.class) public class ConfigB { public @Bean B b() { return new B(). as only one class needs to be dealt with.class). rather than needing to specify both ConfigA.class and ConfigB. the @Import annotation allows for loading @Bean definitions from another configuration class: @Configuration public class ConfigA { public @Bean A a() { return new A(). } This approach simplifies container instantiation.web.class).Spring Framework <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.context.springframework.getBean(A.springframework. only ConfigB needs to be supplied explicitly: public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB..map all requests for /app/* to the dispatcher servlet --> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/app/*</url-pattern> </servlet-mapping> </web-app> Composing Java-based configurations Using the @Import annotation Much as the <import/> element is used within Spring XML files to aid in modularizing configurations. config locations must consist of one or more comma.class). B b = ctx. } } @Configuration @Import(ConfigA.

"C456"). Remember that @Configuration classes are ultimately just another bean in the container . For example. because there is no compiler involved. Fortunately.class). public @Bean AccountRepository accountRepository() { return new JdbcAccountRepository(dataSource). } } @Configuration @Import({ServiceConfig.00.class}) public class SystemTestConfig { public @Bean DataSource dataSource() { /* return new DataSource */ } } public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(SystemTestConfig.getBean(TransferService. each depending on beans declared in the others: @Configuration public class ServiceConfig { private @Autowired AccountRepository accountRepository. // everything wires up across configuration classes. When using XML. transferService.. when using @Configuration classes. how do you know exactly where the @Autowired AccountRepository bean is declared? It's not explicit in the code. per se. and one can simply declare ref="someBean" and trust that Spring will work it out during container initialization. } Fully-qualifying imported beans for ease of navigation In the scenario above.Spring Framework Injecting dependencies on imported @Bean definitions The example above works. and will quickly show you the location of 3.class). the Java compiler places constraints on the configuration model. this is not an issue. Of course.that may be all you need.transfer(100. in that references to other beans must be valid Java syntax. } } @Configuration public class RepositoryConfig { private @Autowired DataSource dataSource. public @Bean TransferService transferService() { return new TransferServiceImpl(accountRepository).1 Reference Documentation 120 . and this may be just fine.class. TransferService transferService = ctx. as a developer looking at ServiceConfig.this means that they can take advantage of @Autowired injection metadata just like any other bean! Let's consider a more real-world scenario with several @Configuration classes. RepositoryConfig. "A123". but is simplistic. Remember that the SpringSource Tool Suite provides tooling that can render graphs showing how everything is wired up . your Java IDE can easily find all declarations and uses of the AccountRepository type.. beans will have dependencies on one another across configuration classes. In most practical scenarios. Also. but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. solving this problem is simple. using @Autowired works well and provides the desired modularity.

. DefaultRepositoryConfig.class). } Now ServiceConfig is loosely coupled with respect to the concrete DefaultRepositoryConfig.1 Reference Documentation 121 . } } In the situation above.class).). consider autowiring the configuration classes themselves: @Configuration public class ServiceConfig { private @Autowired RepositoryConfig repositoryConfig.accountRepository()). and built-in IDE tooling is still useful: it will be easy for the developer to get a type hierarchy of RepositoryConfig implementations. ServiceConfig is now tightly coupled to RepositoryConfig. This tight coupling can be somewhat mitigated by using interface-based or abstract class-based @Configuration classes. "A123". } @Configuration public class DefaultRepositoryConfig implements RepositoryConfig { public @Bean AccountRepository accountRepository() { return new JdbcAccountRepository(. transferService. However. Consider the following: @Configuration public class ServiceConfig { private @Autowired RepositoryConfig repositoryConfig.class. } } @Configuration @Import({ServiceConfig. public @Bean TransferService transferService() { return new TransferServiceImpl(repositoryConfig. In cases where this ambiguity is not acceptable and you wish to have direct navigation from within your IDE from one @Configuration class to another. navigating @Configuration classes and their dependencies becomes no different than the usual process of navigating interface-based code..00.getBean(TransferService.class}) // import the concrete config! public class SystemTestConfig { public @Bean DataSource dataSource() { /* return DataSource */ } } public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(SystemTestConfig. "C456").accountRepository()). public @Bean TransferService transferService() { // navigate 'through' the config class to the @Bean method! return new TransferServiceImpl(repositoryConfig.Spring Framework @Bean methods that return that type. that's the tradeoff. it is completely explicit where AccountRepository is defined. TransferService transferService = ctx.transfer(100. 3. In this way. } } @Configuration public interface RepositoryConfig { @Bean AccountRepository accountRepository().

In cases where XML is convenient or necessary.properties 3.AppConfig"/> <bean class="org. } public @Bean TransferService transferService() { return new TransferService(accountRepository()).properties"/> <bean class="com. } } system-test-config.datasource. @Configuration public class AppConfig { private @Autowired DataSource dataSource. Declaring @Configuration classes as plain Spring <bean/> elements Remember that @Configuration classes are ultimately just bean definitions in the container. for example.xml as a <bean/>definition. In this example.1 Reference Documentation 122 . and process the @Bean methods declared in AppConfig properly.springframework. Because <context:annotation-config/> is switched on. or in a "Java-centric" fashion using AnnotationConfigApplicationContext and the @ImportResource annotation to import XML as needed.url}"/> <property name="username" value="${jdbc. Below you'll find the options for using @Configuration classes in this kind of "XML-centric" situation. XML-centric use of @Configuration classes It may be preferable to bootstrap the Spring container from XML and include @Configuration classes in an ad-hoc fashion. we create a @Configuration class named AppConfig and include it within system-test-config.acme.Spring Framework Combining Java and XML configuration Spring's @Configuration class support does not aim to be a 100% complete replacement for Spring XML. For example. ClassPathXmlApplicationContext. public @Bean AccountRepository accountRepository() { return new JdbcAccountRepository(dataSource). in a large existing codebase that uses Spring XML. the container will recognize the @Configuration annotation.DriverManagerDataSource"> <property name="url" value="${jdbc.enable processing of annotations such as @Autowired and @Configuration --> <context:annotation-config/> <context:property-placeholder location="classpath:/com/acme/jdbc. it will be easier to create @Configuration classes on an as-needed basis and include them from the existing XML files.xml <beans> <!-.password}"/> </bean> </beans> jdbc.jdbc. you have a choice: either instantiate the container in an "XML-centric" way using. Some facilities such as Spring XML namespaces remain an ideal way to configure the container.username}"/> <property name="password" value="${jdbc.

url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.xml above.url=jdbc:hsqldb:hsql://localhost/xdb jdbc.. @Configuration-annotated classes are automatically candidates for component scanning.xml").xml to take advantage of component-scanning. In these scenarios. simply use @ImportResource and define only as much XML as is needed. While it would be acceptable to do so.springframework.DriverManagerDataSource"> <property name="url" value="${jdbc.password}") String password.xml") public class AppConfig { private @Value("${jdbc.picks up and registers AppConfig as a bean definition --> <context:component-scan base-package="com.datasource. Note that in this case.. because <context:component-scan/> enables all the same functionality.1 Reference Documentation 123 .acme"/> <context:property-placeholder location="classpath:/com/acme/jdbc. } Note In system-test-config. system-test-config. it is unnecessary given that no other bean will ever refer to it.properties"/> <bean class="org. the AppConfig<bean/> does not declare an id element.getBean(TransferService. Using the same scenario as above. @Configuration @ImportResource("classpath:/com/acme/properties-config. so an explicit bean id is not strictly required. we don't need to explicitly declare <context:annotation-config/>. // .password= public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/com/acme/system-test-config. Likewise with the DataSource bean . Doing so achieves a "Java-centric" approach to configuring the container and keeps XML to a bare minimum.username}") String username. private @Value("${jdbc.password}"/> </bean> </beans> @Configuration class-centric use of XML with @ImportResource In applications where @Configuration classes are the primary mechanism for configuring the container.class).it is only ever autowired by type. private @Value("${jdbc. it will still likely be necessary to use at least some XML.username=sa jdbc. Using <context:component-scan/> to pick up @Configuration classes Because @Configuration is meta-annotated with @Component. we can redefine system-test-config. public @Bean DataSource dataSource() { 3. and it is unlikely that it will be explicitly fetched from the container by name.Spring Framework jdbc. TransferService transferService = ctx.url}") String url.jdbc.xml <beans> <!-.

the bean name will be the same as the method name..Spring Framework return new DriverManagerDataSource(url. } } The preceding configuration is exactly equivalent to the following Spring XML: <beans> <bean id="transferService" class="com. } Using the @Bean annotation @Bean is a method-level annotation and a direct analog of the XML <bean/> element. TransferService transferService = ctx.TransferServiceImpl"/> </beans> Both declarations make a bean named transferService available in the ApplicationContext. such as: init-method. Declaring a bean To declare a bean. 3.class). destroy-method. You can use the @Bean annotation in a @Configuration-annotated or in a @Component-annotated class.class). autowiring and name. simply annotate a method with the @Bean annotation.getBean(TransferService.password= public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig. // .properties"/> </beans> jdbc. The annotation supports some of the attributes offered by <bean/>.1 Reference Documentation 124 . By default. The following is a simple example of a @Bean method declaration: @Configuration public class AppConfig { @Bean public TransferService transferService() { return new TransferServiceImpl().properties jdbc.username=sa jdbc. } } properties-config. You use this method to register a bean definition within an ApplicationContext of the type specified as the method's return value..url=jdbc:hsqldb:hsql://localhost/xdb jdbc. password).xml <beans> <context:property-placeholder location="classpath:/com/acme/jdbc.acme. username.

the foo bean receives a reference to bar via constructor injection.acme. The @Bean annotation supports specifying arbitrary initialization and destruction callback methods. } @Bean public Bar bar() { return new Bar(). } } In the example above. and so on are also fully supported.1 Reference Documentation 125 . Any classes defined with the @Bean annotation can use the @PostConstruct and @PreDestroy annotations from JSR-250. The regular Spring lifecycle callbacks are fully supported as well. expressing that dependency is as simple as having one bean method call another: @Configuration public class AppConfig { @Bean public Foo foo() { return new Foo(bar()). or Lifecycle. Receiving lifecycle callbacks Beans declared in a @Configuration-annotated class support the regular lifecycle callbacks. MessageSourceAware. BeanNameAware. much like Spring XML's init-method and destroy-method attributes on the bean element: public class Foo { public void init() { // initialization logic } } public class Bar { public void cleanup() { // destruction logic } } 3. see JSR-250 annotations for further details.TransferServiceImpl Injecting dependencies When @Beans have dependencies on one another. ApplicationContextAware. The standard set of *Aware interfaces such as BeanFactoryAware. If a bean implements InitializingBean. DisposableBean.Spring Framework bound to an object instance of type TransferServiceImpl: transferService -> com. their respective methods are called by the container.

Spring Framework @Configuration public class AppConfig { @Bean(initMethod = "init") public Foo foo() { return new Foo(). you can do anything you like with your objects and do not always need to rely on the container lifecycle! Specifying bean scope Using the @Scope annotation You can specify that your beans defined with the @Bean annotation should have a specific scope. it would be equally as valid to call the init() method directly during construction: @Configuration public class AppConfig { @Bean public Foo foo() { Foo foo = new Foo().. in the case of Foo above. return foo. foo. } } @Scope and scoped-proxy Spring offers a convenient way of working with scoped dependencies through scoped proxies.. } @Bean(destroyMethod = "cleanup") public Bar bar() { return new Bar().. } } Of course. but you can override this with the @Scope annotation: @Configuration public class MyConfiguration { @Bean @Scope("prototype") public Encryptor encryptor() { // . } Tip When you work directly in Java.. You can use any of the standard scopes specified in the Bean Scopes section. } // . The easiest way to create such a proxy when using the XML configuration is the <aop:scoped-proxy/> 3.init(). The default scope is singleton.1 Reference Documentation 126 .

it would look like the following: // an HTTP Session-scoped bean exposed as a proxy @Bean @Scope(value = "session". If you port the scoped proxy example from the XML reference documentation (see preceding link) to our @Bean using Java. } Lookup method injection As noted earlier.NO).. // inject dependencies here as required return command.INTERFACES. you can create a subclass of CommandManager where the abstract createCommand() method is overridden in such a way that it looks up a new (prototype) command object: @Bean @Scope("prototype") public AsyncCommand asyncCommand() { AsyncCommand command = new AsyncCommand(). lookup method injection is an advanced feature that you should use rarely. Using Java for this type of configuration provides a natural means for implementing this pattern. The default is no proxy (ScopedProxyMode.execute(). Configuring your beans in Java with a @Scope annotation offers equivalent support with the proxyMode attribute. } @Bean public CommandManager commandManager() { // return new anonymous implementation of CommandManager with command() overridden // to return a new prototype Command object return new CommandManager() { 3.Spring Framework element. but where is the implementation of this method? protected abstract Command createCommand().1 Reference Documentation 127 .TARGET_CLASS) public UserPreferences userPreferences() { return new UserPreferences(). } @Bean public Service userService() { UserService service = new SimpleUserService().setUserPreferences(userPreferences()). } // okay. return command. It is useful in cases where a singleton-scoped bean has a dependency on a prototype-scoped bean. } Using Java-configuration support .. public abstract class CommandManager { public Object process(Object commandState) { // grab a new instance of the appropriate Command interface Command command = createCommand().setState(commandState). // set the state on the (hopefully brand new) Command instance command. return service. but you can specify ScopedProxyMode. // a reference to the proxied userPreferences bean service. proxyMode = ScopedProxyMode.TARGET_CLASS or ScopedProxyMode.

@Configuration public class AppConfig { @Bean(name = { "dataSource". "subsystemB-dataSource" }) public DataSource dataSource() { // instantiate.1 Reference Documentation 128 . configuration classes use a @Bean method's name as the name of the resulting bean. "subsystemA-dataSource". @Configuration public class AppConfig { @Bean(name = "myFoo") public Foo foo() { return new Foo().Spring Framework protected Command createCommand() { return asyncCommand(). The name attribute of the @Bean annotation accepts a String array for this purpose. clientService. it is sometimes desirable to give a single bean multiple names. } } Further information about how Java-based configuration works internally The following example shows a @Bean annotated method being called twice: @Configuration public class AppConfig { @Bean public ClientService clientService1() { ClientServiceImpl clientService = new ClientServiceImpl(). This functionality can be overridden. however. } } Bean aliasing As discussed in the section called “Naming beans”.. return clientService. } @Bean public ClientService clientService2() { ClientServiceImpl clientService = new ClientServiceImpl(). configure and return DataSource bean.. otherwise known as bean aliasing. clientService.setClientDao(clientDao()). with the name attribute. } } } Customizing bean naming By default.setClientDao(clientDao()). 3.

Since this method creates a new instance of ClientDaoImpl and returns it. That definitely would be problematic: in Spring. This is where the magic comes in: All @Configuration classes are subclassed at startup-time with CGLIB. } @Bean public ClientDao clientDao() { return new ClientDaoImpl(). We are talking about singletons here. In the subclass. Note The behavior could be different according to the scope of your bean. instantiated beans have a singleton scope by default. <beans> <context:load-time-weaver/> </beans> Adding this element to an XML-based Spring configuration file activates a Spring LoadTimeWeaver 3. you must include the CGLIB jar in your list of dependencies. you would normally expect having 2 instances (one for each service).1 Reference Documentation 129 .5 provides a load-time-weaver element. in order for JavaConfig to work. } } clientDao() has been called once in clientService1() and once in clientService2(). the child method checks the container first for any cached (scoped) beans before it calls the parent method and creates a new instance. Note There are a few restrictions due to the fact that CGLIB dynamically adds features at startup-time: • Configuration classes should not be final • They should have a constructor with no arguments 4.13 Registering a LoadTimeWeaver The context namespace introduced in Spring 2. Note Beware that.Spring Framework return clientService.

Consult the LocalContainerEntityManagerFactoryBean Javadoc for more detail. String default. thereby receiving a reference to the load-time weaver instance. through the HierarchicalBeanFactory interface. such as URLs and files.springframework. The org. To enhance BeanFactory functionality in a more framework-oriented style the context package also provides the following functionality: • Access to messages in i18n-style. through the ResourceLoader interface. through the use of the ApplicationEventPublisher interface. including in a programmatic way.factory package provides basic functionality for managing and manipulating beans. Object[] args. Locale loc): The basic method used to retrieve a message from the MessageSource. 4. but instead relying on support classes such as ContextLoader to automatically instantiate an ApplicationContext as part of the normal startup process of a J2EE web application. Any arguments passed in become replacement values. and therefore provides internationalization (i18n) functionality.springframework.Spring Framework for the ApplicationContext. • Event publication to beans implementing the ApplicationListener interface. • Loading of multiple (hierarchical) contexts.context package adds the ApplicationContext interface. Spring also provides the interface HierarchicalMessageSource. allowing each to be focused on one particular layer. in addition to extending other interfaces to provide additional functionality in a more application framework-oriented style. • String getMessage(String code. When no message is found for the specified locale. Object[] args.1 Reference Documentation 130 . the org. Internationalization using MessageSource The ApplicationContext interface extends an interface called MessageSource. This is particularly useful in combination with Spring's JPA support where load-time weaving may be necessary for JPA class transformation. Locale loc): Essentially the 3.14 Additional Capabilities of the ApplicationContext As was discussed in the chapter introduction. Together these interfaces provide the foundation upon which Spring effects message resolution. For more on AspectJ load-time weaving. such as the web layer of an application. Any bean within that ApplicationContext may implement LoadTimeWeaverAware. through the MessageSource interface. which can resolve messages hierarchically. Many people use the ApplicationContext in a completely declarative fashion. The methods defined on these interfaces include: • String getMessage(String code. using the MessageFormat functionality provided by the standard library. • Access to resources. which extends the BeanFactory interface. the default message is used. see the section called “Load-time weaving with AspectJ in the Spring Framework”.beans. not even creating it programmatically.

a NoSuchMessageException is thrown.. # in format. an empty DelegatingMessageSource is instantiated in order to be able to accept calls to the methods defined above. Both implement HierarchicalMessageSource in order to do nested messaging. String message = resources. but with one difference: no default message can be specified. exceptions and windows.. The bean must have the name messageSource. 3.properties message=Alligators rock! # in exceptions.context.required=The '{0}' argument is required. ResourceBundleMessageSource and StaticMessageSource. System. Locale locale): All properties used in the preceding methods are also wrapped in a class named MessageSourceResolvable. When an ApplicationContext is loaded. if the message cannot be found.out.springframework. Any request to resolve a message will be handled in the JDK standard way of resolving messages through ResourceBundles. null. "Default".properties argument.getMessage("message". public static void main(String[] args) { MessageSource resources = new ClassPathXmlApplicationContext("beans.xml"). A program to execute the MessageSource functionality is shown in the next example.1 Reference Documentation 131 . the ApplicationContext attempts to find a parent containing a bean with the same name. The ResourceBundleMessageSource is shown in the following example: <beans> <bean id="messageSource" class="org. assume the contents of two of the above resource bundle files are. If such a bean is found. If no message source is found. Remember that all ApplicationContext implementations are also MessageSource implementations and so can be cast to the MessageSource interface. which you can use with this method. null). For the purposes of the example. The StaticMessageSource is rarely used but provides programmatic ways to add messages to the source. If it does.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>format</value> <value>exceptions</value> <value>windows</value> </list> </property> </bean> </beans> In the example it is assumed you have three resource bundles defined in your classpath called format.Spring Framework same as the previous method.support. • String getMessage(MessageSourceResolvable resolvable.println(message). it automatically searches for a MessageSource bean defined in the context. If the ApplicationContext cannot find any source for messages. all calls to the preceding methods are delegated to the message source. Spring provides two MessageSource implementations. it uses that bean as the MessageSource.

getMessage("argument.foo. null). which exists at the root of your classpath. you would create files called format_en_GB..properties.properties.properties respectively.context.out.Example"> <property name="messages" ref="messageSource"/> </bean> </beans> public class Example { private MessageSource messages. public void setMessages(MessageSource messages) { this. The next example shows arguments passed to the message lookup.properties. The messageSource bean definition refers to a number of resource bundles through its basenames property. exceptions. Alligators rock! So to summarize.properties respectively. The three files that are passed in the list to the basenames property exist as files at the root of your classpath and are called format.xml. these arguments will be converted into Strings and inserted into placeholders in the lookup message.Spring Framework } The resulting output from the above program will be.ResourceBundleMessageSource"> <property name="basename" value="test-messages"/> </bean> <!-.this MessageSource is being used in a web application --> <bean id="messageSource" class="org. In short. exceptions_en_GB.required".1 Reference Documentation 132 . new Object [] {"userDao"}..support. and windows.properties. "Required".springframework. Spring's various MessageResource implementations follow the same locale resolution and fallback rules as the standard JDK ResourceBundle. With regard to internationalization (i18n). <beans> <!-. and windows_en_GB. and continuing with the example messageSource defined previously.messages = messages. the MessageSource is defined in a file called beans.. if you want to resolve messages against the British (en-GB) locale. } } The resulting output from the invocation of the execute() method will be. } public void execute() { String message = this.lets inject the above MessageSource into this POJO --> <bean id="example" class="com. The userDao argument is required.messages. 3.println(message).. System.

Spring Framework

Typically, locale resolution is managed by the surrounding environment of the application. In this example, the locale against which (British) messages will be resolved is specified manually.
# in exceptions_en_GB.properties argument.required=Ebagum lad, the '{0}' argument is required, I say, required.

public static void main(final String[] args) { MessageSource resources = new ClassPathXmlApplicationContext("beans.xml"); String message = resources.getMessage("argument.required", new Object [] {"userDao"}, "Required", Locale.UK); System.out.println(message); }

The resulting output from the running of the above program will be...
Ebagum lad, the 'userDao' argument is required, I say, required.

You can also use the MessageSourceAware interface to acquire a reference to any MessageSource that has been defined. Any bean that is defined in an ApplicationContext that implements the MessageSourceAware interface is injected with the application context's MessageSource when the bean is created and configured.

Note
As an alternative to ResourceBundleMessageSource, Spring provides a ReloadableResourceBundleMessageSource class. This variant supports the same bundle file format but is more flexible than the standard JDK based ResourceBundleMessageSource implementation. In particular, it allows for reading files from any Spring resource location (not just from the classpath) and supports hot reloading of bundle property files (while efficiently caching them in between). Check out the ReloadableResourceBundleMessageSource javadoc for details.

Standard and Custom Events
Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. If a bean that implements the ApplicationListener interface is deployed into the context, every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified. Essentially, this is the standard Observer design pattern. Spring provides the following standard events: Table 4.7. Built-in Events Event Explanation

ContextRefreshedEvent Published when the ApplicationContext is initialized or refreshed, for example, using the refresh() method on the ConfigurableApplicationContext interface. "Initialized" here 3.1 Reference Documentation 133

Spring Framework

Event

Explanation means that all beans are loaded, post-processor beans are detected and activated, singletons are pre-instantiated, and the ApplicationContext object is ready for use. As long as the context has not been closed, a refresh can be triggered multiple times, provided that the chosen ApplicationContext actually supports such "hot" refreshes. For example, XmlWebApplicationContext supports hot refreshes, but GenericApplicationContext does not.

ContextStartedEvent Published when the ApplicationContext is started, using the start() method on the ConfigurableApplicationContext interface. "Started" here means that all Lifecycle beans receive an explicit start signal. Typically this signal is used to restart beans after an explicit stop, but it may also be used to start components that have not been configured for autostart , for example, components that have not already started on initialization. ContextStoppedEvent Published when the ApplicationContext is stopped, using the stop() method on the ConfigurableApplicationContext interface. "Stopped" here means that all Lifecycle beans receive an explicit stop signal. A stopped context may be restarted through a start() call. ContextClosedEvent Published when the ApplicationContext is closed, using the close() method on the ConfigurableApplicationContext interface. "Closed" here means that all singleton beans are destroyed. A closed context reaches its end of life; it cannot be refreshed or restarted.

RequestHandledEvent A web-specific event telling all beans that an HTTP request has been serviced. This event is published after the request is complete. This event is only applicable to web applications using Spring's DispatcherServlet.

You can also create and publish your own custom events. This example demonstrates a simple class that extends Spring's ApplicationEvent base class:
public class BlackListEvent extends ApplicationEvent { private final String address; private final String test; public BlackListEvent(Object source, String address, String test) { super(source); this.address = address; this.test = test; } // accessor and other methods... }

3.1

Reference Documentation

134

Spring Framework

To publish a custom ApplicationEvent, call the publishEvent() method on an ApplicationEventPublisher. Typically this is done by creating a class that implements ApplicationEventPublisherAware and registering it as a Spring bean. The following example demonstrates such a class:
public class EmailService implements ApplicationEventPublisherAware { private List<String> blackList; private ApplicationEventPublisher publisher; public void setBlackList(List<String> blackList) { this.blackList = blackList; } public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { this.publisher = publisher; } public void sendEmail(String address, String text) { if (blackList.contains(address)) { BlackListEvent event = new BlackListEvent(this, address, text); publisher.publishEvent(event); return; } // send email... } }

At configuration time, the Spring container will detect that EmailService implements ApplicationEventPublisherAware and will automatically call setApplicationEventPublisher(). In reality, the parameter passed in will be the Spring container itself; you're simply interacting with the application context via its ApplicationEventPublisher interface. To receive the custom ApplicationEvent, create a class that implements ApplicationListener and register it as a Spring bean. The following example demonstrates such a class:
public class BlackListNotifier implements ApplicationListener<BlackListEvent> { private String notificationAddress; public void setNotificationAddress(String notificationAddress) { this.notificationAddress = notificationAddress; } public void onApplicationEvent(BlackListEvent event) { // notify appropriate parties via notificationAddress... } }

Notice that ApplicationListener is generically parameterized with the type of your custom event, BlackListEvent. This means that the onApplicationEvent() method can remain type-safe, avoiding any need for downcasting. You may register as many event listeners as you wish, but note that by default event listeners receive events synchronously. This means the publishEvent() method blocks until all listeners have finished processing the event. One advantage of this synchronous and 3.1 Reference Documentation 135

Spring Framework

single-threaded approach is that when a listener receives an event, it operates inside the transaction context of the publisher if a transaction context is available. If another strategy for event publication becomes necessary, refer to the JavaDoc for Spring's ApplicationEventMulticaster interface. The following example shows the bean definitions used to register and configure each of the classes above:
<bean id="emailService" class="example.EmailService"> <property name="blackList"> <list> <value>known.spammer@example.org</value> <value>known.hacker@example.org</value> <value>john.doe@example.org</value> </list> </property> </bean> <bean id="blackListNotifier" class="example.BlackListNotifier"> <property name="notificationAddress" value="blacklist@example.org"/> </bean>

Putting it all together, when the sendEmail() method of the emailService bean is called, if there are any emails that should be blacklisted, a custom event of type BlackListEvent is published. The blackListNotifier bean is registered as an ApplicationListener and thus receives the BlackListEvent, at which point it can notify appropriate parties.

Note
Spring's eventing mechanism is designed for simple communication between Spring beans within the same application context. However, for more sophisticated enterprise integration needs, the separately-maintained Spring Integration project provides complete support for building lightweight, pattern-oriented, event-driven architectures that build upon the well-known Spring programming model.

Convenient access to low-level resources
For optimal usage and understanding of application contexts, users should generally familiarize themselves with Spring's Resource abstraction, as described in the chapter Chapter 5, Resources. An application context is a ResourceLoader, which can be used to load Resources. A Resource is essentially a more feature rich version of the JDK class java.net.URL, in fact, the implementations of the Resource wrap an instance of java.net.URL where appropriate. A Resource can obtain low-level resources from almost any location in a transparent fashion, including from the classpath, a filesystem location, anywhere describable with a standard URL, and some other variations. If the resource location string is a simple path without any special prefixes, where those resources come from is specific and appropriate to the actual application context type. You can configure a bean deployed into the application context to implement the special callback interface, ResourceLoaderAware, to be automatically called back at initialization time with the 3.1 Reference Documentation 136

Spring Framework

application context itself passed in as the ResourceLoader. You can also expose properties of type Resource, to be used to access static resources; they will be injected into it like any other properties. You can specify those Resource properties as simple String paths, and rely on a special JavaBean PropertyEditor that is automatically registered by the context, to convert those text strings to actual Resource objects when the bean is deployed. The location path or paths supplied to an ApplicationContext constructor are actually resource strings, and in simple form are treated appropriately to the specific context implementation. ClassPathXmlApplicationContext treats a simple location path as a classpath location. You can also use location paths (resource strings) with special prefixes to force loading of definitions from the classpath or a URL, regardless of the actual context type.

Convenient ApplicationContext instantiation for web applications
You can create ApplicationContext instances declaratively by using, for example, a ContextLoader. Of course you can also create ApplicationContext instances programmatically by using one of the ApplicationContext implementations. The ContextLoader mechanism comes in two flavors: the ContextLoaderListener and the ContextLoaderServlet. They have the same functionality but differ in that the listener version is not reliable in Servlet 2.3 containers. In the Servlet 2.4 specification, Servlet context listeners must execute immediately after the Servlet context for the web application is created and is available to service the first request (and also when the Servlet context is about to be shut down). As such a Servlet context listener is an ideal place to initialize the Spring ApplicationContext. All things being equal, you should probably prefer ContextLoaderListener; for more information on compatibility, have a look at the Javadoc for the ContextLoaderServlet. You can register an ApplicationContext using the ContextLoaderListener as follows:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- or use the ContextLoaderServlet instead of the above listener <servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> -->

The listener inspects the contextConfigLocation parameter. If the parameter does not exist, the listener uses /WEB-INF/applicationContext.xml as a default. When the parameter does exist, the listener separates the String by using predefined delimiters (comma, semicolon and whitespace) and uses the values as locations where application contexts will be searched. Ant-style path patterns are supported as well. Examples are /WEB-INF/*Context.xml for all files with names ending with 3.1 Reference Documentation 137

Spring Framework

"Context.xml", residing in the "WEB-INF" directory, and /WEB-INF/**/*Context.xml, for all such files in any subdirectory of "WEB-INF". You can use ContextLoaderServlet instead of ContextLoaderListener. The Servlet uses the contextConfigLocation parameter just as the listener does.

Deploying a Spring ApplicationContext as a J2EE RAR file
In Spring 2.5 and later, it is possible to deploy a Spring ApplicationContext as a RAR file, encapsulating the context and all of its required bean classes and library JARs in a J2EE RAR deployment unit. This is the equivalent of bootstrapping a standalone ApplicationContext, just hosted in J2EE environment, being able to access the J2EE servers facilities. RAR deployment is a more natural alternative to scenario of deploying a headless WAR file, in effect, a WAR file without any HTTP entry points that is used only for bootstrapping a Spring ApplicationContext in a J2EE environment. RAR deployment is ideal for application contexts that do not need HTTP entry points but rather consist only of message endpoints and scheduled jobs. Beans in such a context can use application server resources such as the JTA transaction manager and JNDI-bound JDBC DataSources and JMS ConnectionFactory instances, and may also register with the platform's JMX server - all through Spring's standard transaction management and JNDI and JMX support facilities. Application components can also interact with the application server's JCA WorkManager through Spring's TaskExecutor abstraction. Check out the JavaDoc of the SpringContextResourceAdapter class for the configuration details involved in RAR deployment. For a simple deployment of a Spring ApplicationContext as a J2EE RAR file: package all application classes into a RAR file, which is a standard JAR file with a different file extension. Add all required library JARs into the root of the RAR archive. Add a "META-INF/ra.xml" deployment descriptor (as shown in SpringContextResourceAdapters JavaDoc) and the corresponding Spring XML bean definition file(s) (typically "META-INF/applicationContext.xml"), and drop the resulting RAR file into your application server's deployment directory.

Note
Such RAR deployment units are usually self-contained; they do not expose components to the outside world, not even to other modules of the same application. Interaction with a RAR-based ApplicationContext usually occurs through JMS destinations that it shares with other modules. A RAR-based ApplicationContext may also, for example, schedule some jobs, reacting to new files in the file system (or the like). If it needs to allow synchronous access from the outside, it could for example export RMI endpoints, which of course may be used by other application modules on the same machine.

4.15 The BeanFactory
3.1 Reference Documentation 138

Spring Framework

The BeanFactory provides the underlying basis for Spring's IoC functionality but it is only used directly in integration with other third-party frameworks and is now largely historical in nature for most users of Spring. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purposes of backward compatibility with the large number of third-party frameworks that integrate with Spring. Often third-party components that can not use more modern equivalents such as @PostConstruct or @PreDestroy in order to remain compatible with JDK 1.4 or to avoid a dependency on JSR-250. This section provides additional background into the differences between the BeanFactory and ApplicationContext and how one might access the IoC container directly through a classic singleton lookup.

BeanFactory or ApplicationContext?
Use an ApplicationContext unless you have a good reason for not doing so. Because the ApplicationContext includes all functionality of the BeanFactory, it is generally recommended over the BeanFactory, except for a few situations such as in an Applet where memory consumption might be critical and a few extra kilobytes might make a difference. However, for most typical enterprise applications and systems, the ApplicationContext is what you will want to use. Spring 2.0 and later makes heavy use of the BeanPostProcessor extension point (to effect proxying and so on). If you use only a plain BeanFactory, a fair amount of support such as transactions and AOP will not take effect, at least not without some extra steps on your part. This situation could be confusing because nothing is actually wrong with the configuration. The following table lists features provided by the BeanFactory and ApplicationContext interfaces and implementations. Table 4.8. Feature Matrix Feature Bean instantiation/wiring Automatic BeanPostProcessor registration Automatic BeanFactoryPostProcessor registration Convenient MessageSource access (for i18n) 3.1 BeanFactory Yes No ApplicationContext Yes Yes

No

Yes

No

Yes

Reference Documentation

139

Spring Framework

Feature ApplicationEvent publication

BeanFactory No

ApplicationContext Yes

To explicitly register a bean post-processor with a BeanFactory implementation, you must write code like this:
ConfigurableBeanFactory factory = new XmlBeanFactory(...); // now register any needed BeanPostProcessor instances MyBeanPostProcessor postProcessor = new MyBeanPostProcessor(); factory.addBeanPostProcessor(postProcessor); // now start using the factory

To explicitly register a BeanFactoryPostProcessor implementation, you must write code like this:

when

using

a

BeanFactory

XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml")); // bring in some property values from a Properties file PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.setLocation(new FileSystemResource("jdbc.properties")); // now actually do the replacement cfg.postProcessBeanFactory(factory);

In both cases, the explicit registration step is inconvenient, which is one reason why the various ApplicationContext implementations are preferred above plain BeanFactory implementations in the vast majority of Spring-backed applications, especially when using BeanFactoryPostProcessors and BeanPostProcessors. These mechanisms implement important functionality such as property placeholder replacement and AOP.

Glue code and the evil singleton
It is best to write most application code in a dependency-injection (DI) style, where that code is served out of a Spring IoC container, has its own dependencies supplied by the container when it is created, and is completely unaware of the container. However, for the small glue layers of code that are sometimes needed to tie other code together, you sometimes need a singleton (or quasi-singleton) style access to a Spring IoC container. For example, third-party code may try to construct new objects directly (Class.forName() style), without the ability to get these objects out of a Spring IoC container. If the object constructed by the third-party code is a small stub or proxy, which then uses a singleton style access to a Spring IoC container to get a real object to delegate to, then inversion of control has still been achieved for the majority of the code (the object coming out of the container). Thus most code is still unaware of the container or how it is accessed, and remains decoupled from other code, with all ensuing benefits. EJBs may also use this stub/proxy approach to delegate to a plain Java implementation object, retrieved from a Spring IoC container. While the Spring IoC container itself ideally does not have to be a

3.1

Reference Documentation

140

Spring Framework

singleton, it may be unrealistic in terms of memory usage or initialization times (when using beans in the Spring IoC container such as a Hibernate SessionFactory) for each bean to use its own, non-singleton Spring IoC container. Looking up the application context in a service locator style is sometimes the only option for accessing shared Spring-managed components, such as in an EJB 2.1 environment, or when you want to share a single ApplicationContext as a parent to WebApplicationContexts across WAR files. In this case you should look into using the utility class ContextSingletonBeanFactoryLocator locator that is described in this SpringSource team blog entry.

3.1

Reference Documentation

141

Spring Framework

5. Resources
5.1 Introduction
Java's standard java.net.URL class and standard handlers for various URL prefixes unfortunately are not quite adequate enough for all access to low-level resources. For example, there is no standardized URL implementation that may be used to access a resource that needs to be obtained from the classpath, or relative to a ServletContext. While it is possible to register new handlers for specialized URL prefixes (similar to existing handlers for prefixes such as http:), this is generally quite complicated, and the URL interface still lacks some desirable functionality, such as a method to check for the existence of the resource being pointed to.

5.2 The Resource interface
Spring's Resource interface is meant to be a more capable interface for abstracting access to low-level resources.
public interface Resource extends InputStreamSource { boolean exists(); boolean isOpen(); URL getURL() throws IOException; File getFile() throws IOException; Resource createRelative(String relativePath) throws IOException; String getFilename(); String getDescription(); }

public interface InputStreamSource { InputStream getInputStream() throws IOException; }

Some of the most important methods from the Resource interface are: • getInputStream(): locates and opens the resource, returning an InputStream for reading from the resource. It is expected that each invocation returns a fresh InputStream. It is the responsibility of the caller to close the stream. • exists(): returns a boolean indicating whether this resource actually exists in physical form. • isOpen(): returns a boolean indicating whether this resource represents a handle with an open

3.1

Reference Documentation

142

Spring Framework

stream. If true, the InputStream cannot be read multiple times, and must be read once only and then closed to avoid resource leaks. Will be false for all usual resource implementations, with the exception of InputStreamResource. • getDescription(): returns a description for this resource, to be used for error output when working with the resource. This is often the fully qualified file name or the actual URL of the resource. Other methods allow you to obtain an actual URL or File object representing the resource (if the underlying implementation is compatible, and supports that functionality). The Resource abstraction is used extensively in Spring itself, as an argument type in many method signatures when a resource is needed. Other methods in some Spring APIs (such as the constructors to various ApplicationContext implementations), take a String which in unadorned or simple form is used to create a Resource appropriate to that context implementation, or via special prefixes on the String path, allow the caller to specify that a specific Resource implementation must be created and used. While the Resource interface is used a lot with Spring and by Spring, it's actually very useful to use as a general utility class by itself in your own code, for access to resources, even when your code doesn't know or care about any other parts of Spring. While this couples your code to Spring, it really only couples it to this small set of utility classes, which are serving as a more capable replacement for URL, and can be considered equivalent to any other library you would use for this purpose. It is important to note that the Resource abstraction does not replace functionality: it wraps it where possible. For example, a UrlResource wraps a URL, and uses the wrapped URL to do its work.

5.3 Built-in Resource implementations
There are a number of Resource implementations that come supplied straight out of the box in Spring:

UrlResource
The UrlResource wraps a java.net.URL, and may be used to access any object that is normally accessible via a URL, such as files, an HTTP target, an FTP target, etc. All URLs have a standardized String representation, such that appropriate standardized prefixes are used to indicate one URL type from another. This includes file: for accessing filesystem paths, http: for accessing resources via the HTTP protocol, ftp: for accessing resources via FTP, etc. A UrlResource is created by Java code explicitly using the UrlResource constructor, but will often be created implicitly when you call an API method which takes a String argument which is meant to represent a path. For the latter case, a JavaBeans PropertyEditor will ultimately decide which type of Resource to create. If the path string contains a few well-known (to it, that is) prefixes such as classpath:, it will create an appropriate specialized Resource for that prefix. However, if it doesn't recognize the prefix, it will assume the this is just a standard URL string, and will create a 3.1 Reference Documentation 143

Spring Framework

UrlResource.

ClassPathResource
This class represents a resource which should be obtained from the classpath. This uses either the thread context class loader, a given class loader, or a given class for loading resources. This Resource implementation supports resolution as java.io.File if the class path resource resides in the file system, but not for classpath resources which reside in a jar and have not been expanded (by the servlet engine, or whatever the environment is) to the filesystem. To address this the various Resource implementations always support resolution as a java.net.URL. A ClassPathResource is created by Java code explicitly using the ClassPathResource constructor, but will often be created implicitly when you call an API method which takes a String argument which is meant to represent a path. For the latter case, a JavaBeans PropertyEditor will recognize the special prefix classpath:on the string path, and create a ClassPathResource in that case.

FileSystemResource
This is a Resource implementation for java.io.File handles. It obviously supports resolution as a File, and as a URL.

ServletContextResource
This is a Resource implementation for ServletContext resources, interpreting relative paths within the relevant web application's root directory. This always supports stream access and URL access, but only allows java.io.File access when the web application archive is expanded and the resource is physically on the filesystem. Whether or not it's expanded and on the filesystem like this, or accessed directly from the JAR or somewhere else like a DB (it's conceivable) is actually dependent on the Servlet container.

InputStreamResource
A Resource implementation for a given InputStream. This should only be used if no specific Resource implementation is applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible. In contrast to other Resource implementations, this is a descriptor for an already opened resource therefore returning true from isOpen(). Do not use it if you need to keep the resource descriptor somewhere, or if you need to read a stream multiple times.

3.1

Reference Documentation

144

Spring Framework

ByteArrayResource
This is a Resource implementation for a given byte array. It creates a ByteArrayInputStream for the given byte array. It's useful for loading content from any given byte array, without having to resort to a single-use InputStreamResource.

5.4 The ResourceLoader
The ResourceLoader interface is meant to be implemented by objects that can return (i.e. load) Resource instances.
public interface ResourceLoader { Resource getResource(String location); }

All application contexts implement the ResourceLoader interface, and therefore all application contexts may be used to obtain Resource instances. When you call getResource() on a specific application context, and the location path specified doesn't have a specific prefix, you will get back a Resource type that is appropriate to that particular application context. For example, assume the following snippet of code was executed against a ClassPathXmlApplicationContext instance:
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");

What would be returned would be a ClassPathResource; if the same method was executed against a FileSystemXmlApplicationContext instance, you'd get back a FileSystemResource. For a WebApplicationContext, you'd get back a ServletContextResource, and so on. As such, you can load resources in a fashion appropriate to the particular application context. On the other hand, you may also force ClassPathResource to be used, regardless of the application context type, by specifying the special classpath: prefix:
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");

Similarly, one can force a UrlResource to be used by specifying any of the standard java.net.URL prefixes:
Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt");

Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");

The following table summarizes the strategy for converting Strings to Resources:

3.1

Reference Documentation

145

Spring Framework

Table 5.1. Resource strings Prefix classpath: file: Example Explanation

classpath:com/myapp/config.xml Loaded from the classpath. file:/data/config.xml Loaded as a URL, from the filesystem. 1

http: (none)
1

http://myserver/logo.png Loaded as a URL. /data/config.xml Depends on the underlying ApplicationContext.

But see also the section called “FileSystemResource caveats”.

5.5 The ResourceLoaderAware interface
The ResourceLoaderAware interface is a special marker interface, identifying objects that expect to be provided with a ResourceLoader reference.
public interface ResourceLoaderAware { void setResourceLoader(ResourceLoader resourceLoader); }

When a class implements ResourceLoaderAware and is deployed into an application context (as a Spring-managed bean), it is recognized as ResourceLoaderAware by the application context. The application context will then invoke the setResourceLoader(ResourceLoader), supplying itself as the argument (remember, all application contexts in Spring implement the ResourceLoader interface). Of course, since an ApplicationContext is a ResourceLoader, the bean could also implement the ApplicationContextAware interface and use the supplied application context directly to load resources, but in general, it's better to use the specialized ResourceLoader interface if that's all that's needed. The code would just be coupled to the resource loading interface, which can be considered a utility interface, and not the whole Spring ApplicationContext interface. As of Spring 2.5, you can rely upon autowiring of the ResourceLoader as an alternative to implementing the ResourceLoaderAware interface. The "traditional" constructor and byType autowiring modes (as described in the section called “Autowiring collaborators”) are now capable of providing a dependency of type ResourceLoader for either a constructor argument or setter method parameter respectively. For more flexibility (including the ability to autowire fields and multiple parameter methods), consider using the new annotation-based autowiring features. In that case, the 3.1 Reference Documentation 146

Spring Framework

ResourceLoader will be autowired into a field, constructor argument, or method parameter that is expecting the ResourceLoader type as long as the field, constructor, or method in question carries the @Autowired annotation. For more information, see the section called “@Autowired”.

5.6 Resources as dependencies
If the bean itself is going to determine and supply the resource path through some sort of dynamic process, it probably makes sense for the bean to use the ResourceLoader interface to load resources. Consider as an example the loading of a template of some sort, where the specific resource that is needed depends on the role of the user. If the resources are static, it makes sense to eliminate the use of the ResourceLoader interface completely, and just have the bean expose the Resource properties it needs, and expect that they will be injected into it. What makes it trivial to then inject these properties, is that all application contexts register and use a special JavaBeans PropertyEditor which can convert String paths to Resource objects. So if myBean has a template property of type Resource, it can be configured with a simple string for that resource, as follows:
<bean id="myBean" class="..."> <property name="template" value="some/resource/path/myTemplate.txt"/> </bean>

Note that the resource path has no prefix, so because the application context itself is going to be used as the ResourceLoader, the resource itself will be loaded via a ClassPathResource, FileSystemResource, or ServletContextResource (as appropriate) depending on the exact type of the context. If there is a need to force a specific Resource type to be used, then a prefix may be used. The following two examples show how to force a ClassPathResource and a UrlResource (the latter being used to access a filesystem file).
<property name="template" value="classpath:some/resource/path/myTemplate.txt">

<property name="template" value="file:/some/resource/path/myTemplate.txt"/>

5.7 Application contexts and Resource paths
Constructing application contexts
An application context constructor (for a specific application context type) generally takes a string or array of strings as the location path(s) of the resource(s) such as XML files that make up the definition of the context. When such a location path doesn't have a prefix, the specific Resource type built from that path and 3.1 Reference Documentation 147

Spring Framework

used to load the bean definitions, depends on and is appropriate to the specific application context. For example, if you create a ClassPathXmlApplicationContext as follows:
ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");

The bean definitions will be loaded from the classpath, as a ClassPathResource will be used. But if you create a FileSystemXmlApplicationContext as follows:
ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");

The bean definition will be loaded from a filesystem location, in this case relative to the current working directory. Note that the use of the special classpath prefix or a standard URL prefix on the location path will override the default type of Resource created to load the definition. So this FileSystemXmlApplicationContext...
ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:conf/appContext.xml");

... will actually load its bean definitions from the classpath. However, it is still a FileSystemXmlApplicationContext. If it is subsequently used as a ResourceLoader, any unprefixed paths will still be treated as filesystem paths. Constructing ClassPathXmlApplicationContext instances - shortcuts The ClassPathXmlApplicationContext exposes a number of constructors to enable convenient instantiation. The basic idea is that one supplies merely a string array containing just the filenames of the XML files themselves (without the leading path information), and one also supplies a Class; the ClassPathXmlApplicationContext will derive the path information from the supplied class. An example will hopefully make this clear. Consider a directory layout that looks like this:
com/ foo/ services.xml daos.xml MessengerService.class

A ClassPathXmlApplicationContext instance composed of the beans defined in the 'services.xml' and 'daos.xml' could be instantiated like so...
ApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] {"services.xml", "daos.xml"}, MessengerService.class);

Please do consult the Javadocs for the ClassPathXmlApplicationContext class for details of the various constructors.

3.1

Reference Documentation

148

and is resolved at construction time. In the case of a jar URL. In practice.xml file:C:/some/path/*-context. the resolver follows a more complex but defined procedure to try to resolve the wildcard. Both of the latter are effectively wildcards One use for this mechanism is when doing component-style application assembly.net.xml . for example: /WEB-INF/*-context.Spring Framework Wildcards in application context constructor resource paths The resource paths in application context constructor values may be a simple path (as shown above) which has a one-to-one mapping to a target Resource. or a jar URL of some sort. If the specified path is a classpath location.).1 Reference Documentation 149 ..io. or alternately may contain the special "classpath*:" prefix and/or internal Ant-style regular expressions (matched using Spring's PathMatcher utility). as a resource points to just one resource at a time.File representing the directory. and when the final application context is created using the same path prefixed via classpath*:. there is a portability concern on this operation. It has nothing to do with the Resource type itself.g. etc. Since this is just a node of the path (not the file at the end) it is actually undefined (in the ClassLoader Javadocs) exactly what sort of a URL is returned in this case. Note that this wildcarding is specific to use of resource paths in application context constructors (or when using the PathMatcher utility class hierarchy directly). Implications on portability If the specified path is already a file URL (either explicitly. If this URL is not a "jar:" URL or container-specific variant (e. where the classpath resource resolves to a jar location. If a jar URL is obtained for the last non-wildcard segment. then the resolver must obtain the last non-wildcard path segment URL via a Classloader. Ant-style Patterns When the path location contains an Ant-style pattern. It produces a Resource for the path up to the last non-wildcard segment and obtains a URL from it. Still. It's not possible to use the classpath*: prefix to construct an actual Resource. the resolver either gets a java.io.File is obtained from it and used to resolve the wildcard by traversing the filesystem. "wsjar" in WebSphere. All components can 'publish' context definition fragments to a well-known location path. the resolver must be able to get a 3. it is always a java. then wildcarding is guaranteed to work in a completely portable fashion. where the classpath resource resolves to a filesystem location. then a java. or implicitly because the base ResourceLoader is a filesystem one.xml com/mycompany/**/applicationContext. all component fragments will be picked up automatically..getResource() call.xml classpath:com/mycompany/**/applicationContext. "zip:" in WebLogic.JarURLConnection from it or manually parses the jar URL and then traverses the contents of the jar file to resolve the wildcards.

xml".Spring Framework java. This originates from a limitation in the JDK's ClassLoader. This will work in most environments.JarURLConnection from it.. unless the actual target files reside in the file system. and then merged to form the final application context definition. for example "classpath*:META-INF/*-beans. to be able to walk the contents of the jar.xml" will not retrieve files from the root of jar files but rather only from the root of expanded directories. the behavior might differ especially when dealing with jar files. and it is strongly recommended that the wildcard resolution of resources coming from jars be thoroughly tested in your specific environment before you rely on it. but will fail in others. this essentially happens via a ClassLoader. Ant-style patterns with "classpath:" resources are not guaranteed to find matching resources if the root package to search is available in multiple class path locations.net. A simple test to check if classpath* works is to use the classloader to load a file from within a jar on the classpath: getClass().getClassLoader().. Try this test with files that have the same name but are placed inside two different locations. a location string may use the special classpath*: prefix: ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:conf/appContext.getResources() method which only returns file system locations for a passed-in empty string (indicating potential roots to search).getResources(. This special prefix specifies that all classpath resources that match the given name must be obtained (internally. In case an inappropriate result is returned. As most application servers nowadays supply their own classloader implementation.getResources() call is used on the last non-wildcard path segment to get all the matching resources in the class loader hierarchy. the resolution strategy is fairly simple: a ClassLoader.1 Reference Documentation 150 . or manually parse the jar URL.) call). Classpath*: portability The wildcard classpath relies on the getResources() method of the underlying classloader. The "classpath*:" prefix can also be combined with a PathMatcher pattern in the rest of the location path. This means that a pattern like "classpath*:*. Other notes relating to wildcards Please note that "classpath*:" when combined with Ant-style patterns will only work reliably with at least one root directory before the pattern starts. and resolve the wildcard. check the application server documentation for settings that might affect the classloader behavior.xml").getResources("<someFileInsideTheJar>"). The classpath*: prefix When constructing an XML-based application context. and then off each resource the same PathMatcher resoltion strategy described above is used for the wildcard subpath. This is because a resource such as 3. In this case.

the resolver will work off the (first) URL returned by getResource("com/mycompany"). which will search all class path locations that contain the root package..txt"). // force this FileSystemXmlApplicationContext to load its definition via a UrlResource 3. ctx. relative paths as you would expect.getResource("some/resource/path/myTemplate.txt"). it is better to forgo the use of absolute paths with FileSystemResource / FileSystemXmlApplicationContext. In practice.1 Reference Documentation 151 . a FileSystemApplicationContext is not the actual ResourceLoader) will treat absolute vs. If this base package node exists in multiple classloader locations..txt").Spring Framework com/mycompany/package1/service-context. the actual end resource may not be underneath. In practice. whether they start with a leading slash or not. use "classpath*:" with the same Ant-style pattern in such a case. as one case is relative and the other absolute. and just force the use of a UrlResource.getResource("/some/resource/path/myTemplate. FileSystemXmlApplicationContext ctx = . FileSystemResource caveats A FileSystemResource that is not attached to a FileSystemApplicationContext (that is.. ctx. Therefore..getResource("file:/some/resource/path/myTemplate.. this changes when the FileSystemApplicationContext is the ResourceLoader. // actual context type doesn't matter. if true absolute filesystem paths are needed.xml").xml is used to try to resolve it. Relative paths are relative to the current working directory. but when a path such as classpath:com/mycompany/**/service-context. The FileSystemApplicationContext simply forces all attached FileSystemResource instances to treat all location paths as relative...xml may be in only one location.xml").) FileSystemXmlApplicationContext ctx = . preferably. ApplicationContext ctx = new FileSystemXmlApplicationContext("/conf/context. As are the following: (Even though it would make sense for them to be different. while absolute paths are relative to the root of the filesystem. this means the following are equivalent: ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/context. For backwards compatibility (historical) reasons however. the Resource will always be UrlResource ctx. by using the file: URL prefix.

xml").1 Reference Documentation 152 . 3.Spring Framework ApplicationContext ctx = new FileSystemXmlApplicationContext("file:/conf/context.

and is also explained in this chapter. Specifically validation should not be tied to the web tier.convert" package that provides a general type conversion facility. if you were going to use it at all. which is primarily used in but not limited to the MVC framework.Spring Framework 6. we felt that some explanation might be in order. Considering the above. Spring provides the so-called DataBinder to do exactly that. should be easy to localize and it should be possible to plug in any validator available. you would most likely do so when trying to bind data to objects. and will also be discussed in this chapter. Validation. Spring 3 introduces a "core. The PropertyEditor concept is part of the JavaBeans specification. // the usual getters and setters.1 Introduction There are pros and cons for considering validation as business logic. validators can report validation failures to the Errors object. 6. and Spring offers a design for validation (and data binding) that does not exclude either one of them.. Data Binding. Spring's DataBinder and the lower-level BeanWrapper both use PropertyEditors to parse and format property values. private int age.2 Validation using Spring's Validator interface Spring features a Validator interface that you can use to validate objects. } 3. The Validator interface works using an Errors object so that while validating. The BeanWrapper is a fundamental concept in the Spring Framework and is used in a lot of places. you probably will not have the need to use the BeanWrapper directly. The Validator and the DataBinder make up the validation package.. as well as a higher-level "format" package for formatting UI field values. These new packages may be used as simpler alternatives to PropertyEditors. Data binding is useful for allowing user input to be dynamically bound to the domain model of an application (or whatever objects you use to process user input).1 Reference Documentation 153 . Because this is reference documentation however. We will explain the BeanWrapper in this chapter since. Let's consider a small data object: public class Person { private String name. Spring has come up with a Validator interface that is both basic ands eminently usable in every layer of an application. However. and Type Conversion 6.

"name".rejectIfEmpty(e. it may be better to encapsulate the validation logic for each nested class of object in its own Validator implementation.) method on the ValidationUtils class is used to reject the 'name' property if it is null or the empty string. } else if (p. public CustomerValidator(Validator addressValidator) { if (addressValidator == null) { throw new IllegalArgumentException( "The supplied [Validator] is required and must not be null.empty"). "negativevalue"). Errors e) { ValidationUtils. Address objects may be used independently of Customer objects.").validation. "too. you can dependency-inject or instantiate an AddressValidator within your CustomerValidator. the static rejectIfEmpty(. While it is certainly possible to implement a single Validator class to validate each of the nested objects in a rich object.equals(clazz). and so a distinct AddressValidator has been implemented.rejectValue("age".getAge() > 110) { e..Errors) .Can this Validator validate instances of the supplied Class? • validate(Object.old").class.darn. } if (!addressValidator.springframework.class)) { throw new IllegalArgumentException( "The supplied [Validator] must support the validation of [Address] instances.Validator interface: • supports(Class) . especially when you know of the ValidationUtils helper class that the Spring Framework also provides.rejectValue("age". org. If you want your CustomerValidator to reuse the logic contained within the AddressValidator class without resorting to copy-and-paste. and use it like so: public class CustomerValidator implements Validator { private final Validator addressValidator.1 Reference Documentation 154 .Spring Framework We're going to provide validation behavior for the Person class by implementing the following two methods of the org. } public void validate(Object obj."). } 3. if (p. } } } As you can see.springframework. "name.validation. Person p = (Person) obj.supports(Address. A simple example of a 'rich' object would be a Customer that is composed of two String properties (a first and second name) and a complex Address object.getAge() < 0) { e. Have a look at the Javadoc for the ValidationUtils class to see what functionality it provides besides the example shown previously. registers those with the given Errors object Implementing a Validator is fairly straightforward. public class PersonValidator implements Validator { /** * This Validator validates just Person instances */ public boolean supports(Class clazz) { return Person.validates the given object and in case of validation errors.

old. "field.required"). What error codes it registers is determined by the MessageCodesResolver that is used.darn. When you call (either directly.class. but also a number of additional error codes. but of course you can also inspect the errors object yourself. 6. the underlying implementation will not only register the code you've passed in. apart from the too. the DefaultMessageCodesResolver is used.springframework. try { errors. "too.old. Spring will also register too.rejectIfEmptyOrWhitespace(errors.invokeValidator(this. Errors errors) { ValidationUtils. but also messages that include the field name you passed to the reject method. More information on the MessageCodesResolver and the default strategy can be found online with the Javadocs for MessageCodesResolver and DefaultMessageCodesResolver respectively. ValidationUtils.1 Reference Documentation 155 . and any subclasses of Customer too */ public boolean supports(Class clazz) { return Customer. Customer customer = (Customer) target. errors).pushNestedPath("address").addressValidator = addressValidator. using for example the ValidationUtils class) rejectValue or one of the other reject methods from the Errors interface. } public void validate(Object target.3 Resolving codes to error messages We've talked about databinding and validation. If we're going to output the error messages by using a MessageSource. ValidationUtils.required"). In case of Spring Web MVC you can use <spring:bind/> tag to inspect the error messages.getAddress(). By default. or indirectly. customer. "surname". "field.darn. which for example not only registers a message with the code you gave. } } } Validation errors are reported to the Errors object passed to the validator. "firstName".old").int (so the first will include the field name and the second will include the type of the field). Outputting messages corresponding to validation errors is the last thing we need to discuss. 6.beans package adheres to the JavaBeans standard provided by Sun.age and too.darn. } finally { errors.darn. A 3.popNestedPath().rejectIfEmptyOrWhitespace(errors. In the example we've shown above.Spring Framework this. More information about the methods it offers can be found from the Javadoc.addressValidator.old code.4 Bean manipulation and the BeanWrapper The org.isAssignableFrom(clazz). this is done as a convenience to aid developers in targeting error messages and suchlike. So in case you reject a field using rejectValue("age". } /** * This Validator validates Customer instances. we rejected the name and the age field.age. we will do so using the error code we've given when rejecting the field ('name' and 'age' in this case).

Indexed properties can be of type array. and to query properties to determine if they are readable or writable. Also. Then. The way the BeanWrapper works is partly indicated by its name: it wraps a bean to perform actions on that bean.setName() or getAccount(). The BeanWrapper usually isn't used by application code directly.) Indicates the nested property name of the property account corresponding e.com/products/javabeans). the BeanWrapper supports the ability to add standard JavaBeans PropertyChangeListeners and VetoableChangeListeners.name account[2] account[COMPANYNAME] Indicates the value of the map entry indexed by the key COMPANYNAME of the Map property account Below you'll find some examples of working with the BeanWrapper to get and set properties. For more information about JavaBeans and the specification. As quoted from the Javadoc. If you're just using the DataBinder and the BeanFactory and their out-of-the-box 3. which follows a naming convention where (by way of an example) a property named bingoMadness would have a setter method setBingoMadness(. Examples of properties Expression name Explanation Indicates the property name corresponding to the methods getName() or isName() and setName(. One quite important class in the beans package is the BeanWrapper interface and its corresponding implementation (BeanWrapperImpl). A couple of examples: Table 6.. enabling the setting of properties on sub-properties to an unlimited depth. (This next section is not vitally important to you if you're not planning to work with the BeanWrapper directly. the BeanWrapper offers functionality to set and get property values (individually or in bulk). What's important to know is that there are a couple of conventions for indicating properties of an object. please refer to Sun's website ( java. the BeanWrapper provides support for the setting of indexed properties. like setting and retrieving properties.1.g. Last but not least. list or other naturally ordered collection account.sun.1 Reference Documentation 156 . Setting and getting basic and nested properties Setting and getting properties is done using the setPropertyValue(s) and getPropertyValue(s) methods that both come with a couple of overloaded variants. They're all described in more detail in the Javadoc Spring comes with. the BeanWrapper offers support for nested properties.Spring Framework JavaBean is simply a class with a default no-argument constructor.getName() Indicates the third element of the indexed property account. to the methods getAccount().. but by the DataBinder and the BeanFactory. get property descriptors.) and a getter method getBingoMadness(). without the need for supporting code in the target class.

public String getName() { return this. } public float getSalary() { return salary.1 Reference Documentation 157 .name = name. // retrieving the salary of the managingDirector through the company Float salary = (Float) company.")..setPropertyValue("managingDirector". } public void setSalary(float salary) { this.. } public void setName(String name) { this. jim. "Some Company Inc. private Employee managingDirector.managingDirector = managingDirector. company. } public void setManagingDirector(Employee managingDirector) { this. "Some Company Inc. public String getName() { return this. // ok. } } public class Employee { private String name.name.setPropertyValue(value).salary = salary. can also be done like this: PropertyValue value = new PropertyValue("name".Spring Framework implementation.setPropertyValue("name". you should skip ahead to the section about PropertyEditors.salary").getWrappedInstance()). let's create the director and tie it to the company: BeanWrapper jim = BeanWrapperImpl(new Employee()). } public void setName(String name) { this.managingDirector.name = name.. // setting the company name. "Jim Stravinsky"). private float salary. } } The following code snippets show some examples of how to retrieve and manipulate some of the properties of instantiated Companies and Employees: BeanWrapper company = BeanWrapperImpl(new Company()). company. company.getPropertyValue("managingDirector.) Consider the following two classes: public class Company { private String name.name. jim.setPropertyValue("name"."). // . Built-in PropertyEditor implementations 3. } public Employee getManagingDirector() { return this.

Strings will simply be converted to their corresponding byte representations.PropertyEditor. gives it the knowledge of how to convert properties to the desired type.util. Registering custom editors on a BeanWrapper or alternately in a specific IoC container as mentioned in the previous chapter. Customizable property editor for Boolean properties. supporting a custom DateFormat. Registered by default by BeanWrapperImpl.Spring Framework Spring uses the concept of PropertyEditors to effect the conversion between an Object and a String. Read more about PropertyEditors in the Javadoc of the java. of type java.beans package provided by Sun. Spring has a number of built-in PropertyEditors to make life easy. a Date can be represented in a human readable way (as the String '2007-14-09'). it sometimes might be handy to be able to represent properties in a different way than the object itself. Built-in PropertyEditors Class ByteArrayPropertyEditor Explanation Editor for byte arrays. When mentioning java. back to Date objects). Where the property editor is configurable in some fashion. This behavior can be achieved by registering custom editors.beans. Must be user ClassEditor CustomBooleanEditor CustomCollectionEditor CustomDateEditor 3. Registered by default by BeanWrapperImpl.String as the value of a property of some bean you're declaring in XML file. For example. are registered by default by BeanWrapperImpl. When a class is not found. while we're still able to convert the human readable form back to the original date (or even better: convert any date entered in a human readable form. but not all (as indicated below). but. NOT registered by default.2. A couple of examples where property editing is used in Spring: • setting properties on beans is done using PropertyEditors. • parsing HTTP request parameters in Spring's MVC framework is done using all kinds of PropertyEditors that you can manually bind in all subclasses of the CommandController. Registered by default by BeanWrapperImpl.springframework.propertyeditors package. If you think about it.Date. Each of those is listed below and they are all located in the org. Parses Strings representing classes to actual classes and the other way around. you can of course still register your own variant to override the default one: Table 6. an IllegalArgumentException is thrown. can be overridden by registering custom instance of it as custom editor. converting any source Collection to a given target Collection type.beans.lang. Customizable property editor for java. Most. Property editor for Collections. Spring will (if the setter of the corresponding property has a Class-parameter) use the ClassEditor to try to resolve the parameter to a Class object.1 Reference Documentation 158 .

Registered by default by BeanWrapperImpl. but can be overridden by registering custom instance of it as a custom editor. Capable of resolving Strings to JDK 1. FileEditor InputStreamEditor LocaleEditor PatternEditor PropertiesEditor StringTrimmerEditor URLEditor Spring uses the java. Registered by default by BeanWrapperImpl. Capable of resolving Strings to java. The search path also includes sun.beans. which includes PropertyEditor implementations for types such as Font.File objects. one could have the following class and package structure. which would be sufficient for the FooEditor class to be recognized and used as the PropertyEditor for Foo-typed properties. and most of the primitive types. One-way property editor. Long.lang. Color. which is the same thing the toString() method of Locale provides). CustomNumberEditor Customizable property editor for any Number subclass like Integer.Spring Framework Class Explanation registered as needed with appropriate format. Registered by default by BeanWrapperImpl. Registered by default by BeanWrapperImpl.1 Reference Documentation 159 . with 'Editor' appended. Float.io. Capable of resolving a String representation of a URL to an actual URL object.PropertyEditorManager to set the search path for property editors that might be needed.Properties class) to Properties objects. Optionally allows transforming an empty string into a null value.bean. Capable of resolving Strings to Locale objects and vice versa (the String format is [language]_[country]_[variant]. capable of taking a text string and producing (via an intermediate ResourceEditor and Resource) an InputStream. so InputStream properties may be directly set as Strings. Registered by default by BeanWrapperImpl. Note also that the standard JavaBeans infrastructure will automatically discover PropertyEditor classes (without you having to register them explicitly) if they are in the same package as the class they handle. 3. Capable of converting Strings (formatted using the format as defined in the Javadoc for the java. and have the same name as that class.5 Pattern objects and vice versa. for example. must be user registered as needed.editors. Property editor that trims Strings. Double. Note that the default usage will not close the InputStream for you! Registered by default by BeanWrapperImpl. NOT registered by default.

Foo. public class FooBeanInfo extends SimpleBeanInfo { public PropertyDescriptor[] getPropertyDescriptors() { try { final PropertyEditor numberPE = new CustomNumberEditor(Integer. This would associate a CustomNumberEditor with the age property of the Foo class. }. Spring pre-registers a number of custom PropertyEditors (for example. return new PropertyDescriptor[] { ageDescriptor }. assuming you have a BeanFactory reference. com chank pop Foo FooBeanInfo // the BeanInfo for the Foo class Here is the Java source code for the referenced FooBeanInfo class.class) { public PropertyEditor createPropertyEditor(Object bean) { return numberPE. Another. PropertyDescriptor ageDescriptor = new PropertyDescriptor("age". If there is a need to register other custom PropertyEditors. the CustomEditorConfigurer has a nested property setup. to convert a classname expressed as a string into a real Class object). } catch (IntrospectionException ex) { throw new Error(ex. true). mechanism is to use a special bean factory post-processor called CustomEditorConfigurer. Additionally. Although bean factory post-processors can be used with BeanFactory implementations. Find below an example of using the BeanInfo mechanism for explicitly registering one or more PropertyEditor instances with the properties of an associated class. to be found automatically.class. Java's standard JavaBeans PropertyEditor lookup mechanism allows a PropertyEditor for a class simply to be named appropriately and placed in the same package as the class it provides support for. there are several mechanisms available. slightly more convenient. so it is strongly recommended that it is used with the 3. which is not normally convenient or recommended.Spring Framework com chank pop Foo FooEditor // the PropertyEditor for the Foo class Note that you can also use the standard BeanInfo JavaBeans mechanism here as well (described in not-amazing-detail here). a Spring IoC container ultimately uses standard JavaBeans PropertyEditors to convert these Strings to the complex type of the property.toString()). is to simply use the registerCustomEditor() method of the ConfigurableBeanFactory interface. }. The most manual approach.1 Reference Documentation 160 . } } } Registering additional custom PropertyEditors When setting bean properties as a string value.

1 Reference Documentation 161 . Consider a user class ExoticType.DependsOnExoticType"> <property name="type" value="aNameForExoticType"/> </bean> The PropertyEditor implementation could look similar to this: // converts string representation to ExoticType object package example. CustomEditorConfigurer. a bean factory post-processor. and another class DependsOnExoticType which needs ExoticType set as a property: package example. Standard JavaBeans PropertyEditor instances are used to convert property values expressed as strings to the actual complex type of the property.name = name.Spring Framework ApplicationContext.toUpperCase())). public ExoticType(String name) { this. ApplicationContexts also override or add an additional number of editors to handle resource lookups in a manner appropriate to the specific application context type. } } public class DependsOnExoticType { private ExoticType type. we want to be able to assign the type property as a string. which a PropertyEditor will behind the scenes convert into an actual ExoticType instance: <bean id="sample" class="example. where it may be deployed in similar fashion to any other bean.type = type. may be used to conveniently add support for additional PropertyEditor instances to an ApplicationContext. } } When things are properly set up. public class ExoticTypeEditor extends PropertyEditorSupport { public void setAsText(String text) { setValue(new ExoticType(text. through their use of something called a BeanWrapper to handle property conversions. and automatically detected and applied. } } 3. Additionally. Note that all bean factories and application contexts automatically use a number of built-in property editors. The standard property editors that the BeanWrapper registers are listed in the previous section. public void setType(ExoticType type) { this. public class ExoticType { private String name.

it avoids the need for synchronization on custom editors: a PropertyEditorRegistrar is expected to create fresh PropertyEditor instances for each bean creation attempt. // you could register as many custom property editors as are required here.. First off.): PropertyEditorRegistrars added to a CustomEditorConfigurer in this fashion can easily be shared with DataBinder and Spring MVC Controllers. Notice how in its implementation of the registerCustomEditors(. which will then be able to use it as needed: <bean class="org.1 Reference Documentation 162 .beans.springframework..factory.class.springframework.factory..Spring Framework Finally.config. } } See also the org.ExoticType" value="example. This interface is particularly useful when you need to use the same set of property editors in several different situations: write a corresponding registrar and reuse that in each case.springframework. PropertyEditorRegistrars work in conjunction with an interface called PropertyEditorRegistry.) method it creates new instances of each property editor.ExoticTypeEditor"/> </map> </property> </bean> Using PropertyEditorRegistrars Another mechanism for registering property editors with the Spring container is to create and use a PropertyEditorRegistrar.editors.support. we use CustomEditorConfigurer to register the new PropertyEditor with the ApplicationContext.spring. which exposes a property called setPropertyEditorRegistrars(. public final class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar { public void registerCustomEditors(PropertyEditorRegistry registry) { // it is expected that new PropertyEditor instances are created registry. PropertyEditorRegistrars are particularly convenient when used in conjunction with the CustomEditorConfigurer (introduced here).config.registerCustomEditor(ExoticType.beans.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="example.ResourceEditorRegistrar for an example PropertyEditorRegistrar implementation. Furthermore.foo.CustomEditorConfigurer"> <property name="propertyEditorRegistrars"> <list> <ref bean="customPropertyEditorRegistrar"/> 3. you need to create your own PropertyEditorRegistrar implementation: package com. Using a PropertyEditorRegistrar is perhaps best illustrated with an example. new ExoticTypeEditor()). an interface that is implemented by the Spring BeanWrapper (and DataBinder). Next we configure a CustomEditorConfigurer CustomPropertyEditorRegistrar into it: and inject an instance of our <bean class="org.beans..

} // other methods to do with registering a User } This style of PropertyEditor registration can lead to concise code (the implementation of initBinder(. Within a Spring container.registerCustomEditors(binder). public RegisterUserController(PropertyEditorRegistrar propertyEditorRegistrar) { this. T> { T convert(S source).converter.) is just one line long!).) method: public final class RegisterUserController extends SimpleFormController { private final PropertyEditorRegistrar customPropertyEditorRegistrar. as well as an API to execute type conversions at runtime. The public API may also be used anywhere in your application where type conversion is needed. The system defines an SPI to implement type conversion logic.foo. public interface Converter<S.1 Reference Documentation 163 .convert.editors.convert package that provides a general type conversion system.CustomPropertyEditorRegistrar"/> Finally.spring.Spring Framework </list> </property> </bean> <bean id="customPropertyEditorRegistrar" class="com.springframework. } protected void initBinder(HttpServletRequest request.core. Find below an example of using a PropertyEditorRegistrar in the implementation of an initBinder(. for those of you using Spring's MVC web framework. 6. } 3. this system can be used as an alternative to PropertyEditors to convert externalized bean property value strings to required property types.customPropertyEditorRegistrar.customPropertyEditorRegistrar = propertyEditorRegistrar. ServletRequestDataBinder binder) throws Exception { this. and in a bit of a departure from the focus of this chapter.5 Spring 3 Type Conversion Spring 3 introduces a core.. Converter SPI The SPI to implement type conversion logic is simple and strongly typed: package org.. and allows common PropertyEditor registration code to be encapsulated in a class and then shared amongst as many Controllers as needed. using PropertyEditorRegistrars in conjunction with data-binding Controllers (such as SimpleFormController) can be very convenient.

Parameterize S as the type you are converting from. } private final class StringToEnumConverter<T extends Enum> implements Converter<String. For each call to convert(S). Several converter implementations are provided in the core.lang. final class StringToInteger implements Converter<String.core.converter. for example. Your Converter may throw any Exception if conversion fails.valueOf(source). when converting from String to java.core. implement ConverterFactory: package org.1 Reference Documentation 164 . public interface ConverterFactory<S. T> getConverter(Class<T> targetType) { return new StringToEnumConverter(targetType).springframework.enumType.support.Enum objects. simply implement the interface above. Then implement getConverter(Class<T>). Consider the StringToEnum ConverterFactory as an example: package org. R> { <T extends R> Converter<S.support.convert. the source argument is guaranteed to be NOT null. 3.convert.support package as a convenience.core. } } ConverterFactory When you need to centralize the conversion logic for an entire class hierarchy. and T as the type you are converting to. Take care to ensure your Converter implementation is thread-safe.springframework. public StringToEnumConverter(Class<T> enumType) { this. An IllegalArgumentException should be thrown to report an invalid source value. Integer> { public Integer convert(String source) { return Integer. Consider StringToInteger as an example Converter implementation: package org.trim()). } Parameterize S to be the type you are converting from and R to be the base type defining the range of classes you can convert to.springframework.convert. T> getConverter(Class<T> targetType).convert.enumType = enumType. } public T convert(String source) { return (T) Enum. Enum> { public <T extends Enum> Converter<String.Spring Framework To create your own Converter. T> { private Class<T> enumType. These include converters from Strings to Numbers and other common types.valueOf(this. source. where T is a subclass of R. final class StringToEnumConverterFactory implements ConverterFactory<String.

a GenericConverter makes available source and target field context you can use when implementing your conversion logic. TypeDescriptor. TypeDescriptor targetType). you might only want to execute a Converter if a specific annotation is present on the target field.convert. With a more flexible but less strongly typed signature. ConditionalGenericConverter Sometimes you only want a Converter to execute if a specific condition holds true.springframework. Note Because GenericConverter is a more complex SPI interface. Then implement convert(Object. TypeDescriptor sourceType. Such context allows a type conversion to be driven by a field annotation. such as static valueOf method. package org. TypeDescriptor targetType). } 3. For example. Object convert(Object source. In addition. TypeDescriptor) to implement your conversion logic. Or you might only want to execute a Converter if a specific method. Such an ArrayToCollectionConverter introspects the field that declares the target Collection type to resolve the Collection's element type. have getConvertibleTypes() return the supported source->target type pairs. A good example of a GenericConverter is a converter that converts between a Java Array and a Collection. Favor Converter or ConverterFactory for basic type conversion needs. is defined on the target class. ConditionalGenericConverter is an subinterface of GenericConverter that allows you to define such custom matching criteria: public interface ConditionalGenericConverter extends GenericConverter { boolean matches(TypeDescriptor sourceType.core. or generic information declared on a field signature.Spring Framework } } } GenericConverter When you require a sophisticated Converter implementation. This allows each element in the source array to be converted to the Collection element type before the Collection is set on the target field. The source TypeDescriptor provides access to the source field holding the value being converted.1 Reference Documentation 165 .converter. The target TypeDescriptor provides access to the target field where the converted value will be set. consider the GenericConverter interface. only use it when you need it. public interface GenericConverter { public Set<ConvertiblePair> getConvertibleTypes(). } To implement a GenericConverter. a GenericConverter supports converting between multiple source and target types.

Class<?> targetType). ConversionServiceFactory provides a convenient factory for creating common ConversionService configurations. findAccount(Long). <T> T convert(Object source. Class<T> targetType). You would perform such a finder method check in the implementation of matches(TypeDescriptor. Such a EntityConverter might only match if the target entity type declares a static finder method e. Configuring a ConversionService A ConversionService is a stateless object designed to be instantiated at application startup. which provides an SPI for registering converters. TypeDescriptor targetType). Note If no ConversionService is registered with Spring. Internally.convert. In a Spring application. You may also inject this ConversionService into any of your beans and invoke it directly. then shared between multiple threads. public interface ConversionService { boolean canConvert(Class<?> sourceType. TypeDescriptor sourceType.core. a ConversionService implementation delegates to its registered converters to carry out type conversion logic. the original PropertyEditor-based system is used. ConversionService API The ConversionService defines a unified API for executing type conversion logic at runtime. GenericConversionService is the general-purpose implementation suitable for use in most environments.convert.g. To register a default ConversionService with Spring. Converters are often executed behind this facade interface: package org.support package. That ConversionService will be picked up by Spring and then used whenever a type conversion needs to be performed by the framework. boolean canConvert(TypeDescriptor sourceType. Object convert(Object source. TypeDescriptor targetType).springframework. } Most ConversionService implementations also implement ConverterRegistry.1 Reference Documentation 166 . add the following bean definition with id 3.Spring Framework A good example of a ConditionalGenericConverter is an EntityConverter that converts between an persistent entity identifier and an entity reference. A robust ConversionService implementation is provided in the core. you typically configure a ConversionService instance per Spring container (or ApplicationContext). TypeDescriptor).

For example. or GenericConverter interfaces. To suppliment or override the default converters with your own custom converter(s). } public void doIt() { this. both the Spring Expression Language (SpEL) and DataBinder use this system to bind field values.context.. It provides a unified ConversionService API as well as a strongly-typed Converter SPI for implementing conversion logic from one type to another.springframework.MyCustomConverter"/> </list> </property> </bean> It is also common to use a ConversionService within a Spring MVC application.convert is a general-purpose type conversion system. ConverterFactory. A Spring Container uses this system to bind bean property values. maps. numbers. See the section called “Configuring Formatting in Spring MVC” for details on use with <mvc:annotation-driven/>. <bean id="conversionService" class="org.context.convert(.ConversionServiceFactoryBean"/> A default ConversionService can convert between strings.support.conversionService..support. and other common types. when SpEL needs to coerce a Short to a Long to complete an 3. core. Property values may implement either of the Converter. In addition. Using a ConversionService programatically To work with a ConversionService instance programatically.Spring Framework conversionService: <bean id="conversionService" class="org.1 Reference Documentation 167 . simply inject a reference to it like you would for any other bean: @Service public class MyService { @Autowired public MyService(ConversionService conversionService) { this.springframework. collections.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="example. See the section called “FormatterRegistry SPI” for details on using FormattingConversionServiceFactoryBean.6 Spring 3 Field Formatting As discussed in the previous section.conversionService = conversionService. In certain situations you may wish to apply formatting during conversion. set the converters property.) } } 6. enums.

java. Parameterize T to be the type of object you wish to format. The ConversionService provides a unified type conversion API for both SPIs.Long. Parser<T> { } Where Formatter extends from the Printer and Parser building-block interfaces: public interface Printer<T> { String print(T fieldValue.joda package provides comprehensive datetime formatting support based on the Joda Time library.lang. The datetime. for example. for example. In general.Date objects with a java. Locale locale) throws ParseException.lang.Date. In addition.NumberFormat.convert system performs the coercion.util. simply implement the Formatter interface above.util. Implement the parse() operation to parse an instance of T from the formatted representation returned from the client locale.DateFormat. Formatter SPI The Formatter SPI to implement field formatting logic is simple and strongly typed: package org. CurrencyFormatter. as well as back to String to support the view rendering process.Number objects using a java. Your Formatter should throw a ParseException or IllegalArgumentException if a parse attempt fails. public interface Formatter<T> extends Printer<T>.convert Converter SPI does not address such formatting requirements directly.Spring Framework expression.text. Spring 3 introduces a convenient Formatter SPI that provides a simple and robust alternative to PropertyEditors for client environments. Locale locale).springframework. } To create your own Formatter.ParseException. use the Converter SPI when you need to implement general-purpose type conversion logic. 3. Object value) attempt.util. the core. public interface Parser<T> { T parse(String clientValue. Implement the print() operation to print an instance of T for display in the client locale. Use the Formatter SPI when you're working in a client environment. The number package provides a NumberFormatter.setValue(Object bean. you typically convert from String to support the client postback process. The more general core.text. you often need to localize String values. such as a web application.format. Now consider the type conversion requirements of a typical client environment such as a web or desktop application. To directly address them. The datetime package provides a DateFormatter to format java. } import java. Several Formatter implementations are provided in format subpackages as a convenience. Take care to ensure your Formatter implementation is thread-safe. and PercentFormatter to format java.Date and and java.text. In such environments. for converting between a java.1 Reference Documentation 168 . and need to parse and print localized field values.

springframework. } public Date parse(String formatted. public interface AnnotationFormatterFactory<A extends Annotation> { Set<Class<?>> getFieldTypes().Spring Framework Consider DateFormatter as an example Formatter implementation: package org. } return getDateFormat(locale). public final class DateFormatter implements Formatter<Date> { private String pattern.DateTimeFormat.length() == 0) { return null.setLenient(false).datetime. Have getFieldTypes() return the types of fields the annotation may be used on. locale). return dateFormat. } return getDateFormat(locale). Printer<?> getPrinter(A annotation. Locale locale) throws ParseException { if (formatted. Have getPrinter() return a Printer to print the value of an annotated field. Class<?> fieldType). } Parameterize A to be the field annotationType you wish to associate formatting logic with. Have getParser() return a Parser to parse a 3. field formatting can be configured by field type or annotation.parse(formatted).org to contribute.pattern.1 Reference Documentation 169 . Formatter contributions. for example org. see Annotation-driven Formatting As you will see. To bind an Annotation to a formatter.springframework. } protected DateFormat getDateFormat(Locale locale) { DateFormat dateFormat = new SimpleDateFormat(this. dateFormat.format. Locale locale) { if (date == null) { return "".annotation.format. Parser<?> getParser(A annotation.format. Class<?> fieldType). } public String print(Date date.springframework.springframework. public DateFormatter(String pattern) { this.pattern = pattern. implement AnnotationFormatterFactory: package org.format(date). } } The Spring team welcomes community-driven http://jira.

if (style == Style.class })).CURRENCY) { return new CurrencyFormatter(). Long.util. fieldType).util.CURRENCY) private BigDecimal decimal. fieldType).class.class.Number fields.Date as a ISO Date (yyyy-MM-dd): public class MyModel { @DateTimeFormat(iso=ISO. BigDecimal.Calendar.PERCENT) { return new PercentFormatter(). simply annotate fields with @NumberFormat: public class MyModel { @NumberFormat(style=Style.class.class.Spring Framework clientValue for an annotated field. Use @DateTimeFormat to format java. } Format Annotation API A portable format annotation API exists in the org.1 Reference Documentation 170 . Use @NumberFormat to format java. Float. The example below uses @DateTimeFormat to format a java. Integer. 3. } else { Style style = annotation.style(). } private Formatter<Number> configureFormatterFrom(NumberFormat annotation.annotation package.util. } } } } To trigger formatting. Class<?> fieldType) { if (!annotation. } public Printer<Number> getPrinter(NumberFormat annotation.class.Date.class. } public Parser<Number> getParser(NumberFormat annotation. java. BigInteger.lang.Long. The example AnnotationFormatterFactory implementation below binds the @NumberFormat Annotation to a formatter.util. } else if (style == Style.pattern().pattern()). Class<?> fieldType) { return configureFormatterFrom(annotation. or Joda Time fields. java.springframework. This annotation allows either a number style or pattern to be specified: public final class NumberFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<NumberFormat> { public Set<Class<?>> getFieldTypes() { return new HashSet<Class<?>>(asList(new Class<?>[] { Short.format. } else { return new NumberFormatter().DATE) private Date date.isEmpty()) { return new NumberFormatter(annotation. Class<?> fieldType) { return configureFormatterFrom(annotation. Double.

The FormatterRegistry SPI allows you to configure Formatting rules centrally. Formatters can be registered by fieldType or annotation. It can also be useful where declarative registration is insufficient. With a shared FormatterRegistry. The next section provides more information on 3. ?> factory).springframework.springframework. } A FormatterRegistrar is useful when registering multiple related converters and formatters for a given formatting category. void addFormatterForAnnotation(AnnotationFormatterFactory<?. you might want to enforce that all Date fields are formatted a certain way. void addFormatterForFieldType(Class<?> fieldType. Parser<?> parser). it can be directly configured for use with Spring's DataBinder and the Spring Expression Language (SpEL). Review the FormatterRegistry SPI below: package org. public interface FormatterRegistrar { void registerFormatters(FormatterRegistry registry).1 Reference Documentation 171 . FormattingConversionService is an implementation of FormatterRegistry suitable for most environments. } As shown above. void addFormatterForFieldType(Formatter<?> formatter). For example when a formatter needs to be indexed under a specific field type different from its own <T> or when registering a Printer/Parser pair.format. For example. public interface FormatterRegistry extends ConverterRegistry { void addFormatterForFieldType(Class<?> fieldType. you define these rules once and they are applied whenever formatting is needed. Because this implemementation also implements ConversionService. FormatterRegistrar SPI The FormatterRegistrar is an SPI for registering formatters and converters through the FormatterRegistry: package org. such as Date formatting. instead of duplicating such configuration across your Controllers. Printer<?> printer.Spring Framework } FormatterRegistry SPI The FormatterRegistry is an SPI for registering formatters and converters. or fields with a specific annotation are formatted in a certain way.format. This implementation may be configured programatically or declaratively as a Spring bean using FormattingConversionServiceFactoryBean. Formatter<?> formatter).

0" encoding="UTF-8"?> <beans xmlns="http://www.support.MyConverter"/> </set> </property> <property name="formatters"> <set> 3.springframework.springframework.xsd http://www.format.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.0. Spring MVC will automatically register default formatters and converters for common types such as numbers and dates.springframework. Full support for the Joda Time formatting library is also installed if Joda Time is present on the classpath. To inject a ConversionService instance with custom formatters and converters registered.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="org.springframework.org/schema/mvc http://www.org/schema/mvc" xmlns:xsi="http://www. If not configured explicitly.springframework.springframework.xsd"> <mvc:annotation-driven/> </beans> With this one-line of configuation.xsd"> <mvc:annotation-driven conversion-service="conversionService"/> <bean id="conversionService" class="org.springframework. you may configure a custom ConversionService instance explicity as an attribute of the annotation-driven element of the MVC namespace.xsd http://www.org/schema/beans http://www. Configuring Formatting in Spring MVC In a Spring MVC application. default formatters for Numbers and Date types will be installed.springframework. set the conversion-service attribute and then specify custom converters.Spring Framework converter and formatter registration.org/schema/mvc" xmlns:xsi="http://www.org/schema/beans" xmlns:mvc="http://www.1 Reference Documentation 172 .0" encoding="UTF-8"?> <beans xmlns="http://www.w3.org/schema/beans/spring-beans-3. no custom configuration is required in your Spring MVC config XML: <?xml version="1.org/schema/mvc/spring-mvc-3.0.springframework.org/schema/beans" xmlns:mvc="http://www.org/schema/beans/spring-beans-3.w3.springframework.example.org/schema/mvc http://www. or FormatterRegistrars as properties of the FormattingConversionServiceFactoryBean: <?xml version="1.0.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.org/schema/beans http://www.springframework. This ConversionService will then be used anytime a type conversion is required during Controller model binding.org/schema/mvc/spring-mvc-3. To rely on default formatting rules. including support for the @NumberFormat and @DateTimeFormat annotations. formatters.0.springframework.

7 Spring 3 Validation Spring 3 introduces several enhancements to its validation support.MyAnnotationFormatterFactory"/> </set> </property> <property name="formatterRegistrars"> <set> <bean class="org. private int age.Spring Framework <bean class="org. when used programatically.example. @Min(0) private int age. Second. Overview of the JSR-303 Bean Validation API JSR-303 standardizes validation constraint declaration and metadata for the Java platform.MyFormatter"/> <bean class="org. There are a number of built-in constraints you can take advantage of. To illustrate.example. You may also define your own custom constraints. } 3.MyFormatterRegistrar"/> </set> </property> </bean> </beans> Note See the section called “FormatterRegistrar SPI” and the FormattingConversionServiceFactoryBean for more information on when to use FormatterRegistrars. } JSR-303 allows you to define declarative validation constraints against such properties: public class PersonForm { @NotNull @Size(max=64) private String name. consider a simple PersonForm model with two properties: public class PersonForm { private String name. First. you annotate domain model properties with declarative validation constraints and the runtime enforces them.1 Reference Documentation 173 . Third. Spring's DataBinder can now validate objects as well as bind to them.example. 6. Using this API. the JSR-303 Bean Validation API is now fully supported. Spring MVC now has support for declaratively validating @Controller inputs.

validation. is expected to be present in the classpath and will be detected automatically.Validator to be injected wherever validation is needed in your application. This allows for a javax.Validator. Inject a reference to org. To learn how to setup a JSR-303 implementation as a Spring bean. @Service public class MyService { @Autowired private Validator validator.validation.validation.Validator if your bean requires the Spring Validation API: import org.ValidatorFactory and javax.validation.validation.Spring Framework When an instance of this class is validated by a JSR-303 Validator.validation.springframework.ValidatorFactory or javax. these constraints will be enforced.validation.beanvalidation. Inject a reference to javax. 3. This includes convenient support for bootstrapping a JSR-303 implementation as a Spring bean.validation.validation.Validator. @Service public class MyService { @Autowired private Validator validator. keep reading. For information on the specific capabilities of the default reference implementation.LocalValidatorFactoryBean"/> The basic configuration above will trigger JSR-303 to initialize using its default bootstrap mechanism. Use the LocalValidatorFactoryBean to configure a default JSR-303 Validator as a Spring bean: <bean id="validator" class="org. such as Hibernate Validator.1 Reference Documentation 174 . For general information on JSR-303.Validator. as well as Spring's org.springframework.Validator.validation. see the Bean Validation Specification. Injecting a Validator LocalValidatorFactoryBean implements both javax. A JSR-303 provider. You may inject a reference to either of these interfaces into beans that need to invoke validation logic. see the Hibernate Validator documentation.springframework. Configuring a Bean Validation Implementation Spring provides full support for the JSR-303 Bean Validation API.springframework.Validator if you prefer to work with the JSR-303 API directly: import javax.

each @Constraint annotation references a corresponding ValidationConstraint implementation class. ElementType.. Configuring a DataBinder Since Spring 3. an implementation of the javax..class) public @interface MyConstraint { } import javax.FIELD}) @Retention(RetentionPolicy.1 Reference Documentation 175 . Shown below is an example of a custom @Constraint declaration. To associate a declaration with an implementation. At runtime. See the JavaDocs of LocalValidatorFactoryBean for more information on these options.RUNTIME) @Constraint(validatedBy=MyConstraintValidator.validation. a @Constraint annotation that declares the constraint and its configurable properties.ConstraintValidator. a ConstraintValidatorFactory instantiates the referenced implementation when the constraint annotation is encountered in your domain model.validation. a ConstraintValidator implementation may have its dependencies @Autowired like any other Spring bean.Spring Framework } Configuring Custom Constraints Each JSR-303 validation constraint consists of two parts. There are a number of other configuration options for various JSR-303 constructs. public class MyConstraintValidator implements ConstraintValidator { @Autowired. Additional Configuration Options The default LocalValidatorFactoryBean configuration should prove sufficient for most cases.METHOD. followed by an associated ConstraintValidator implementation that uses Spring for dependency injection: @Target({ElementType. from message interpolation to traversal resolution. By default. Second. the Validator 3. private Foo aDependency.ConstraintValidator interface that implements the constraint's behavior. } As you can see. a DataBinder instance can be configured with a Validator. the LocalValidatorFactoryBean configures a SpringConstraintValidatorFactory that uses Spring to create ConstraintValidator instances. . First. Once configured. This allows your custom ConstraintValidators to benefit from dependency injection like any other Spring bean.

. First.1 Reference Documentation 176 . Spring MVC 3 Validation Beginning with Spring 3.POST) public void processFoo(@Valid Foo foo) { /* . this can be used to invoke validation logic after binding to a target object: Foo target = new Foo().setValidator(new FooValidator()). binder. In previous versions it was up to the developer to manually invoke validation logic. DataBinder binder = new DataBinder(target). // bind to the target object binder. Note The @Valid annotation is part of the standard JSR-303 Bean Validation API. // get BindingResult that includes any validation errors BindingResult results = binder.bind(propertyValues). */ } Spring MVC will validate a @Valid object after binding so-long as an appropriate Validator has been configured. When working with the DataBinder programatically. you may call binder. method=RequestMethod. and is not a Spring-specific construct.validate(). Configuring a Validator for use by Spring MVC The Validator instance invoked when a @Valid method argument is encountered may be configured in two ways.validate().Spring Framework may be invoked by calling binder. This allows you to configure a Validator instance per @Controller class: @Controller public class MyController { 3..getBindingResult(). Any validation Errors are automatically added to the binder's BindingResult.setValidator(Validator) within a @Controller's @InitBinder callback. // validate the target object binder. simply annotate the input argument as @Valid: @Controller public class MyController { @RequestMapping("/foo". Triggering @Controller Input Validation To trigger validation of a @Controller input. Spring MVC has the ability to automatically validate @Controller inputs.

springframework. Spring MVC will detect it and automatically enable JSR-303 support across all Controllers.springframework.org/schema/mvc http://www.. you may call setValidator(Validator) on the global WebBindingInitializer.org/schema/beans" xmlns:mvc="http://www..org/schema/mvc/spring-mvc-3.springframework. JSR-303.0" encoding="UTF-8"?> <beans xmlns="http://www. Any ConstraintViolations will automatically be exposed as errors in the BindingResult renderable by standard Spring MVC form tags. simply add a JSR-303 Provider. anytime a @Valid @Controller input is encountered.POST) public void processFoo(@Valid Foo foo) { .setValidator(new FooValidator()). in turn.validation.springframework. it will be validated by the JSR-303 provider.0. } } Second.xsd http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.springframework.JSR-303 support will be detected on classpath and enabled automatically --> <mvc:annotation-driven/> </beans> With this minimal configuration.xsd"> <mvc:annotation-driven validator="globalValidator"/> </beans> Configuring a JSR-303 Validator for use by Spring MVC With JSR-303.org/schema/beans" xmlns:mvc="http://www. This allows you to configure a Validator instance across all @Controllers.0.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.springframework.0. 3.xsd http://www.org/schema/beans http://www.org/schema/mvc" xmlns:xsi="http://www.xsd"> <!-. To configure a JSR-303-backed Validator with Spring MVC.0.org/schema/mvc/spring-mvc-3. a single javax.org/schema/beans http://www. to your classpath. } @RequestMapping("/foo".w3. will enforce any constraints declared against the input.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.0" encoding="UTF-8"?> <beans xmlns="http://www.Validator instance typically validates all model objects that declare validation constraints.springframework.1 Reference Documentation 177 .springframework.org/schema/beans/spring-beans-3.org/schema/mvc http://www.w3. such as Hibernate Validator.org/schema/beans/spring-beans-3. method=RequestMethod.springframework. The Spring MVC configuration required to enable JSR-303 support is shown below: <?xml version="1. This can be achieved easily by using the Spring MVC namespace: <?xml version="1.springframework.Spring Framework @InitBinder protected void initBinder(WebDataBinder binder) { binder.

In several places an Inventor and Inventor's Society class are used as the target objects for expression evaluation. This chapter covers the features of the expression language. to name a few. While SpEL serves as the foundation for expression evaluation within the Spring portfolio. it is not directly tied to Spring and can be used independently. lists. and its language syntax.2 Feature Overview The expression language supports the following functionality • Literal expressions • Boolean and relational operators • Regular expressions • Class expressions • Accessing properties. and JBoss EL. In order to be self contained. The language syntax is similar to Unified EL but offers additional features.1 Reference Documentation 178 .Spring Framework 7. arrays. Most Spring users will not need to deal with this infrastructure and will instead only author expression strings for evaluation. That said. the Spring Expression Language was created to provide the Spring community with a single well supported expression language that can be used across all the products in the Spring portfolio. many of the examples in this chapter use SpEL as if it were an independent expression language. OGNL. 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.1 Introduction The Spring Expression Language (SpEL for short) is a powerful expression language that supports querying and manipulating an object graph at runtime. Spring Expression Language (SpEL) 7. An example of this typical use is the integration of SpEL into creating XML or annotated based bean definitions as shown in the section Expression support for defining bean definitions. SpEL is based on a technology agnostic API allowing other expression language implementations to be integrated should the need arise. maps • Method invocation 3. MVEL. its API. 7. While there are several other Java expression languages available. These class declarations and the data used to populate them are listed at the end of the chapter. most notably method invocation and basic string templating functionality. This requires creating a few bootstrapping infrastructure classes such as the parser.

3 Expression Evaluation using Spring's Expression Interface This section introduces the simple use of SpEL interfaces and its expression language.springframework. String message = (String) exp. The interface ExpressionParser is responsible for parsing an expression string. Expression exp = parser. ExpressionParser parser = new SpelExpressionParser(). The value of the message variable is simply 'Hello World'. ParseException and EvaluationException when calling 'parser. The SpEL classes and interfaces you are most likely to use are located in the packages org. The interface Expression is responsible for evaluating the previously defined expression string.parseExpression("'Hello World'").support.getValue' respectively.1 Reference Documentation 179 .expression and its sub packages and spel. 3. The following code introduces the SpEL API to evaluate the literal string expression 'Hello World'. The complete language reference can be found in the section Language Reference.Spring Framework • Relational operators • Assignment • Calling constructors • Bean references • Array construction • Inline lists • Ternary operator • Variables • User defined functions • Collection projection • Collection selection • Templated expressions 7.parseExpression' and 'exp.getValue(). In this example the expression string is a string literal denoted by the surrounding single quotes. There are two exceptions that can be thrown.

byte[] bytes = (byte[]) exp. ExpressionParser parser = new SpelExpressionParser(). Expression exp = parser.concat('!')").toUpperCase()").parseExpression("'Hello World'. Using this method removes the need to cast the value of the expression to the desired result type. ExpressionParser parser = new SpelExpressionParser(). As an example of calling a JavaBean property.bytes"). c. String message = exp.set(1856.getValue(). There are two options here and which to choose depends on whether the object against which the expression is being evaluated will be changing with each call to evaluate the expression. such as calling methods.e. i. // invokes 'getBytes(). 7. prop1.prop2. As an example of method invocation. and calling constructors. Note the use of the generic method public <T> T getValue(Class<T> desiredResultType).getValue(). The more common usage of SpEL is to provide an expression string that is evaluated against a specific object instance (called the root object).length"). An EvaluationException will be thrown if the value cannot be cast to the type T or converted using the registered type converter. // Create and set a calendar GregorianCalendar c = new GregorianCalendar(). the String property 'Bytes' can be called as shown below. Expression exp = parser. ExpressionParser parser = new SpelExpressionParser(). // invokes 'getBytes()' Expression exp = parser.parseExpression("new String('hello world'). 9).bytes. The value of message is now 'Hello World!'. ExpressionParser parser = new SpelExpressionParser(). accessing properties.getValue(String. 3.parseExpression("'Hello World'.prop3 and the setting of property values Public fields may also be accessed. int length = (Integer) exp. String message = (String) exp. The String's constructor can be called instead of using a string literal. In the following example we retrieve the name property from an instance of the Inventor class. we call the 'concat' method on the string literal. SpEL also supports nested properties using standard 'dot' notation.parseExpression("'Hello World'.getValue().Spring Framework SpEL supports a wide range of features.class).1 Reference Documentation 180 .length' Expression exp = parser.

The StandardEvaluationContext is relatively expensive to construct and during repeated usage it builds up cached state that enables subsequent expression evaluations to be performed more quickly.getValue(tesla). EvaluationContext context = new StandardEvaluationContext(tesla).getValue(context). String name = (String) exp. c. In these situations the root object passed on the call is considered to override any (which maybe null) specified on the evaluation context.parseExpression("name"). root object and any predefined variables are all set up implicitly. the value of the string variable 'name' will be set to "Nikola Tesla". 9). it can be supplied on each call to getValue. and nationality. for example for Spring bean or Spring Web Flow definitions. birthday. Note In standalone usage of SpEL there is a need to create the parser. evaluation context. In this case. Inventor tesla = new Inventor("Nikola Tesla". String name = (String) exp. Inventor tesla = new Inventor("Nikola Tesla".Spring Framework // The constructor arguments are name. as this next example shows: / Create and set a calendar GregorianCalendar c = new GregorianCalendar(). it can simply be set once in the evaluation context. The class StandardEvaluationContext is where you can specify which object the "name" property will be evaluated against. parse expressions and perhaps provide evaluation contexts and a root context object. birthday. If the root object is likely to change repeatedly. In this case the inventor tesla has been supplied directly to getValue and the expression evaluation infrastructure creates and manages a default evaluation context internally . This is the mechanism to use if the root object is unlikely to change. more common usage is to provide only the SpEL expression string as part of a configuration file. However.set(1856. the parser. In some cases it can be desirable to use a configured evaluation context and yet still supply a different root object on each call to getValue.it did not require one to be supplied. rather than construct a new one for each expression evaluation. In the last line. getValue allows both to be specified on the same call. 7. ExpressionParser parser = new SpelExpressionParser(). For this reason it is better to cache and reuse them where possible. Expression exp = parser.1 Reference Documentation 181 . c. "Serbian").getTime(). and nationality. c. Expression exp = parser.parseExpression("name"). requiring the user to specify nothing other than the expressions.getTime(). 3. "Serbian"). // The constructor arguments are name. ExpressionParser parser = new SpelExpressionParser().

MethodResolvers. The out-of-the-box implementation. This means that when working with generic types in expressions.1 Reference Documentation 182 . // b will be false Boolean b = simple.class). The StandardEvaluationContext is where you may specify the root object to evaluate against via the method setRootObject() or passing the root object into the constructor. SpEL will attempt conversions to maintain type correctness for any objects it encounters. The StandardEvaluationContext is also where you can register custom ConstructorResolvers.lang. caching java. A simple example: class Simple { public List<Boolean> booleanList = new ArrayList<Boolean>().ConversionService). You can also specify variables and functions that will be used in the expression using the methods setVariable() and registerFunction().add(true). and PropertyAccessors to extend how SpEL evaluates expressions. Boolean. // evaluates to true The EvaluationContext interface The interface EvaluationContext is used when evaluating an expression to resolve properties. fields.parseExpression("booleanList[0]").booleanList. Please refer to the JavaDoc of these classes for more details. boolean result = exp. The type of the property is actually List<Boolean>. What does this mean in practice? Suppose assignment. Expression exp = parser. the use of a boolean operator is shown using the Inventor object in the previous example. simple. StandardEvaluationContext simpleContext = new StandardEvaluationContext(simple).get(0). using setValue().setValue(simpleContext. Additionally it has the key capability that it is generics aware.springframework. uses reflection to manipulate the object. and Constructor instances for increased performance.booleanList. } Simple simple = new Simple(). StandardEvaluationContext.getValue(context.core. is being used to set a List property. and to help perform type conversion. 3. This conversion service comes with many converters built in for common conversions but is also fully extensible so custom conversions between types can be added. Field. The use of variables and functions are described in the language reference sections Variables and Functions. SpEL and the conversion service will // correctly recognize that it needs to be a Boolean and convert it parser.Spring Framework As a final introductory example. "false").convert. methods. // false is passed in here as a string. Type Conversion By default SpEL uses the conversion service available in Spring core (org.parseExpression("name == 'Nikola Tesla'").reflect's Method. SpEL will recognize that the elements of the list need to be converted to Boolean before being placed in it.

In both cases the syntax to define the expression is of the form #{ <expression string> }.spring.ShapeGuess"> <property name="initialShapeSeed" value="#{ numberGuess. for example.other properties --> </bean> You can also refer to other bean properties by name.randomNumber }"/> <!-. <bean id="taxCalculator" class="org.other properties --> </bean> Annotation-based configuration The @Value annotation can be placed on fields.0 }"/> <!-. public static class FieldValueTestBean @Value("#{ systemProperties['user.Math).spring.region'] }") private String defaultLocale.TaxCalculator"> <property name="defaultLocale" value="#{ systemProperties['user.lang.region'] }"/> <!-.samples. <bean id="numberGuess" class="org.4 Expression support for defining bean definitions SpEL expressions can be used with XML or annotation based configuration metadata for defining BeanDefinitions.samples.spring. Note that you do not have to prefix the predefined variable with the '#' symbol in this context.random() * 100.spring. 3.other properties --> </bean> The variable 'systemProperties' is predefined.samples.samples.random() * 100. so you can use it in your expressions as shown below.1 Reference Documentation 183 .NumberGuess"> <property name="randomNumber" value="#{ T(java.other properties --> </bean> <bean id="shapeGuess" class="org.NumberGuess"> <property name="randomNumber" value="#{ T(java. XML based configuration A property or constructor-arg value can be set using expressions as shown below <bean id="numberGuess" class="org. methods and method/constructor parameters to specify a default value.Math).lang.Spring Framework 7. Here is an example to set the default value of a field variable.0 }"/> <!-.

this. @Autowired public void configure(MovieFinder movieFinder. @Autowired public MovieRecommender(CustomerPreferenceDao customerPreferenceDao. @Value("#{systemProperties['user.region'] }"} String defaultLocale) { this.Spring Framework public void setDefaultLocale(String defaultLocale) { this. public class SimpleMovieLister { private MovieFinder movieFinder. private CustomerPreferenceDao customerPreferenceDao.1 Reference Documentation 184 . this.customerPreferenceDao = customerPreferenceDao. } } The equivalent but on a property setter method is shown below..defaultLocale = defaultLocale. public static class PropertyValueTestBean private String defaultLocale.defaultLocale = defaultLocale.defaultLocale = defaultLocale.defaultLocale. } // .. @Value("#{ systemProperties['user.movieFinder = movieFinder. @Value("#{ systemProperties['user.region'] }") public void setDefaultLocale(String defaultLocale) { this. } public String getDefaultLocale() { return this. } public class MovieRecommender { private String defaultLocale. } public String getDefaultLocale() { return this. } } Autowired methods and constructors can also use the @Value annotation.defaultLocale = defaultLocale.country']}"} String defaultLocale) { this.defaultLocale. private String defaultLocale. } 3.

numeric values (int. // evals to "Hello World" String helloWorld = (String) parser. just use a period to indicate a nested property value. Case insensitivity is allowed for the first letter of property names. Maps. // evals to 2147483647 int maxValue = (Integer) parser. were populated with data listed in the section Classes used in the examples.getValue().parseExpression("true"). To navigate "down" and get Tesla's year of birth and Pupin's city of birth the following expressions are used. boolean and null.parseExpression("null"). and decimal points.parseExpression("0x7FFFFFFF"). Object nullValue = parser.0221415E+23"). To put a single quote itself in a string use two single quote characters.5 Language Reference Literal expressions The types of literal expressions supported are strings.parseDouble(). Lists. // Inventions Array StandardEvaluationContext teslaContext = new StandardEvaluationContext(tesla).parseExpression("Birthdate. exponential notation. but as part of a more complex expression. Numbers support the use of the negative sign. boolean trueValue = (Boolean) parser. Indexers Navigating with property references is easy. real.Year + 1900").getValue().City").getValue(). By default real numbers are parsed using Double..parseExpression("6. The instances of Inventor class. Strings are delimited by single quotes. ExpressionParser parser = new SpelExpressionParser(). // evals to 1856 int year = (Integer) parser. Typically they would not be used in isolation like this. The contents of arrays and lists are obtained using square bracket notation. pupin and tesla.1 Reference Documentation 185 .Spring Framework // . Properties. 3. and hex).getValue(). Arrays.getValue(context). double avogadrosNumber = (Double) parser. for example using a literal on one side of a logical comparison operator. } 7. String city = (String) parser.parseExpression("placeOfBirth. dates..getValue().getValue(context). The following listing shows simple usage of literals.parseExpression("'Hello World'"). ExpressionParser parser = new SpelExpressionParser().

getValue(teslaContext.getValue(societyContext. {} by itself means an empty list.1 Reference Documentation 186 . Inventor.class). because keys for the Officers map are strings. List listOfLists = (List) parser.parseExpression("inventions[3]"). // evaluates to "Nikola Tesla" String name = parser.getValue(context).parseExpression("Officers['president'].parseExpression("Members[0].Name").parseExpression("Officers['advisors'][0].{'x'.parseExpression("{1.class).2. String. // evaluates to a Java list containing the four numbers List numbers = (List) parser.class).City"). In this case. // setting values parser. if the list is itself entirely composed of fixed literals then a constant list is created to represent the expression. // evaluates to "Idvor" String city = parser.'y'}}"). String.parseExpression("new int[4]").4}"). Array construction Arrays can be built using the familiar Java syntax. // Array with initializer 3. // List and Array navigation // evaluates to "Wireless communication" String invention = parser. "Croatia").'b'}.3.parseExpression("Members[0].setValue(societyContext.getValue(societyContext. // Members List StandardEvaluationContext societyContext = new StandardEvaluationContext(ieee). For performance reasons. String. we can specify string literals.Country"). rather than building a new list on each evaluation.PlaceOfBirth.getValue(societyContext.class).PlaceOfBirth. String. Inline lists Lists can be expressed directly in an expression using {} notation. int[] numbers1 = (int[]) parser.parseExpression("{{'a'.Inventions[6]"). // Officer's Dictionary Inventor pupin = parser.getValue(societyContext. The contents of maps are obtained by specifying the literal key value within the brackets.getValue(context).class).parseExpression("Officers['president']").getValue(context).Spring Framework // evaluates to "Induction motor" String invention = parser. optionally supplying an initializer to have the array populated at construction time.

getValue(String.getValue(Boolean. // evaluates to true boolean trueValue = parser. In addition to standard relational operators SpEL supports the 'instanceof' and regular expression based 'matches' operator.class). and greater than or equal are supported using standard operator notation.class). 3)"). // string literal.00' matches '^-?\\d+(\\. not equal.parseExpression("new int[]{1. less than.class).class). Boolean.parseExpression("'abc'. evaluates to "bc" String c = parser.getValue(Boolean.parseExpression("'xyz' instanceof T(int)").getValue(societyContext.class). Each symbolic operator can also be specified as a purely alphabetic equivalent.substring(2. It is not currently allowed to supply an initializer when constructing a multi-dimensional array.parseExpression("2 < -5.class).getValue(Boolean.\\d{2})?$'"). // evaluates to true boolean trueValue = parser.0067' matches '^-?\\d+(\\.class). greater than.parseExpression("2 == 2").parseExpression("isMember('Mihajlo Pupin')").Spring Framework int[] numbers2 = (int[]) parser.0"). // evaluates to true boolean isMember = parser. The textual equivalents are shown here: lt ('<').getValue(Boolean. le ('<=').2. // evaluates to false boolean falseValue = parser.parseExpression("'5.getValue(Boolean. // evaluates to false boolean falseValue = parser.1 Reference Documentation 187 .getValue(context). gt ('>').getValue(context). an XML document). ge ('>='). // evaluates to true boolean trueValue = parser.class).\\d{2})?$'"). You may also invoke methods on literals. eq 3. This avoids problems where the symbols used have special meaning for the document type in which the expression is embedded (eg. Varargs are also supported.3}").getValue(Boolean. //evaluates to false boolean falseValue = parser.parseExpression("'5. Methods Methods are invoked using typical Java programming syntax. Operators Relational operators The relational operators. less than or equal.parseExpression("'black' < 'block'").parseExpression("new int[4][5]"). equal. // Multi dimensional array int[][] numbers3 = (int[][]) parser.

parseExpression("1000.getValue(Boolean. Subtraction can be used on numbers and dates. Boolean.class).parseExpression("'test' + ' ' + 'string'").getValue(societyContext. // Subtraction int four = parser.getValue(Integer.class).class).parseExpression("2. // Addition int two = parser.class).getValue(Boolean. These are case insensitive. not ('!'). div ('/'). // 24. boolean trueValue = parser.parseExpression("true and false"). // -9000 // Multiplication int six = parser. strings and dates. // -.class). // 2 String testString = parser.OR -// evaluates to true boolean trueValue = parser.parseExpression(expression).getValue(Double.parseExpression("!true").Spring Framework ('==').1 Reference Documentation 188 .-3").NOT -// evaluates to false boolean falseValue = parser.getValue(Double.0 * 3e0 * 4").class). // -. Boolean. // 6 double twentyFour = parser.AND and NOT -String expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')".getValue(Integer.class). boolean trueValue = parser. Their use is demonstrated below.parseExpression("1 . Boolean.class).AND -// evaluates to false boolean falseValue = parser. Mathematical operators The addition operator can be used on numbers.0 // Division // 'test string' 3.class).parseExpression("true or false"). // evaluates to true String expression = "isMember('Nikola Tesla') or isMember('Albert Einstien')". boolean falseValue = parser.class). mod ('%'). Logical operators The logical operators that are supported are and.getValue(Boolean. // -. // 4 double d = parser.class).class). // evaluates to true String expression = "isMember('Nikola Tesla') and isMember('Mihajlo Pupin')".getValue(societyContext.parseExpression(expression).parseExpression("1 + 1").00 . Multiplication and division can be used only on numbers. // -.getValue(Integer.getValue(String.1e4").parseExpression("-2 * -3").getValue(societyContext. or. Standard operator precedence is enforced. These operators are demonstrated below.parseExpression(expression). ne ('!='). and not. Other mathematical operators supported are modulus (%) and exponential power (^).

parseExpression("new org.Class (the 'type').getValue(inventorContext. Constructors Constructors can be invoked using the new operator. "Alexander Seovic2").getValue(Inventor.CEILING < T(java. 'German')") . The StandardEvaluationContext uses a TypeLocator to find types and the StandardTypeLocator (which can be replaced) is built with an understanding of the java.class).Date)"). but all other type references must be.parseExpression("8 / 5 % 2").parseExpression("T(String)").class).RoundingMode). // -2 double one = parser.math. // 3 int one = parser. This would typically be done within a call to setValue but can also be done inside a call to getValue.getValue(Integer. Inventor inventor = new Inventor(). The fully qualified class name should be used for all but the primitive type and String (where int. Class stringClass = parser.getValue(Integer.parseExpression("T(java.Spring Framework int minusTwo = parser.spel.parseExpression("7 % 4"). boolean trueValue = parser.class).class). // alternatively String aleks = parser. This means T() references to types within java.setValue(inventorContext.Inventor('Albert Einstein'.0 // Modulus int three = parser.RoundingMode). etc.class).FLOOR") .getValue(Boolean.spring. // 1 // Operator precedence int minusTwentyOne = parser.parseExpression("T(java.parseExpression("Name").parseExpression("1+2-3*8"). Inventor einstein = p.class).class).getValue(Double. parser.lang. // -21 Assignment Setting of a property is done by using the assignment operator.parseExpression("6 / -3").lang package. Class dateClass = parser.inventor. StandardEvaluationContext inventorContext = new StandardEvaluationContext(inventor).getValue(Integer. 3. String.util. Static methods are invoked using this operator as well.samples.getValue(Integer. float. Types The special 'T' operator can be used to specify an instance of java.1 Reference Documentation 189 . can be used).class).math.parseExpression("8.lang do not need to be fully qualified.parseExpression("Name = 'Alexandar Seovic'"). // 1.class).getValue(Class.0 / 4e0 / 2").class).getValue(Class.

parseExpression("Name = #newName").getName()) // "Mike Tesla" The #this and #root variables The variable #this is always defined and refers to the current evaluation object (against which unqualified references are resolved). primes.primes).asList(2.13. For example. Variables Variables can be referenced in the expression using the syntax #variableName. context.setVariable("newName".inventor.Spring Framework //create new inventor instance within add method of List p.Inventor('Albert Einstein'. The function is registered with the StandardEvaluationContext using the method.out. // all prime numbers > 10 from the list (using selection ?{. public abstract class StringUtils { public static String reverseString(String input) { StringBuilder backwards = new StringBuilder().}) // evaluates to [11. StandardEvaluationContext context = new StandardEvaluationContext(tesla).println(tesla.getValue(context). "Mike Tesla"). Functions You can extend SpEL by registering user defined functions that can be called within the expression string. #root always refers to the root.1 Reference Documentation 190 .. // create parser and set variable 'primes' as the array of integers ExpressionParser parser = new SpelExpressionParser(). 'German'))") . public void registerFunction(String name. // create an array of integers List<Integer> primes = new ArrayList<Integer>().samples. Method m) A reference to a Java Method provides the implementation of the function. Although #this may vary as components of an expression are evaluated.3..5. System.spring.spel. Variables are set using the method setVariable on the StandardEvaluationContext.add(new org. "Serbian"). 3.parseExpression("Members. context. Inventor tesla = new Inventor("Nikola Tesla". a utility method to reverse a string is shown below.setVariable("primes".getValue(context).getValue(societyContext).17)). StandardEvaluationContext context = new StandardEvaluationContext(). parser.7.parseExpression("#primes.addAll(Arrays. 17] List<Integer> primesGreaterThanTen = (List<Integer>) parser.11.?[#this>10]"). 13. The variable #root is always defined and refers to the root context object.

class). "IEEE"). String queryResultString = parser.parseExpression("#reverseString('hello')").toString().length() . context.class).setVariable("queryName". expression = "isMember(#queryName)? #queryName + ' is a member of the ' " + "+ Name + ' Society' : #queryName + ' is not a member of the ' + Name + ' Society'".getDeclaredMethod("reverseString". StandardEvaluationContext context = new StandardEvaluationContext(). StringUtils. String. // This will end up calling resolve(context. parser.class.getValue(String.parseExpression("Name"). } return backwards.setBeanResolver(new MyBeanResolver()). ExpressionParser parser = new SpelExpressionParser().class).parseExpression("@foo"). StandardEvaluationContext context = new StandardEvaluationContext().i)). ExpressionParser parser = new SpelExpressionParser(). } } This method is then registered with the evaluation context and can be used within an expression string.class })).getValue(context). A minimal example is: String falseString = parser.charAt(input.Spring Framework for (int i = 0.setValue(societyContext. the boolean false results in returning the string value 'falseExp'. societyContext.1 Reference Documentation 191 . 3.registerFunction("reverseString".1 . new Class[] { String."foo") on MyBeanResolver during evaluation Object bean = parser.parseExpression(expression). A more realistic example is shown below. "Nikola Tesla"). context. i < input. i++) backwards.length(). In this case. Ternary Operator (If-Then-Else) You can use the ternary operator for performing if-then-else conditional logic inside the expression. String.getValue(context. // queryResultString = "Nikola Tesla is a member of the IEEE Society" Also see the next section on the Elvis operator for an even shorter syntax for the ternary operator.parseExpression("false ? 'trueExp' : 'falseExp'"). Bean references If the evaluation context has been configured with a bean resolver it is possible to lookup beans from an expression using the (@) symbol.append(input. String helloWorldReversed = parser.getValue(societyContext.

class).out. city = parser. String. Instead you can use the Elvis operator.class).1 Reference Documentation 192 . StandardEvaluationContext context = new StandardEvaluationContext(tesla).out.setName(null). StandardEvaluationContext context = new StandardEvaluationContext(tesla). // Mike Tesla tesla. "Serbian").parseExpression("PlaceOfBirth?. // null . System. String name = parser. // Smiljan tesla. // 'Unknown' Here is a more complex example.out. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. String. System. String city = parser.println(city).out. Inventor tesla = new Inventor("Nikola Tesla".println(city).getValue(context. System.City").println(name). // Elvis Presley Safe Navigation operator The Safe Navigation operator is used to avoid a NullPointerException and comes from the Groovy language. ExpressionParser parser = new SpelExpressionParser(). String.parseExpression("Name?:'Elvis Presley'"). System.setPlaceOfBirth(new PlaceOfBirth("Smiljan")).setPlaceOfBirth(null). ExpressionParser parser = new SpelExpressionParser().class). System. named for the resemblance to Elvis' hair style.getValue(context. To avoid this. String displayName = name != null ? name : "Unknown".out.parseExpression("PlaceOfBirth?.println(name).println(name). for example: String name = "Elvis Presley". String.City").does not throw NullPointerException!!! 3.getValue(context. Inventor tesla = new Inventor("Nikola Tesla". the safe navigation operator will simply return null instead of throwing an exception. String name = parser.getValue(String. name = parser. ExpressionParser parser = new SpelExpressionParser(). "Serbian").parseExpression("null?:'Unknown'"). With the ternary operator syntax you usually have to repeat a variable twice.getValue(context.class).class).parseExpression("Name?:'Elvis Presley'"). tesla.Spring Framework The Elvis Operator The Elvis operator is a shortening of the ternary operator syntax and is used in the Groovy language.

'Idvor' ] List placesOfBirth = (List)parser.. This will filter the collection and return a new collection containing a subset of the original elements.g.]. 3. Selection is possible upon both lists and maps.parseExpression("Members.. This expression will return a new map consisting of those elements of the original map where the entry value is less than 27.1 Reference Documentation 193 .parseExpression("map. To obtain the first entry matching the selection the syntax is ^[.getValue(). In the former case the selection criteria is evaluated against each individual list element whilst against a map the selection criteria is evaluated against each map entry (objects of the Java type Map. Using projection: // returns [ 'Smiljan'. Map entries have their key and value accessible as properties for use in the selection.parseExpression("Members. The syntax for projection is ![projectionExpression].. Collection Projection Projection allows a collection to drive the evaluation of a sub-expression and the result is a new collection.Spring Framework Note The Elvis operator can be used to apply default values in expressions. e. For example.?[Nationality == 'Serbian']").city' for every entry in the inventor list.port'] ?: 25}") This will inject a system property pop3. Most easily understood by example.?[value<27]"). In addition to returning all the selected elements. in an @Value expression: @Value("#{systemProperties['pop3. Selection uses the syntax ?[selectionExpression].city]"). suppose we have a list of inventors but want the list of cities where they were born.Entry).. selection would allow us to easily get a list of Serbian inventors: List<Inventor> list = (List<Inventor>) parser.] whilst to obtain the last matching selection the syntax is $[. Collection Selection Selection is a powerful expression language feature that allows you to transform some source collection into another by selecting from its entries.getValue(societyContext). Effectively we want to evaluate 'placeOfBirth. Map newMap = parser.port if it is defined or 25 if not. it is possible to retrieve just the first or the last value.![placeOfBirth.

The definition of TemplateParserContext is shown below. The second argument to the method parseExpression() is of the type ParserContext. PlaceOfBirth placeOfBirth.parseExpression("random number is #{T(java. import java. The result of a projection across a map is a list consisting of the evaluation of the projection expression against each map entry. new TemplateParserContext()).util.getValue(String.Math). a common choice is to use #{ } as the delimiters.java package org. } } 7. // evaluates to "random number is 0. 3.1 Reference Documentation 194 . in this case the result of calling that random() method. For example. } public String getExpressionSuffix() { return "}".lang. String nationality.Spring Framework A map can also be used to drive projection and in this case the projection expression is evaluated against each entry in the map (represented as a Java Map.spring.6 Classes used in the examples Inventor.GregorianCalendar.class).Entry). Expression templating Expression templates allow a mixing of literal text with one or more evaluation blocks.random()}".7038186818312008" The string is evaluated by concatenating the literal text 'random number is ' with the result of evaluating the expression inside the #{ } delimiter. import java. public class Inventor { private private private private private String name. public class TemplateParserContext implements ParserContext { public String getExpressionPrefix() { return "#{". Each evaluation block is delimited with prefix and suffix characters that you can define. String[] inventions.inventor. Date birthdate.samples.spel.util. String randomPhrase = parser.Date. The ParserContext interface is used to influence how the expression is parsed in order to support the expression templating functionality. } public boolean isTemplate() { return true.

inventions = inventions.spring. this.birthdate = birthdate. String nationality) { this.1 Reference Documentation 195 .birthdate = birthdate. } public PlaceOfBirth(String city. String country) { this(city).spel.placeOfBirth = placeOfBirth. } public String getNationality() { return nationality. public PlaceOfBirth(String city) { this. } public Inventor() { } public String getName() { return name. } public void setPlaceOfBirth(PlaceOfBirth placeOfBirth) { this.nationality = nationality. } 3. } public void setNationality(String nationality) { this. String nationality) { GregorianCalendar c= new GregorianCalendar().getTime(). this. } } PlaceOfBirth. } public Inventor(String name.city=city.name = name. } public PlaceOfBirth getPlaceOfBirth() { return placeOfBirth.birthdate = c.samples. } public void setBirthdate(Date birthdate) { this. Date birthdate.name = name.name = name.inventor. this. } public Date getBirthdate() { return birthdate. } public void setName(String name) { this. this. } public String[] getInventions() { return inventions.nationality = nationality. public class PlaceOfBirth { private String city.country = country.nationality = nationality.Spring Framework public Inventor(String name. } public void setInventions(String[] inventions) { this. private String country. this.java package org. this.

1 Reference Documentation 196 .spring. } } return found. public static String Advisors = "advisors". break. public class Society { private String name.equals(name)) { found = true. } public String getName() { return name. } public void setCountry(String country) { this. } public boolean isMember(String name) { boolean found = false. } public void setCity(String s) { this. } } Society. } public String getCountry() { return country.getName().*.country = country. private Map officers = new HashMap().util. } } 3.name = name.city = s.inventor.samples. public List getMembers() { return members. import java. for (Inventor inventor : members) { if (inventor. } public Map getOfficers() { return officers. } public void setName(String name) { this.java package org. public static String President = "president". private List<Inventor> members = new ArrayList<Inventor>().spel.Spring Framework public String getCity() { return city.

Spring Framework 3.1 Reference Documentation 197 .

and @AspectJ-based AOP support is discussed in this chapter. • . you do not need to work directly with Spring AOP. The Spring 2.. These terms are not Spring-specific..1 Introduction Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure.0 AOP Spring 2. AOP terminology is not particularly intuitive. Aspect Oriented Programming with Spring 8. it would be even more confusing if Spring used its own terminology. • Aspect: a modularization of a concern that cuts across multiple classes. unfortunately. AOP is used in the Spring Framework to. If you are interested only in generic declarative services or other pre-packaged declarative middleware services such as pooling.2 APIs is discussed in the following chapter. meaning you do not need to use AOP if you don't want to. especially as a replacement for EJB declarative services. however. provide declarative enterprise services. The most important such service is declarative transaction management. while still using Spring AOP for weaving. and the lower-level AOP support offered by the Spring 1..0 schema. complementing their use of OOP with AOP.) One of the key components of Spring is the AOP framework. and can skip most of this chapter.. whereas in AOP the unit of modularity is the aspect. Transaction management is a 3.1 Reference Documentation 198 .2 AOP. Both of these styles offer fully typed advice and use of the AspectJ pointcut language. allow users to implement custom aspects.. AOP concepts Let us begin by defining some central AOP concepts and terminology. • .. Spring 2.. Spring 2. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. While the Spring IoC container does not depend on AOP.0 AOP remains fully backwards compatible with Spring 1. The key unit of modularity in OOP is the class. AOP complements Spring IoC to provide a very capable middleware solution.0 introduces a simpler and more powerful way of writing custom aspects using either a schema-based approach or the @AspectJ annotation style. (Such concerns are often termed crosscutting concerns in AOP literature.Spring Framework 8..

Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example. and Spring uses the AspectJ pointcut expression language by default. • Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. For example. an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy. model an advice as an interceptor. (An introduction is known as an inter-type declaration in the AspectJ community. (Advice types are discussed below. including Spring. the execution of a method with a certain name). • Pointcut: a predicate that matches join points. you could use an introduction to make a bean implement an IsModified interface. to simplify caching. • AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). like other pure Java AOP frameworks. • Advice: action taken by an aspect at a particular join point.) Many AOP frameworks. Also referred to as the advised object. Around advice can perform custom behavior before and after the method 3. this object will always be a proxied object.1 Reference Documentation 199 . • Join point: a point during the execution of a program. Since Spring AOP is implemented using runtime proxies. Different types of advice include "around. performs weaving at runtime. but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception). maintaining a chain of interceptors around the join point. Types of advice: • Before advice: Advice that executes before a join point. • After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return)." "before" and "after" advice. In Spring AOP. The concept of join points as matched by pointcut expressions is central to AOP. if a method returns without throwing an exception. In the Spring Framework. • Weaving: linking aspects with other application types or objects to create an advised object. In Spring AOP. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. This can be done at compile time (using the AspectJ compiler. for example).Spring Framework good example of a crosscutting concern in enterprise Java applications. or at runtime. such as the execution of a method or the handling of an exception. aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style). a join point always represents a method execution. load time.) • Target object: object being advised by one or more aspects. Spring AOP. • After returning advice: Advice to be executed after a join point completes normally: for example. • Introduction: declaring additional methods or fields on behalf of a type. • After throwing advice: Advice to be executed if a method exits by throwing an exception.

although an around advice can accomplish the same thing. Using the most specific advice type provides a simpler programming model with less potential for errors. you are better off implementing an after returning advice than an around advice. Pointcuts enable advice to be targeted independently of the Object-Oriented hierarchy. However. For example. for example. if you need only to update a cache with the return value of a method. the Spring Framework's AOP functionality is normally used in conjunction with the Spring IoC container. Spring AOP capabilities and goals Spring AOP is implemented in pure Java. Aspects are configured using normal bean definition syntax (although this allows powerful "autoproxying" capabilities): this is a crucial difference from other AOP implementations. Thus. our experience is that Spring AOP provides an excellent solution to most problems in enterprise Java applications that are amenable to AOP. matched by pointcuts.0. In Spring 2. Spring AOP's approach to AOP differs from that of most other AOP frameworks. There is no need for a special compilation process. you do not need to invoke the proceed() method on the JoinPoint used for around advice. Around advice is the most general kind of advice. For example. Spring AOP does not need to control the class loader hierarchy. If you need to advise field access and update join points. Field interception is not implemented. we recommend that you use the least powerful advice type that can implement the required behavior.Spring Framework invocation. There are some things you cannot do easily or efficiently with Spring AOP.1 Reference Documentation 200 . Since Spring AOP. and is thus suitable for use in a Servlet container or application server. and hence cannot fail to invoke it. The concept of join points. like AspectJ. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception. is the key to AOP which distinguishes it from older technologies offering only interception. Spring AOP currently supports only method execution join points (advising the execution of methods on Spring beans). 3. consider a language such as AspectJ. it is rather to provide a close integration between AOP implementation and Spring IoC to help solve common problems in enterprise applications. provides a full range of advice types. an around advice providing declarative transaction management can be applied to a set of methods spanning multiple objects (such as all business operations in the service layer). although support for field interception could be added without breaking the core Spring AOP APIs. such as advise very fine-grained objects (such as domain objects typically): AspectJ is the best choice in such cases. The aim is not to provide the most complete AOP implementation (although Spring AOP is quite capable). all advice parameters are statically typed. so that you work with advice parameters of the appropriate type (the type of the return value from a method execution for example) rather than Object arrays. For example.

1 Reference Documentation 201 . You have the choice of AspectJ and/or Spring AOP. One such choice that is relevant to this chapter is that of which AOP framework (and which AOP style) to choose. This integration does not affect the Spring AOP API or the AOP Alliance API: Spring AOP remains backward-compatible. We believe that both proxy-based frameworks like Spring AOP and full-blown frameworks such as AspectJ are valuable. See the following chapter for a discussion of the Spring AOP APIs. See Section 8. rather than interfaces. This enables any interface (or set of interfaces) to be proxied. or where you need to pass a proxied object to a method as a concrete type. Spring AOP can also use CGLIB proxies. As it is good practice to program to interfaces rather than classes. It is possible to force the use of CGLIB.0 seamlessly integrates Spring AOP and IoC with AspectJ. The Spring Framework (almost) always offers you the choice though: you have the freedom to make an informed decision as to which option best suits your particular use case or scenario. Spring 2. CGLIB is used by default if a business object does not implement an interface. in some places the Spring Framework does give you the option to introduce Spring Framework-specific dependencies into your codebase: the rationale in giving you such options is because in certain scenarios it might be just plain easier to read or code some specific piece of functionality in such a way. However. to enable all uses of AOP to be catered for within a consistent Spring-based application architecture. This is necessary to proxy classes. “Choosing which AOP declaration style to use” for a more complete discussion of the whys and wherefores of each style. and you also have the choice of either the @AspectJ annotation-style approach or the Spring XML configuration-style approach. See the section called “Understanding AOP proxies” for a thorough examination of exactly what this implementation detail actually means. this is the idea that you should not be forced to introduce framework-specific classes and interfaces into your business/domain model. business classes normally will implement one or more business interfaces. The fact that this chapter chooses to introduce the @AspectJ-style approach first should not be taken as an indication that the Spring team favors the @AspectJ annotation-style approach over the Spring XML configuration-style.4.Spring Framework Spring AOP will never strive to compete with AspectJ to provide a comprehensive AOP solution. in those (hopefully rare) cases where you need to advise a method that is not declared on an interface. It is important to grasp the fact that Spring AOP is proxy-based. Note One of the central tenets of the Spring Framework is that of non-invasiveness. 3. and that they are complementary. AOP Proxies Spring AOP defaults to using standard J2SE dynamic proxies for AOP proxies. rather than in competition.

pointing to a bean class that has the @Aspect annotation: 3. Using the AspectJ compiler and weaver enables use of the full AspectJ language. it will automatically generate a proxy for that bean to intercept method invocations and ensure that advice is executed as needed.annotation. The @AspectJ support is enabled by including the following element inside your spring configuration: <aop:aspectj-autoproxy/> This assumes that you are using schema support as described in Appendix C. and autoproxying beans based on whether or not they are advised by those aspects. This library is available in the 'lib' directory of an AspectJ distribution or via the Maven Central repository.aspectj.1 Reference Documentation 202 . Spring 2. See the section called “The aop schema” for how to import the tags in the aop namespace. The @AspectJ style was introduced by the AspectJ project as part of the AspectJ 5 release. Enabling @AspectJ Support To use @AspectJ aspects in a Spring configuration you need to enable Spring support for configuring Spring AOP based on @AspectJ aspects.jar library on the classpath of your application. “Using AspectJ with Spring applications”. version 1.aop. it is still possible to enable @AspectJ support by adding the following definition to your application context: <bean class="org. Declaring an aspect With the @AspectJ support enabled.8 or later. By autoproxying we mean that if Spring determines that a bean is advised by one or more aspects. If you are using the DTD.AnnotationAwareAspectJAutoProxyCreator" /> You will also need AspectJ's aspectjrt.0 interprets the same annotations as AspectJ 5.Spring Framework 8. any bean defined in your application context with a class that is an @AspectJ aspect (has the @Aspect annotation) will be automatically detected by Spring and used to configure Spring AOP.2 @AspectJ support @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations. The following example shows the minimal definition required for a not-very-useful aspect: A regular bean definition in the application context.springframework. and there is no dependency on the AspectJ compiler or weaver. XML Schema-based configuration. using a library supplied by AspectJ for pointcut parsing and matching.8. The AOP runtime is still pure Spring AOP though. and is discussed in Section 8.6.

An example will help make this distinction between a pointcut signature and a pointcut expression clear.Spring Framework <bean id="myAspect" class="org.xyz. Advising aspects with other aspects? In Spring AOP.just like any other Spring-managed bean. package org.aspectj. or autodetect them through classpath scanning . you need to add a separate @Component annotation (or alternatively a custom stereotype annotation that qualifies.xyz.annotation.NotVeryUsefulAspect"> <!-. Declaring a pointcut Recall that pointcuts determine join points of interest.lang. a pointcut signature is provided by a regular method definition. A pointcut declaration has two parts: a signature comprising a name and any parameters. However.aspectj. and a pointcut expression that determines exactly which method executions we are interested in. note that the @Aspect annotation is not sufficient for autodetection in the classpath: For that purpose. The following example defines a pointcut named 'anyOldTransfer' that will match the execution of any method named 'transfer': 3. so you can think of a pointcut as matching the execution of methods on Spring beans. In the @AspectJ annotation-style of AOP. Spring AOP only supports method execution join points for Spring beans. as per the rules of Spring's component scanner). @Aspect public class NotVeryUsefulAspect { } definition. annotated with Aspects (classes annotated with @Aspect) may have methods and fields just like any other class. The @Aspect annotation on a class marks it as an aspect. They may also contain pointcut. import org. and introduction (inter-type) declarations.1 Reference Documentation 203 .Aspect annotation. and the pointcut expression is indicated using the @Pointcut annotation (the method serving as the pointcut signature must have a void return type). and thus enable us to control when advice executes.Aspect. Autodetecting aspects through component scanning You may register aspect classes as regular beans in your Spring XML configuration. advice.configure properties of aspect here as normal --> </bean> And the NotVeryUsefulAspect class org.lang.annotation. and hence excludes it from auto-proxying. it is not possible to have aspects themselves be the target of advice from other aspects.

.limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type(s) 3. These are: call.Spring Framework @Pointcut("execution(* transfer(.))")// the pointcut expression private void anyOldTransfer() {}// the pointcut signature The pointcut expression that forms the value of the @Pointcut annotation is a regular AspectJ 5 pointcut expression.limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type • @args .limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type • target . the AspectJ 5 Developers Notebook) or one of the books on AspectJ such as “Eclipse AspectJ” by Colyer et. For a full discussion of AspectJ's pointcut language. cflowbelow. preinitialization. Use of these pointcut designators in pointcut expressions interpreted by Spring AOP will result in an IllegalArgumentException being thrown. Supported Pointcut Designators Spring AOP supports the following AspectJ pointcut designators (PCD) for use in pointcut expressions: Other pointcut types The full AspectJ pointcut language supports additional pointcut designators that are not supported in Spring. al. if. The set of pointcut designators supported by Spring AOP may be extended in future releases to support more of the AspectJ pointcut designators. see the AspectJ Programming Guide (and for Java 5 based extensions. withincode. • execution .limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type • args . adviceexecution.for matching method execution join points.limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP) • this .limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types • @target . or “AspectJ in Action” by Ramnivas Laddad. set. cflow. staticinitialization.1 Reference Documentation 204 . initialization. handler. this is the primary pointcut designator you will use when working with Spring AOP • within . @this. and @withincode. get.

limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation Because Spring AOP limits matching to only method execution join points. This constitutes a different mode of AOP usage with different characteristics. The 'bean' PCD has the following form: bean(idOrNameOfBean) The 'idOrNameOfBean' token can be the name of any Spring bean: limited wildcard support using the '*' character is provided. This PCD allows you to limit the matching of join points to a particular named Spring bean. so be sure to make yourself familiar with weaving first before making a decision.Spring Framework • @within . or to a set of named Spring beans (when using wildcards). the discussion of the pointcut designators above gives a narrower definition than you will find in the AspectJ programming guide. Spring AOP also supports an additional PCD named 'bean'.the object executing the method. The 'bean' PCD operates at the instance level (building on the Spring bean name concept) rather than at the type level only (which is what weaving-based AOP is limited to). Instance-based pointcut designators are a special capability of Spring's proxy-based AOP framework and its close integration with the Spring bean factory. AspectJ itself has type-based semantics and at an execution join point both 'this' and 'target' refer to the same object . neither for JDK proxies (where this isn't applicable) nor for CGLIB proxies (where this is technically possible but not recommendable for AOP purposes). It is a Spring-specific extension to the standard PCDs that AspectJ defines. consider the use of Spring-driven native AspectJ weaving instead of Spring's proxy-based AOP framework. where it is natural and 3. Note Please note that the 'bean' PCD is only supported in Spring AOP . Spring AOP is a proxy-based system and differentiates between the proxy object itself (bound to 'this') and the target object behind the proxy (bound to 'target'). the 'bean' PCD can be &&'ed. and ! (negated) too. ||'ed. protected methods are by definition not intercepted. so if you establish some naming conventions for your Spring beans you can quite easily write a 'bean' PCD expression to pick them out.limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP) • @annotation . any given pointcut will be matched against public methods only! If your interception needs include protected/private methods or even constructors.and not in native AspectJ weaving.1 Reference Documentation 205 . As a consequence. Note Due to the proxy-based nature of Spring's AOP framework. In addition. As is the case with other pointcut designators.

someapp.xyz.lang.someapp. */ @Pointcut("within(com.. protected pointcuts in the hierarchy. */ @Pointcut("within(com.Pointcut.someapp.*)") public void inWebLayer() {} /** * A join point is in the service layer if the method is defined * in a type in the com. The following example shows three pointcut expressions: anyPublicOperation (which matches if a method execution join point represents the execution of any public method).someapp. @Pointcut("execution(public * *(.service.xyz.xyz.Spring Framework straightforward to identify specific beans by name. import org. '||' and '!'.annotation.xyz. normal Java visibility rules apply (you can see private pointcuts in the same type.lang. import org. Sharing common pointcut definitions When working with enterprise applications..web..someapp. @Aspect public class SystemArchitecture { /** * A join point is in the web layer if the method is defined * in a type in the com. When referring to pointcuts by name. It is also possible to refer to pointcut expressions by name. inTrading (which matches if a method execution is in the trading module).web package or any sub-package * under that. Visibility does not affect pointcut matching.xyz.*)") 3. and tradingOperation (which matches if a method execution represents any public method in the trading module). We recommend defining a "SystemArchitecture" aspect that captures common pointcut expressions for this purpose.aspectj..trading.))") private void anyPublicOperation() {} @Pointcut("within(com.annotation. Combining pointcut expressions Pointcut expressions can be combined using '&&'.*)") private void inTrading() {} @Pointcut("anyPublicOperation() && inTrading()") private void tradingOperation() {} It is a best practice to build more complex pointcut expressions out of smaller named components as shown above.someapp. public pointcuts anywhere and so on).aspectj. A typical such aspect would look as follows: package com.service package or any sub-package * under that.Aspect. you often want to refer to modules of the application and particular sets of operations from within several aspects.xyz.1 Reference Documentation 206 .

* * If you group service interfaces by functional area (for example.*)") public void inDataAccessLayer() {} /** * A business service is the execution of any method defined on a service * interface.xyz.*(.) */ @Pointcut("execution(* com.SystemArchitecture. */ @Pointcut("within(com.))") public void businessService() {} /** * A data access operation is the execution of any method defined on a * dao interface.*.dao.dao. This definition assumes that interfaces are placed in the * "service" package.Spring Framework public void inServiceLayer() {} /** * A join point is in the data access layer if the method is defined * in a type in the com. * in packages com.dao package or any sub-package * under that.3.*.someapp. (This assumes that you have * named your Spring service beans in a consistent fashion. like so "bean(*Service)". Examples Spring AOP users are likely to use the execution pointcut designator the most often. you can write the expression using the 'bean' * PCD. * * Alternatively.*(.. The format of an execution expression is: execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) 3.xyz.someapp.xyz. and that implementation types are in sub-packages.someapp.xyz..*(.))") public void dataAccessOperation() {} } The pointcuts defined in such an aspect can be referred to anywhere that you need a pointcut expression. For example.def.someapp.xyz.xyz.xyz. you could write: <aop:config> <aop:advisor pointcut="com.service. and that implementation types are in sub-packages. Transaction Management.service.1 Reference Documentation 207 .*.service and com.abc.... */ @Pointcut("execution(* com. to make the service layer transactional.someapp. The transaction elements are discussed in Chapter 11. “Schema-based AOP support”.))" * could be used instead.someapp.service) then * the pointcut expression "execution(* com.businessService()" advice-ref="tx-advice"/> </aop:config> <tx:advice id="tx-advice"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> The <aop:config> and <aop:advisor> elements are discussed in Section 8. This definition assumes that interfaces are placed in the * "dao" package.someapp.xyz.

. The name pattern matches the method name.service.)) • any join point (method execution only in Spring AOP) within the service package: within(com.) matches any number of parameters (zero or more). the first can be of any type. name pattern.service..AccountService) 3.)) • the execution of any method defined in the service package: execution(* com. Consult the Language Semantics section of the AspectJ Programming Guide for more information. The returning type pattern determines what the return type of the method must be in order for a join point to be matched.service. The parameters pattern is slightly more complex: () matches a method that takes no parameters. (*.service. Most frequently you will use * as the returning type pattern. whereas (.. Some examples of common pointcut expressions are given below.xyz. You can use the * wildcard as all or part of a name pattern.*) • any join point (method execution only in Spring AOP) where the proxy implements the AccountService interface: this(com.xyz.service.xyz.)) • the execution of any method defined by the AccountService interface: execution(* com.. the second must be a String..service.*.Spring Framework throws-pattern?) All parts except the returning type pattern (ret-type-pattern in the snippet above).1 Reference Documentation 208 ..)) • the execution of any method defined in the service package or a sub-package: execution(* com.. and parameters pattern are optional.xyz..String) matches a method taking two parameters.xyz.xyz.*(.*(. A fully-qualified type name will match only when the method returns the given type. The pattern (*) matches a method taking one parameter of any type. • the execution of any public method: execution(public * *(.)) • the execution of any method with a name beginning with "set": execution(* set*(.AccountService.*) • any join point (method execution only in Spring AOP) within the service package or a sub-package: within(com.*(.*. which matches any return type.

xyz.see the following section on advice for how to make the method arguments available in the advice body. the execution version matches if the method signature declares a single parameter of type Serializable.see the following section on advice for how to make the target object available in the advice body. Note that the pointcut given in this example is different to execution(* *(java.io.transaction.annotation.Serializable)): the args version matches if the argument passed at runtime is Serializable.transaction.Spring Framework 'this' is more commonly used in a binding form :.see the following section on advice for how to make the annotation object available in the advice body. • any join point (method execution only in Spring AOP) where the executing method has an @Transactional annotation: @annotation(org. • any join point (method execution only in Spring AOP) which takes a single parameter. • any join point (method execution only in Spring AOP) where the target object has an @Transactional annotation: @target(org.see the following section on advice for how to make the annotation object available in the advice body.see the following section on advice for how to make the proxy object available in the advice body.Transactional) '@within' can also be used in a binding form :.springframework. and where the argument passed at runtime is Serializable: args(java.Transactional) '@target' can also be used in a binding form :. • any join point (method execution only in Spring AOP) where the target object implements the AccountService interface: target(com.1 Reference Documentation 209 .service.see the following section on advice for how to make the annotation object available in the advice body.annotation.Transactional) '@annotation' can also be used in a binding form :.io.annotation. 3. • any join point (method execution only in Spring AOP) where the declared type of the target object has an @Transactional annotation: @within(org.springframework.springframework.transaction.Serializable) 'args' is more commonly used in a binding form :.AccountService) 'target' is more commonly used in a binding form :.

security. call. whilst the contextual designators may be included if wishing to match based on join point context. For example: within. This means you do not have to worry about understanding the performance of various pointcut designators and may supply them in any order in a pointcut declaration. set. target. For example: execution. What does this mean? Basically pointcuts are rewritten in DNF (Disjunctive Normal Form) and the components of the pointcut are sorted such that those components that are cheaper to evaluate are checked first. withincode • Contextual designators are those that match (and optionally bind) based on context. handler • Scoping designators are those which select a group of join points of interest (of probably many kinds). For example: this.Classified) '@args' can also be used in a binding form :. AspectJ processes pointcuts in order to try and optimize matching performance. (A dynamic match means the match cannot be fully determined from static analysis and a test will be placed in the code to determine if there is an actual match when the code is running). On first encountering a pointcut declaration. • any join point (method execution only in Spring AOP) on a Spring bean named 'tradeService': bean(tradeService) • any join point (method execution only in Spring AOP) on Spring beans having names that match the wildcard expression '*Service': bean(*Service) Writing good pointcuts During compilation. AspectJ will rewrite it into an optimal form for the matching process. However. AspectJ can only work with what it is told. and for optimal performance of matching you should think about what they are trying to achieve and narrow the search space for matches as much as possible in the definition. Supplying either just a kinded designator or just a contextual designator will 3.see the following section on advice for how to make the annotation object(s) available in the advice body. The existing designators naturally fall into one of three groups: kinded.Spring Framework • any join point (method execution only in Spring AOP) which takes a single parameter. and where the runtime type of the argument passed has the @Classified annotation: @args(com. get. or bind that context for use in the advice. scoping and context: • Kinded designators are those which select a particular kind of join point. Examining code and determining if each join point matches (statically or dynamically) a given pointcut is a costly process.xyz.1 Reference Documentation 210 . @annotation A well written pointcut should try and include at least the first two types (kinded and scoping).

SystemArchitecture.aspectj.xyz. Before advice Before advice is declared in an aspect using the @Before annotation: import org. Scoping designators are very fast to match and their usage means AspectJ can very quickly dismiss groups of join points that should not be further processed . or a pointcut expression declared in place..Aspect.AfterReturning.*. @Aspect public class AfterReturningExample { 3..annotation. Declaring advice Advice is associated with a pointcut expression.annotation.lang.that is why a good pointcut should always include one if possible.annotation.lang.dataAccessOperation()") public void doAccessCheck() { // . It is declared using the @AfterReturning annotation: import org.annotation.aspectj.Before.xyz.lang..annotation.myapp. import org.Spring Framework work but could affect weaving performance (time and memory used) due to all the extra processing and analysis.annotation.Before.1 Reference Documentation 211 . and runs before. import org. } } If using an in-place pointcut expression we could rewrite the above example as: import org. or around method executions matched by the pointcut.*(.aspectj.Aspect.lang. import org.Aspect.lang.aspectj.dao.myapp. @Aspect public class BeforeExample { @Before("com.. } } After returning advice After returning advice runs when a matched method execution returns normally.))") public void doAccessCheck() { // .aspectj. after.aspectj.lang.. @Aspect public class BeforeExample { @Before("execution(* com. The pointcut expression may be either a simple reference to a named pointcut.

and you also often need access to the thrown exception in the advice body. import org. all inside the same aspect. After throwing advice After throwing advice runs when a matched method execution exits by throwing an exception. Please note that it is not possible to return a totally different reference when using after-returning advice. import org. returning="retVal") public void doAccessCheck(Object retVal) { // . It is declared using the @AfterThrowing annotation: import org.lang.annotation. When a method execution returns. and other members as well.aspectj. } } Note: it is of course possible to have multiple advice declarations.annotation. @Aspect public class AfterReturningExample { @AfterReturning( pointcut="com. A returning clause also restricts matching to only those method executions that return a value of the specified type (Object in this case.myapp.lang.myapp.xyz.SystemArchitecture.1 Reference Documentation 212 . We're just showing a single advice declaration in these examples to focus on the issue under discussion at the time.AfterThrowing.xyz.annotation..dataAccessOperation()". } } Often you want the advice to run only when exceptions of a given type are thrown.lang. Sometimes you need access in the advice body to the actual value that was returned. Use the throwing attribute to both restrict 3.SystemArchitecture.Aspect.dataAccessOperation()") public void doAccessCheck() { // .myapp.Spring Framework @AfterReturning("com. } } The name used in the returning attribute must correspond to the name of a parameter in the advice method.xyz.aspectj.AfterReturning..lang..Aspect. the return value will be passed to the advice method as the corresponding argument value.SystemArchitecture. You can use the form of @AfterReturning that binds the return value for this: import org.dataAccessOperation()") public void doRecoveryActions() { // .aspectj..annotation.aspectj. which will match any return value).. @Aspect public class AfterThrowingExample { @AfterThrowing("com..

After. calling proceed() on the 3. It is declared using the @After annotation.aspectj. When a method execution exits by throwing an exception.Spring Framework matching (if desired.SystemArchitecture.annotation. import org.AfterThrowing. the exception will be passed to the advice method as the corresponding argument value. After (finally) advice After (finally) advice runs however a matched method execution exits.lang.e.myapp. Around advice is often used if you need to share state before and after a method execution in a thread-safe manner (starting and stopping a timer for example).lang.1 Reference Documentation 213 .dataAccessOperation()") public void doReleaseLock() { // . Around advice is declared using the @Around annotation.xyz.myapp. don't use around advice if simple before advice would do).Aspect. After advice must be prepared to handle both normal and exception return conditions..aspectj. how. Within the body of the advice.lang.annotation. import org.aspectj.SystemArchitecture. } } The name used in the throwing attribute must correspond to the name of a parameter in the advice method. throwing="ex") public void doRecoveryActions(DataAccessException ex) { // ..lang.aspectj.annotation. use Throwable as the exception type otherwise) and bind the thrown exception to an advice parameter. A throwing clause also restricts matching to only those method executions that throw an exception of the specified type (DataAccessException in this case). @Aspect public class AfterThrowingExample { @AfterThrowing( pointcut="com. @Aspect public class AfterFinallyExample { @After("com.. import org. and even if.Aspect. and to determine when. The first parameter of the advice method must be of type ProceedingJoinPoint. Around advice runs "around" a matched method execution.xyz. Always use the least powerful form of advice that meets your requirements (i.. It has the opportunity to do work both before and after the method executes.annotation.dataAccessOperation()". the method actually gets to execute at all. It is typically used for releasing resources. etc. import org. } } Around advice The final kind of advice is around advice.

Around.the values in the array will be used as the arguments to the method execution when it proceeds.ProceedingJoinPoint.aspectj. and the value passed to proceed in a given argument position supplants the original value at the join point for the entity the value was bound to (Don't worry if this doesn't make sense right now!). import org.xyz. Advice parameters Spring 2. A simple caching aspect for example could return a value from a cache if it has one.aspectj.lang. We'll see how to make argument and other contextual values available to the advice body in a moment. or not at all within the body of the around advice.aspectj.lang. } } The value returned by the around advice will be the return value seen by the caller of the method.businessService()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // start stopwatch Object retVal = pjp. There is a way to write such aspects that is 100% compatible across both Spring AOP and AspectJ. import org. // stop stopwatch return retVal. You only need to be aware of this difference if you are compiling @AspectJ aspects written for Spring and using proceed with arguments with the AspectJ compiler and weaver. and invoke proceed() if it does not. The proceed method may also be called passing in an Object[] .aspectj. which is a subclass of JoinPoint.meaning that you declare the parameters you need in the advice signature (as we saw for the returning and throwing examples above) rather than work with Object[] arrays all the time. For around advice written using the traditional AspectJ language. all of these are quite legal. Access to the current JoinPoint Any advice method may declare as its first parameter. The JoinPoint interface provides a number of useful methods such as getArgs() (returns the method arguments). execution only semantics. and this is discussed in the following section on advice parameters.myapp. a parameter of type org.SystemArchitecture.proceed(). The behavior of proceed when called with an Object[] is a little different than the behavior of proceed for around advice compiled by the AspectJ compiler.annotation. First let's take a look at how to write generic advice that can find out about the method the advice is currently advising.annotation.Aspect.1 Reference Documentation 214 . import org. many times. 3.lang. the number of arguments passed to proceed must match the number of arguments passed to the around advice (not the number of arguments taken by the underlying join point). The approach taken by Spring is simpler and a better match to its proxy-based.JoinPoint (please note that around advice is required to declare a first parameter of type ProceedingJoinPoint.Spring Framework ProceedingJoinPoint causes the underlying method to execute. Note that proceed may be invoked once.lang.0 offers fully typed advice . @Aspect public class AroundExample { @Around("com.

Another way of writing this is to declare a pointcut that "provides" the Account object value when it matches a join point.dataAccessOperation() &&" + "args(account.)") public void validateAccount(Account account) { // .1 Reference Documentation 215 . } 3. and then just refer to the named pointcut from the advice.. and the argument passed to that parameter is an instance of Account. it restricts matching to only those method executions where the method takes at least one parameter.xyz. The following example shows how you could match the execution of methods annotated with an @Auditable annotation. @args) can all be bound in a similar fashion. An example should make this clearer.. First the definition of the @Auditable annotation: @Retention(RetentionPolicy.. If a parameter name is used in place of a type name in an args expression. Passing parameters to advice We've already seen how to bind the returned value or exception value (using after returning and after throwing advice). you can use the binding form of args.SystemArchitecture.dataAccessOperation() &&" + "args(account.Spring Framework getThis() (returns the proxy object).myapp. This would look as follows: @Pointcut("com.SystemArchitecture. Suppose you want to advise the execution of dao operations that take an Account object as the first parameter. @target. The proxy object (this). } The interested reader is once more referred to the AspectJ programming guide for more details.myapp.. and you need access to the account in the advice body. secondly. You could write the following: @Before("com... target object (target). getSignature() (returns a description of the method that is being advised) and toString() (prints a useful description of the method being advised).RUNTIME) @Target(ElementType. and extract the audit code. } The args(account. To make argument values available to the advice body..) part of the pointcut expression serves two purposes: firstly. @annotation. it makes the actual Account object available to the advice via the account parameter. then the value of the corresponding argument will be passed as the parameter value when the advice is invoked.. getTarget() (returns the target object). and annotations (@within. Please do consult the Javadocs for full details...METHOD) public @interface Auditable { AuditCode value().xyz.)") private void accountDataAccessOperation(Account account) {} @Before("accountDataAccessOperation(account)") public void validateAccount(Account account) { // .

Parameter names are not available through Java reflection. To achieve something similar to this you have to type the parameter to Collection<?> and manually check the type of the elements. So you cannot define a pointcut like this: @Before("execution(* . For example: @Before( value="com.sampleGenericMethod(*)) && args(param)") public void beforeSampleMethod(MyType param) { // Advice implementation } That this works is pretty obvious as we already discussed above. 3.. void sampleGenericCollectionMethod(Collection>T> param). } You can restrict interception of method types to certain parameter types by simply typing the advice parameter to the parameter type you want to intercept the method for: @Before("execution(* .. // .lib..these argument names are available at runtime. so Spring AOP uses the following strategies to determine parameter names: 1. then the specified parameter names are used: both the advice and the pointcut annotations have an optional "argNames" attribute which can be used to specify the argument names of the annotated method .xyz.1 Reference Documentation 216 . However.sampleGenericCollectionMethod(*)) && args(param)") public void beforeSampleMethod(Collection<MyType> param) { // Advice implementation } To make this work we would have to inspect every element of the collection.xyz..lib.anyPublicMethod() && " + "@annotation(auditable)") public void audit(Auditable auditable) { AuditCode code = auditable.Spring Framework And then the advice that matches the execution of @Auditable methods: @Before("com.Pointcuts.Sample+. Suppose you have a generic type like this: public interface Sample<T> { void sampleGenericMethod(T param).Pointcuts. Determining argument names The parameter binding in advice invocations relies on matching names used in pointcut expressions to declared parameter names in (advice and pointcut) method signatures.Sample+. which is not reasonable as we also cannot decide how to treat null values in general. If the parameter names have been specified by the user explicitly. it's worth pointing out that this won't work for generic collections.value().anyPublicMethod() && target(bean) && @annotation(auditable)". } Advice parameters and generics Spring AOP can handle generics used in class declarations and method parameters.

// .auditable") public void audit(Object bean. 3..1 Reference Documentation 217 .. For example. you should encounter no difficulties building with this flag on. then Spring AOP will look at the debug information for the class and try to determine the parameter names from the local variable table. ProceedingJoinPoint.value()..StaticPart type. so if the 'argNames' attribute has not been specified. // . If the code has been compiled without the necessary debug information.anyPublicMethod()") public void audit(JoinPoint jp) { // ..xyz. you may leave out the name of the parameter from the value of the "argNames" attribute. Object bean. This information will be present as long as the classes have been compiled with debug information ('-g:vars' at a minimum). Using the 'argNames' attribute is a little clumsy. bean.Spring Framework argNames="bean. then Spring AOP will attempt to deduce the pairing of binding variables to parameters (for example. the following advice need not declare the "argNames" attribute: @Before( "com. Auditable auditable) { AuditCode code = auditable. the "argNames" attribute need not include it: @Before( value="com. If the binding of variables is ambiguous given the available information. (2) the class file sizes will be very slightly bigger (typically inconsequential). you may simply omit the "argNames" attribute. 4.Pointcuts.lib. or JoinPoint. and JoinPoint. (3) the optimization to remove unused local variables will not be applied by your compiler. Auditable auditable) { AuditCode code = auditable. In other words. argNames="bean. If all of the above strategies fail then an IllegalArgumentException will be thrown.auditable") public void audit(JoinPoint jp..lib. and jp } The special treatment given to the first parameter of the JoinPoint. If an @AspectJ aspect has been compiled by the AspectJ compiler (ajc) even without the debug information then there is no need to add the argNames attribute as the compiler will retain the needed information. 3. use jp } 2. ProceedingJoinPoint. and the advice method only takes one parameter. the pairing is obvious!). if you modify the preceding advice to receive the join point object. In such situations. then an AmbiguousBindingException will be thrown.anyPublicMethod() && target(bean) && @annotation(auditable)". For example. use code and bean } If the first parameter is of the JoinPoint.xyz. use code. The consequences of compiling with this flag on are: (1) your code will be slightly easier to understand (reverse engineer).Pointcuts..value(). if only one variable is bound in the pointcut expression.StaticPart types is particularly convenient for advice that do not collect any other join point context.

springframework.which can be ordered at the aspect level.inDataAccessLayer() && " + "args(accountHolderNamePattern)") public Object preProcessQueryPattern(ProceedingJoinPoint pjp. the one with the highest precedence will run second). and an implementation of that interface DefaultUsageTracked. the one with highest precedence runs first). Advice ordering What happens when multiple pieces of advice all want to run at the same join point? Spring AOP follows the same precedence rules as AspectJ to determine the order of advice execution. For example.core. } In many cases you will be doing this binding anyway (as in the example above). An introduction is made using the @DeclareParents annotation. the highest precedence advice runs last (so given two pieces of after advice. This annotation is used to declare that matching types have a new parent (hence the name). unless you specify otherwise the order of execution is undefined. The highest precedence advice runs first "on the way in" (so given two pieces of before advice.xyz. The solution is simply to ensure that the advice signature binds each of the method parameters in order. the aspect returning the lower value from Ordered. String accountHolderNamePattern) throws Throwable { String newPattern = preProcess(accountHolderNamePattern).1 Reference Documentation 218 . This is done in the normal Spring way by either implementing the org.SystemArchitecture.myapp. Consider collapsing such advice methods into one advice method per join point in each aspect class. When two pieces of advice defined in the same aspect both need to run at the same join point. and to provide an implementation of that interface on behalf of those objects. For example: @Around("execution(List<Account> find*(.. the following 3.Spring Framework Proceeding with arguments We remarked earlier that we would describe how to write a proceed call with arguments that works consistently across Spring AOP and AspectJ.getValue() (or the annotation value) has the higher precedence. "On the way out" from a join point. given an interface UsageTracked.)) &&" + "com. the ordering is undefined (since there is no way to retrieve the declaration order via reflection for javac-compiled classes). Introductions Introductions (known as inter-type declarations in AspectJ) enable an aspect to declare that advised objects implement a given interface. return pjp. Given two aspects.proceed(new Object[] {newPattern}). or refactor the pieces of advice into separate aspect classes . When two pieces of advice defined in different aspects both need to run at the same join point.Ordered interface in the aspect class or annotating it with the Order annotation. You can control the order of execution by specifying precedence.

Spring Framework aspect declares that all implementors of service interfaces also implement the UsageTracked interface.businessService()) public void recordServiceUsage() { // . @Before(com. } } The effect of the 'perthis' clause is that one aspect instance will be created for each unique service object executing a business service (each unique object bound to 'this' at join points matched by the pointcut expression). defaultImpl=DefaultUsageTracked.any bean of a matching type will implement the UsageTracked interface. Before the aspect instance 3.SystemArchitecture.class) public static UsageTracked mixin. so if you are just starting out with AOP you can safely skip it until later. A "perthis" aspect is declared by specifying a perthis clause in the @Aspect annotation. } } The interface to be implemented is determined by the type of the annotated field.Spring supports AspectJ's perthis and pertarget instantiation models (percflow.) @Aspect public class UsageTracking { @DeclareParents(value="com.*+".myapp.businessService())") public class MyAspect { private int someState.businessService() &&" + "this(usageTracked)") public void recordUsage(UsageTracked usageTracked) { usageTracked.getBean("myService"). It is possible to define aspects with alternate lifecycles :. Let's look at an example. @Aspect("perthis(com. (In order to expose statistics via JMX for example.xyz.. service beans can be directly used as implementations of the UsageTracked interface.xyz.SystemArchitecture. The aspect instance is created the first time that a method is invoked on the service object. Note that in the before advice of the above example. @Before("com.myapp.SystemArchitecture.service. AspectJ calls this the singleton instantiation model. and then we'll explain how it works. If accessing a bean programmatically you would write the following: UsageTracked usageTracked = (UsageTracked) context.incrementUseCount().) By default there will be a single instance of each aspect within the application context. and pertypewithin are not currently supported).myapp.. The value attribute of the @DeclareParents annotation is an AspectJ type pattern :. percflowbelow.1 Reference Documentation 219 .xyz. Aspect instantiation models (This is an advanced topic.xzy.myapp. The aspect goes out of scope when the service object goes out of scope.

let's put them together to do something useful! The execution of business services can sometimes fail due to concurrency issues (for example. If the operation is retried. it is quite likely to succeed next time round. } catch(PessimisticLockingFailureException ex) { lockFailureException = ex. we'd like to transparently retry the operation to avoid the client seeing a PessimisticLockingFailureException.SystemArchitecture. deadlock loser). } public int getOrder() { return this. throw lockFailureException.order. do { numAttempts++.xyz. Because we want to retry the operation. we will need to use around advice so that we can call proceed multiple times. Here's how the basic aspect implementation looks: @Aspect public class ConcurrentOperationExecutor implements Ordered { private static final int DEFAULT_MAX_RETRIES = 2. } @Around("com. public void setMaxRetries(int maxRetries) { this. private int maxRetries = DEFAULT_MAX_RETRIES. but only when the service object is the one this aspect is associated with.businessService()") public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable { int numAttempts = 0. } 3.myapp.maxRetries).1 Reference Documentation 220 . As soon as the aspect instance has been created.order = order. See the AspectJ programming guide for more information on per-clauses. } public void setOrder(int order) { this. but creates one aspect instance for each unique target object at matched join points. private int order = 1. the advice declared within it will execute at matched join points. Example Now that you have seen how all the constituent parts work.proceed(). The 'pertarget' instantiation model works in exactly the same way as perthis.maxRetries = maxRetries.Spring Framework is created. } } while(numAttempts <= this. PessimisticLockingFailureException lockFailureException. try { return pjp. This is a requirement that clearly cuts across multiple services in the service layer. For business services where it is appropriate to retry in such conditions (idempotent operations that don't need to go back to the user for conflict resolution). and hence is ideal for implementing via an aspect. none of the advice within it executes.

myapp.1 Reference Documentation 221 .SystemArchitecture. Notice that for the moment we're applying the retry logic to all businessService()s.xyz.2.Spring Framework } Note that the aspect implements the Ordered interface so we can set the precedence of the aspect higher than the transaction advice (we want a fresh transaction each time we retry). The change to the aspect to only retry idempotent operations simply involves refining the pointcut expression so that only @Idempotent operations match: @Around("com.myapp. or simply prefer an XML-based format. you need to import the spring-aop schema as described in Appendix C.xyz. See the section called “The aop schema” for how to import the tags in the aop namespace. To use the aop namespace tags described in this section. 3.. XML Schema-based configuration. then Spring 2.xyz. hence in this section we will focus on the new syntax and refer the reader to the discussion in the previous section (Section 8. We try to proceed. The corresponding Spring configuration is: <aop:aspectj-autoproxy/> <bean id="concurrentOperationExecutor" class="com.RUNTIME) public @interface Idempotent { // marker annotation } and use the annotation to annotate the implementation of service operations.0 also offers support for defining aspects using the new "aop" namespace tags..3 Schema-based AOP support If you are unable to use Java 5. and if we fail with an PessimisticLockingFailureException we simply try again unless we have exhausted all of our retry attempts.service.ConcurrentOperationExecutor"> <property name="maxRetries" value="3"/> <property name="order" value="100"/> </bean> To refine the aspect so that it only retries idempotent operations. we might define an Idempotent annotation: @Retention(RetentionPolicy.businessService() && " + "@annotation(com.Idempotent)") public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable { . “@AspectJ support”) for an understanding of writing pointcut expressions and the binding of advice parameters. } 8. The main action happens in the doConcurrentOperation around advice. The exact same pointcut expressions and advice kinds are supported as when using the @AspectJ style. The maxRetries and order properties will both be configured by Spring.myapp.impl.service.

Warning The <aop:config> style of configuration makes heavy use of Spring's auto-proxying mechanism."> .*. The state and behavior is captured in the fields and methods of the object.. and the backing bean is referenced using the ref attribute: <aop:config> <aop:aspect id="myAspect" ref="aBean"> . or just the AutoProxyCreator style.myapp.. an aspect is simply a regular Java object defined as a bean in your Spring application context. and aspect elements (note these must be declared in that order).1 Reference Documentation 222 . and the pointcut and advice information is captured in the XML. </bean> The bean backing the aspect ("aBean" in this case) can of course be configured and dependency injected just like any other Spring bean.. An <aop:config> element can contain pointcut. enabling the pointcut definition to be shared across several aspects and advisors. A pointcut representing the execution of any business service in the service layer could be defined as follows: <aop:config> <aop:pointcut id="businessService" expression="execution(* com.. An aspect is declared using the <aop:aspect> element. </aop:aspect> </aop:config> <bean id="aBean" class="..xyz.. This can cause issues (such as advice not being woven) if you are already using explicit auto-proxying via the use of BeanNameAutoProxyCreator or suchlike. all aspect and advisor elements must be placed within an <aop:config> element (you can have more than one <aop:config> element in an application context configuration). Declaring a pointcut A named pointcut can be declared inside an <aop:config> element.service. The recommended usage pattern is to use either just the <aop:config> style.))"/> </aop:config> 3.*(. Declaring an aspect Using the schema support. advisor.Spring Framework Within your Spring configurations..

this(service)"/> <aop:before pointcut-ref="businessService" method="monitor"/> ..*(.. } When combining pointcut sub-expressions.&amp.2. Declaring a pointcut inside an aspect is very similar to declaring a top-level pointcut: <aop:config> <aop:aspect id="myAspect" ref="aBean"> <aop:pointcut id="businessService" expression="execution(* com. If you are using the schema based declaration style with Java 5..myapp.. </aop:aspect> </aop:config> Much the same way in an @AspectJ aspect.. '&&' is awkward within an XML document.*(. </aop:aspect> </aop:config> The advice must be declared to receive the collected join point context by including parameters of the matching names: public void monitor(Object service) { .1 Reference Documentation 223 . another way of defining the above pointcut would be: <aop:config> <aop:pointcut id="businessService" expression="com. you can refer to named pointcuts defined in types (@Aspects) within the pointcut expression.myapp.)) &amp.*.. For example.SystemArchitecture.service. the following pointcut collects the 'this' object as the join point context and passes it to advice: <aop:config> <aop:aspect id="myAspect" ref="aBean"> <aop:pointcut id="businessService" expression="execution(* com.xyz.. but this feature is not available on JDK 1.xyz.businessService()"/> </aop:config> Assuming you have a SystemArchitecture aspect as described in the section called “Sharing common pointcut definitions”.xyz.myapp.service. “@AspectJ support”. and so the 3.5 therefore. On JDK 1.4 and below (it relies on the Java 5 specific AspectJ reflection APIs).))"/> ..*.Spring Framework Note that the pointcut expression itself is using the same AspectJ pointcut expression language as described in Section 8. pointcuts declared using the schema based definition style may collect join point context.

For example. Before advice Before advice runs before a matched method execution. The named pointcut support in the schema based definition style is thus more limited than that offered by the @AspectJ style. and they have exactly the same semantics. the previous pointcut may be better written as: <aop:config> <aop:aspect id="myAspect" ref="aBean"> <aop:pointcut id="businessService" expression="execution(* com. 'or' and 'not' can be used in place of '&&'.)) and this(service)"/> <aop:before pointcut-ref="businessService" method="monitor"/> .. </aop:aspect> As we noted in the discussion of the @AspectJ style.*. Declaring advice The same five advice kinds are supported as for the @AspectJ style..service...*. using named pointcuts can significantly improve the 3. '||' and '!' respectively. <aop:aspect id="beforeExample" ref="aBean"> <aop:before pointcut-ref="dataAccessOperation" method="doAccessCheck"/> . </aop:aspect> </aop:config> Note that pointcuts defined in this way are referred to by their XML id and cannot be used as named pointcuts to form composite pointcuts.))" method="doAccessCheck"/> . It is declared inside an <aop:aspect> using the <aop:before> element. replace the pointcut-ref attribute with a pointcut attribute: <aop:aspect id="beforeExample" ref="aBean"> <aop:before pointcut="execution(* com.. </aop:aspect> Here dataAccessOperation is the id of a pointcut defined at the top (<aop:config>) level.Spring Framework keywords 'and'.dao.myapp.*(..xyz. To define the pointcut inline instead.xyz.1 Reference Documentation 224 ..*(..myapp.

. it is possible to get hold of the return value within the advice body. the method signature may be declared as: public void doAccessCheck(Object retVal) {. </aop:aspect> The doAccessCheck method must declare a parameter named retVal. For example: <aop:aspect id="afterReturningExample" ref="aBean"> <aop:after-returning pointcut-ref="dataAccessOperation" method="doAccessCheck"/> ... the "doAccessCheck" method on the aspect bean will be invoked.Spring Framework readability of your code. For example. After returning advice After returning advice runs when a matched method execution completes normally. </aop:aspect> Just as in the @AspectJ style... The method attribute identifies a method (doAccessCheck) that provides the body of the advice.. After throwing advice After throwing advice executes when a matched method execution exits by throwing an exception.1 Reference Documentation 225 . 3. This method must be defined for the bean referenced by the aspect element containing the advice. The type of this parameter constrains matching in the same way as described for @AfterReturning. Before a data access operation is executed (a method execution join point matched by the pointcut expression). It is declared inside an <aop:aspect> in the same way as before advice. Use the returning attribute to specify the name of the parameter to which the return value should be passed: <aop:aspect id="afterReturningExample" ref="aBean"> <aop:after-returning pointcut-ref="dataAccessOperation" returning="retVal" method="doAccessCheck"/> . It is declared inside an <aop:aspect> using the after-throwing element: <aop:aspect id="afterThrowingExample" ref="aBean"> <aop:after-throwing pointcut-ref="dataAccessOperation" method="doRecoveryActions"/> ...

it is possible to get hold of the thrown exception within the advice body.1 Reference Documentation 226 . The proceed method may also be calling passing in an Object[] . After (finally) advice After (finally) advice runs however a matched method execution exits. It has the opportunity to do work both before and after the method executes. The first parameter of the advice method must be of type ProceedingJoinPoint. how.the values in the array will be used as the arguments to the method execution when it proceeds. Around advice is declared using the aop:around element. Around advice runs "around" a matched method execution. don't use around advice if simple before advice would do.Spring Framework </aop:aspect> Just as in the @AspectJ style. and to determine when... and even if. </aop:aspect> The doRecoveryActions method must declare a parameter named dataAccessEx. the method signature may be declared as: public void doRecoveryActions(DataAccessException dataAccessEx) {. the method actually gets to execute at all.. The type of this parameter constrains matching in the same way as described for @AfterThrowing.. It is declared using the after element: <aop:aspect id="afterFinallyExample" ref="aBean"> <aop:after pointcut-ref="dataAccessOperation" method="doReleaseLock"/> . See the section called “Around advice” for notes on calling proceed with an 3. Within the body of the advice.. Always use the least powerful form of advice that meets your requirements. Around advice is often used if you need to share state before and after a method execution in a thread-safe manner (starting and stopping a timer for example). </aop:aspect> Around advice The final kind of advice is around advice. calling proceed() on the ProceedingJoinPoint causes the underlying method to execute. For example. Use the throwing attribute to specify the name of the parameter to which the exception should be passed: <aop:aspect id="afterThrowingExample" ref="aBean"> <aop:after-throwing pointcut-ref="dataAccessOperation" throwing="dataAccessEx" method="doRecoveryActions"/> ..

</aop:aspect> The implementation of the doBasicProfiling advice would be exactly the same as in the @AspectJ example (minus the annotation of course): public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // start stopwatch Object retVal = pjp.xyz. which is treated in the same manner to the "argNames" attribute in an advice annotation as described in the section called “Determining argument names”.Spring Framework Object[].proceed().y. See the section called “Advice parameters” for details.Pointcuts.. public interface FooService { Foo getFoo(String fooName.service.anyPublicMethod() and @annotation(auditable)" method="audit" arg-names="auditable"/> The arg-names attribute accepts a comma-delimited list of parameter names. } Advice parameters The schema based declaration style supports fully typed advice in the same way as described for the @AspectJ support . For example: <aop:before pointcut="com. age).. <aop:aspect id="aroundExample" ref="aBean"> <aop:around pointcut-ref="businessService" method="doBasicProfiling"/> . } } 3. package x.1 Reference Documentation 227 . int age) { return new Foo(name.lib. If you wish to explicitly specify argument names for the advice methods (not relying on the detection strategies previously described) then this is done using the arg-names attribute of the advice element. int age). } public class DefaultFooService implements FooService { public Foo getFoo(String name.by matching pointcut parameters by name against advice method parameters. Find below a slightly more involved example of the XSD-based approach that illustrates some around advice used in conjunction with a number of strongly typed parameters. // stop stopwatch return retVal.

int age) throws Throwable { StopWatch clock = new StopWatch( "Profiling for '" + name + "' and '" + age + "'")..this is the actual advice itself --> <bean id="profiler" class="x..StopWatch. } finally { clock.DefaultFooService"/> <!-.org/2001/XMLSchema-instance" xmlns:aop="http://www.y.org/schema/aop/spring-aop-3.w3. String name.toShortString()).util.aspectj. import org.org/schema/beans" xmlns:xsi="http://www. import org.service.1 Reference Documentation 228 .org/schema/beans http://www.service. public final class Boot { 3.SimpleProfiler"/> <aop:config> <aop:aspect ref="profiler"> <aop:pointcut id="theExecutionOfSomeFooServiceMethod" expression="execution(* x.y.springframework.FooService.y. import x.prettyPrint()).proceed().org/schema/beans/spring-beans-3.org/schema/aop http://www.springframework.start(call. the first of which happens to be the join point used to proceed with the method call: the presence of this parameter is an indication that the profile(. } } } Finally.getFoo(String. import org.y.) method accepts a number of strongly-typed parameters.) is to be used as around advice: package x.context.xsd http://www. System.FooService.springframework.out.0.Spring Framework Next up is the aspect.0.y.service. here is the XML configuration that is required to effect the execution of the above advice for a particular join point: <beans xmlns="http://www.stop().ClassPathXmlApplicationContext. try { clock. Notice the fact that the profile(.org/schema/aop" xsi:schemaLocation=" http://www.springframework. return call.xsd"> <!-. public class SimpleProfiler { public Object profile(ProceedingJoinPoint call.springframework.BeanFactory.springframework.lang.springframework.springframework.factory.support.beans.int)) and args(name.ProceedingJoinPoint. age)"/> <aop:around pointcut-ref="theExecutionOfSomeFooServiceMethod" method="profile"/> </aop:aspect> </aop:config> </beans> If we had the following driver script.springframework.println(clock.this is the object that will be proxied by Spring's AOP infrastructure --> <bean id="fooService" class="x. we would get output something like this on standard output: import org.

service. For example.getFoo("Pengo". (In order to expose statistics via JMX for example.tracking.*+" implement-interface="com.SystemArchitecture.xyz. The precedence between aspects is determined by either adding the Order annotation to the bean backing the aspect or by having the bean implement the Ordered interface.UsageTracked" default-impl="com.service. } 3.getBean("fooService").DefaultUsageTracked"/> <aop:before pointcut="com.myapp. and to provide an implementation of that interface on behalf of those objects. Introductions Introductions (known as inter-type declarations in AspectJ) enable an aspect to declare that advised objects implement a given interface.incrementUseCount(). the following aspect declares that all implementors of service interfaces also implement the UsageTracked interface.myapp. FooService foo = (FooService) ctx.businessService() and this(usageTracked)" method="recordUsage"/> </aop:aspect> The class backing the usageTracking bean would contain the method: public void recordUsage(UsageTracked usageTracked) { usageTracked.xyz.tracking. foo.Spring Framework public static void main(final String[] args) throws Exception { BeanFactory ctx = new ClassPathXmlApplicationContext("x/y/plain.xyz.service.xzy.xml"). given an interface UsageTracked.) <aop:aspect id="usageTrackerAspect" ref="usageTracking"> <aop:declare-parents types-matching="com. } } StopWatch 'Profiling for 'Pengo' and '12'': running time (millis) = 0 ----------------------------------------ms % Task name ----------------------------------------00000 ? execution(getFoo) Advice ordering When multiple advice needs to execute at the same join point (executing method) the ordering rules are as described in the section called “Advice ordering”.myapp.myapp.1 Reference Documentation 229 . and an implementation of that interface DefaultUsageTracked. 12). An introduction is made using the aop:declare-parents element inside an aop:aspect This element is used to declare that matching types have a new parent (hence the name).

The advice itself is represented by a bean.myapp. Here's how it looks: <aop:config> <aop:pointcut id="businessService" expression="execution(* com. you can also use the pointcut attribute to define a pointcut expression inline. Advisors can take advantage of AspectJ pointcut expressions though. Aspect instantiation models The only supported instantiation model for schema-defined aspects is the singleton model. The value of the types-matching attribute is an AspectJ type pattern :. An advisor is like a small self-contained aspect that has a single piece of advice.))"/> <aop:advisor pointcut-ref="businessService" advice-ref="tx-advice"/> </aop:config> <tx:advice id="tx-advice"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> As well as the pointcut-ref attribute used in the above example..*(.*. and must implement one of the advice interfaces described in the section called “Advice types in Spring”. If accessing a bean programmatically you would write the following: UsageTracked usageTracked = (UsageTracked) context. use the order attribute to define the Ordered value of the advisor. Example 3.Spring Framework The interface to be implemented is determined by implement-interface attribute. Spring 2.any bean of a matching type will implement the UsageTracked interface.0 supports the advisor concept with the <aop:advisor> element.2 and does not have a direct equivalent in AspectJ. Advisors The concept of "advisors" is brought forward from the AOP support defined in Spring 1.xyz.1 Reference Documentation 230 .service. Other instantiation models may be supported in future releases.getBean("myService"). You will most commonly see it used in conjunction with transactional advice. To define the precedence of an advisor so that the advice can participate in ordering. Note that in the before advice of the above example. which also has its own namespace support in Spring 2. service beans can be directly used as implementations of the UsageTracked interface.0.

private int maxRetries = DEFAULT_MAX_RETRIES. The maxRetries and order properties will both be configured by Spring. PessimisticLockingFailureException lockFailureException. The main action happens in the doConcurrentOperation around advice method. we'll need to use around advice so that we can call proceed multiple times. } public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable { int numAttempts = 0. we'd like to transparently retry the operation to avoid the client seeing a PessimisticLockingFailureException. We try to proceed. try { return pjp. 3.order = order.maxRetries). and hence is ideal for implementing via an aspect. it is quite likely it will succeed next time round. } } while(numAttempts <= this. This is a requirement that clearly cuts across multiple services in the service layer. deadlock loser). } public void setOrder(int order) { this. The execution of business services can sometimes fail due to concurrency issues (for example. public void setMaxRetries(int maxRetries) { this.proceed(). do { numAttempts++. throw lockFailureException.1 Reference Documentation 231 . If the operation is retried. For business services where it is appropriate to retry in such conditions (idempotent operations that don't need to go back to the user for conflict resolution). } public int getOrder() { return this. } catch(PessimisticLockingFailureException ex) { lockFailureException = ex.Spring Framework Let's see how the concurrent locking failure retry example from the section called “Example” looks when rewritten using the schema support. Because we want to retry the operation.order. Here's how the basic aspect implementation looks (it's just a regular Java class using the schema support): public class ConcurrentOperationExecutor implements Ordered { private static final int DEFAULT_MAX_RETRIES = 2. and if we fail with a PessimisticLockingFailureException we simply try again unless we have exhausted all of our retry attempts.maxRetries = maxRetries. private int order = 1. } } Note that the aspect implements the Ordered interface so we can set the precedence of the aspect higher than the transaction advice (we want a fresh transaction each time we retry).

xyz. development tools. and between the Aspect language (code) style. by introducing an Idempotent annotation: @Retention(RetentionPolicy.myapp.myapp. and team familiarity with AOP.myapp. The change to the aspect to retry only idempotent operations simply involves refining the pointcut expression so that only @Idempotent operations match: <aop:pointcut id="idempotentOperation" expression="execution(* com.1 Reference Documentation 232 ..service.xyz.RUNTIME) public @interface Idempotent { // marker annotation } and using the annotation to annotate the implementation of service operations.4 Choosing which AOP declaration style to use Once you have decided that an aspect is the best approach for implementing a given requirement.ConcurrentOperationExecutor"> <property name="maxRetries" value="3"/> <property name="order" value="100"/> </bean> Notice that for the time being we assume that all business services are idempotent. but with the annotations removed.Spring Framework This class is identical to the one used in the @AspectJ example. how do you decide between using Spring AOP or AspectJ.impl.service. Spring AOP or full AspectJ? Use the simplest thing that can work.xyz.Idempotent)"/> 8.*(. Spring AOP is simpler than using full AspectJ as there is no requirement to introduce the AspectJ compiler / weaver into your development and build processes.xyz.*.myapp.))"/> <aop:around pointcut-ref="idempotentOperation" method="doConcurrentOperation"/> </aop:aspect> </aop:config> <bean id="concurrentOperationExecutor" class="com.service. or the Spring XML style? These decisions are influenced by a number of factors including application requirements.*. @AspectJ annotation style. If this is not the case we can refine the aspect so that it only retries genuinely idempotent operations.)) and @annotation(com.. The corresponding Spring configuration is: <aop:config> <aop:aspect id="concurrentOperationRetry" ref="concurrentOperationExecutor"> <aop:pointcut id="idempotentOperation" expression="execution(* com. If 3.service.*(.

in which this information is encapsulated. The XML style will be most familiar to existing Spring users. When using the @AspectJ style there is a single module . and the XML in the configuration file.)) public void operationReturningAnAccount() {} @Pointcut(propertyAccess() && operationReturningAnAccount()) public void accountPropertyAccess() {} In the XML style I can declare the first two pointcuts: 3. the XML style is slightly more limited in what it can express than the @AspectJ style: only the "singleton" aspect instantiation model is supported. The DRY principle says that there should be a single. then you will need to use AspectJ. then the AspectJ language syntax is the preferred option: it is cleaner and simpler because the language was purposefully designed for writing aspects. The XML style has two disadvantages. Clearly. for Java 5 projects there are various tradeoffs to consider. authoritative representation of any piece of knowledge within a system. Firstly it does not fully encapsulate the implementation of the requirement it addresses in a single place. the knowledge of how a requirement is implemented is split across the declaration of the backing bean class. When using AOP as a tool to configure enterprise services then XML can be a good choice (a good test is whether you consider the pointcut expression to be a part of your configuration you might want to change independently). then you have a choice of @AspectJ or XML style. and it is not possible to combine named pointcuts declared in XML. you have the choice of the AspectJ language syntax (also known as the "code style") or the @AspectJ annotation style.. then the XML style is the appropriate choice.xyz. If aspects play a large role in your design. and adding an aspect weaving phase to your build script.the aspect . or have only a few aspects that do not play a major role in your application. Secondly. and so on). When using the XML style. You will also need to use AspectJ if you wish to advise join points other than simple method executions (for example. field get or set join points.1 Reference Documentation 233 .. For example. With the XML style arguably it is clearer from your configuration what aspects are present in the system.Account+ *(. then Spring AOP is the right choice. in the @AspectJ style you can write something like: @Pointcut(execution(* get*())) public void propertyAccess() {} @Pointcut(execution(org. Clearly if you are not running on Java 5+. and you are able to use the AspectJ Development Tools (AJDT) plugin for Eclipse. if you are not using Java 5+ then the choice has been made for you. When using AspectJ.. @AspectJ or XML for Spring AOP? If you have chosen to use Spring AOP. If you need to advise objects not managed by the Spring container (such as domain objects typically). unambiguous. then you may want to consider using the @AspectJ style and sticking with a regular Java compilation in your IDE. use the code style. If you are not using Eclipse.Spring Framework you only need to advise the execution of operations on Spring beans. It can be used with any JDK level (referring to named pointcuts from within pointcut expressions does still require Java 5+ though) and is backed by genuine POJOs.

• The constructor of your proxied object will be called twice. All of these are implemented using the same underlying support mechanism and will co-exist without any difficulty. All of the interfaces implemented by the target type will be proxied. For each proxied instance. This is a natural consequence of the CGLIB proxy model whereby a subclass is generated for each proxied object. as they cannot be overriden.2 style in the same configuration. If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used. If the target object does not implement any interfaces then a CGLIB proxy will be created. to proxy every method defined for the target object. two objects are created: the actual proxied object and an instance of the subclass that 3. • You will need the CGLIB 2 binaries on your classpath.5 Mixing aspect types It is perfectly possible to mix @AspectJ style aspects using the autoproxying support. If you want to force the use of CGLIB proxying (for example.Spring Framework <aop:pointcut id="propertyAccess" expression="execution(* get*())"/> <aop:pointcut id="operationReturningAnAccount" expression="execution(org. whereas dynamic proxies are available with the JDK. It has the advantage of keeping the aspect as a modular unit. 8. schema-defined <aop:aspect> aspects.1 Reference Documentation 234 .so if you later decide you need the capabilities of AspectJ to implement additional requirements then it is very easy to migrate to an AspectJ-based approach.xyz. On balance the Spring team prefer the @AspectJ style whenever you have aspects that do more than simple "configuration" of enterprise services.Account+ *(. <aop:advisor> declared advisors and even proxies and interceptors defined using the Spring 1.6 Proxying mechanisms Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given target object. there are some issues to consider: • final methods cannot be advised. not just those implemented by its interfaces) you can do so. and richer pointcut composition. Spring will automatically warn you when it needs CGLIB and the CGLIB library classes are not found on the classpath. The @AspectJ style supports additional instantiation models.. 8. However. (JDK dynamic proxies are preferred whenever you have a choice).))"/> The downside of the XML approach is that you cannot define the 'accountPropertyAccess' pointcut by combining these definitions. It also has the advantage the @AspectJ aspects can be understood (and thus consumed) both by Spring AOP and by AspectJ .

on or Understanding AOP proxies Spring AOP is proxy-based. calling the constructor of the proxied type twice. which applies the strongest proxy settings that any of the <aop:config/> sections (typically from different XML bean definition files) specified. as illustrated by the following code snippet. To be clear: using 'proxy-target-class="true"' <tx:annotation-driven/>. the method is invoked directly on that object reference. It is vitally important that you grasp the semantics of what that last statement actually means before you write your own aspects or use any of the Spring AOP-based aspects supplied with the Spring Framework. nothing-special-about-it. straight object reference. --> </aop:config> To force CGLIB proxying when using the @AspectJ autoproxy support. This behavior is not exhibited when using JDK proxies. } } If you invoke a method on an object reference.Spring Framework implements the advice. Consider first the scenario where you have a plain-vanilla. as 3.1 Reference Documentation 235 ..bar().. } public void bar() { // some logic. <aop:aspectj-autoproxy/> <aop:config/> elements will force the use of CGLIB proxies for all three of them... This also applies to the <tx:annotation-driven/> and <aop:aspectj-autoproxy/> elements. To force the use of CGLIB proxies set the value of the proxy-target-class attribute of the <aop:config> element to true: <aop:config proxy-target-class="true"> <!-. un-proxied.other beans defined here. public class SimplePojo implements Pojo { public void foo() { // this next method invocation is a direct call on the 'this' reference this. set 'proxy-target-class' attribute of the <aop:aspectj-autoproxy> element to true: <aop:aspectj-autoproxy proxy-target-class="true"/> the Note Multiple <aop:config/> sections are collapsed into a single unified auto-proxy creator at runtime. is not an issue. as there are usually only assignments taking place and no real logic is implemented in the constructor. Usually.

factory. 3.class). Consider the following diagram and code snippet. public class Main { public static void main(String[] args) { ProxyFactory factory = new ProxyFactory(new SimplePojo()).addAdvice(new RetryAdvice()).Spring Framework can be seen below. public class Main { public static void main(String[] args) { Pojo pojo = new SimplePojo().addInterface(Pojo. // this is a direct method call on the 'pojo' reference pojo.foo().1 Reference Documentation 236 . factory. } } Things change slightly when the reference that client code has is a proxy.

Okay. and not the proxy. It means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute. which flies in the face of AOP. This has important implications. Pojo pojo = (Pojo) factory.bar(). least-invasive approach. and I am almost reticent to point it out precisely because it is so horrendous.foo(). // this is a method call on the proxy! pojo.Spring Framework Pojo pojo = (Pojo) factory. For sure. are going to be invoked against the this reference.setExposeProxy(true).bar() or this. but. } } This totally couples your code to Spring AOP. However... factory..adddInterface(Pojo.foo().1 Reference Documentation 237 .class). } } Finally. factory.) of the Main class has a reference to the proxy. but it is the best. } public void bar() { // some logic.getProxy(). 3. such as this. gah! ((Pojo) AopContext. factory. so what is to be done about this? The best approach (the term best is used loosely here) is to refactor your code such that the self-invocation does not happen. it must be noted that AspectJ does not have this self-invocation issue because it is not a proxy-based AOP framework. It also requires some additional configuration when the proxy is being created: public class Main { public static void main(String[] args) { ProxyFactory factory = new ProxyFactory(new SimplePojo()).addAdvice(new RetryAdvice()). any method calls that it may make on itself. // this is a method call on the proxy! pojo. this does entail some work on your part. and it makes the class itself aware of the fact that it is being used in an AOP context. the SimplePojo reference in this case. and as such the proxy will be able to delegate to all of the interceptors (advice) that are relevant to that particular method call.. You can (choke!) totally tie the logic within your class to Spring AOP by doing this: public class SimplePojo implements Pojo { public void foo() { // this works. once the call has finally reached the target object. } } The key thing to understand here is that the client code inside the main(.currentProxy()). The next approach is absolutely horrendous.. This means that method calls on that object reference will be calls on the proxy.foo().getProxy().

Spring AOP if your needs go beyond the facilities offered by Spring AOP alone.addAspect(usageTracker). which is available standalone in your distribution as spring-aspects. it is also possible programmatically to create proxies that advise target objects. // add an aspect.. // now get the proxy object. the section called “Using AspectJ to dependency inject domain objects with Spring” and the section called “Other Spring aspects for AspectJ” discuss the content of this library and how you can use it. The class org. For the full details of Spring's AOP API..jar contains an annotation-driven aspect that exploits this capability to allow dependency injection of any object. we're going to look at how you can use the AspectJ compiler/weaver instead of.jar. the class must be an @AspectJ aspect // you can call this as many times as you need with different aspects factory. 8. the section called “Load-time weaving with AspectJ in the Spring Framework” provides an introduction to load-time weaving for Spring applications using AspectJ. // you can also add existing aspect instances.getProxy(). MyInterfaceType proxy = factory. The spring-aspects.7 Programmatic creation of @AspectJ Proxies In addition to declaring aspects in your configuration using either <aop:config> or <aop:aspectj-autoproxy>. as illustrated below.springframework. you'll need to add this to your classpath in order to use the aspects in it.class).1 Reference Documentation 238 . Domain objects often fall into this 3.Spring Framework 8. Here we want to focus on the ability to automatically create proxies using @AspectJ aspects. the type of the object supplied must be an @AspectJ aspect factory. or in addition to. Spring ships with a small AspectJ aspect library. the section called “Configuring AspectJ aspects using Spring IoC” discusses how to dependency inject AspectJ aspects that are woven using the AspectJ compiler. The support is intended to be used for objects created outside of the control of any container. Using AspectJ to dependency inject domain objects with Spring The Spring container instantiates and configures beans defined in your application context. Basic usage for this class is very simple. // create a factory that can generate a proxy for the given target object AspectJProxyFactory factory = new AspectJProxyFactory(targetObject).annotation. see the next chapter.addAspect(SecurityManager.8 Using AspectJ with Spring applications Everything we've covered so far in this chapter is pure Spring AOP. It is also possible to ask a bean factory to configure a pre-existing object given the name of a bean definition containing the configuration to be applied.aspectj. Finally.AspectJProxyFactory can be used to create a proxy for a target object that is advised by one or more @AspectJ aspects.aop. See the Javadocs for full information. In this section.

domain.Configurable.myapp.. or by an ORM tool as a result of a database query. “Annotation-based container configuration” for further details)..xyz.Account).. import org.xyz. Finally you can enable Spring dependency checking for the object references in the newly created and configured object by using the dependencyCheck attribute (for example: @Configurable(autowire=Autowire.springframework.factory. @Configurable public class Account { // .9.annotation.Configurable.Spring Framework category because they are often created programmatically using the new operator.xyz.1 Reference Documentation 239 .BY_TYPE) or @Configurable(autowire=Autowire. as of Spring 2. } When used as a marker interface in this way.springframework.factory. You can also use autowiring to avoid having to specify a prototype-scoped bean definition at all.domain.beans. In the simplest case it can be used just as a marker annotation: package com. The @Configurable annotation marks a class as eligible for Spring-driven configuration.domain.BY_NAME for autowiring by type or by name respectively. import org.Account" scope="prototype"> <property name="fundsTransferService" ref="fundsTransferService"/> </bean> If you want to explicitly specify the name of the prototype bean definition to use.xyz. annotation-driven dependency injection for your @Configurable beans by using @Autowired or @Inject at the field or method level (see Section 4. then Spring will validate after configuration that all properties (which are not 3.BY_NAME.. If this attribute is set to true.myapp.domain. Since the default name for a bean is the fully-qualified name of its type.annotation. a convenient way to declare the prototype definition is simply to omit the id attribute: <bean class="com. @Configurable("account") public class Account { // .beans. Spring will configure new instances of the annotated type (Account in this case) using a prototype-scoped bean definition with the same name as the fully-qualified type name (com. you can do so directly in the annotation: package com.myapp. To have Spring apply autowiring use the 'autowire' property of the @Configurable annotation: specify either @Configurable(autowire=Autowire.5 it is preferable to specify explicit. } Spring will now look for a bean definition named "account" and use that as the definition to configure new Account instances.dependencyCheck=true)). As an alternative.myapp.

1 Reference Documentation 240 ...aspectj. the exact semantics of 'after returning from the initialization of a new object' will be fine.springframework.factory. It is the AnnotationBeanConfigurerAspect in spring-aspects.. in this context. 'after initialization' means that the dependencies will be injected after the object has been constructed . In essence the aspect says "after returning from the initialization of a new object of a type annotated with @Configurable. In this context.. If you want the dependencies to be injected before the constructor bodies execute. the equivalent definition is: <bean class="org.AnnotationBeanConfigurerAspect" factory-method="aspectOf"/> Instances of @Configurable objects created before the aspect has been configured will result in a warning being issued to the log and no configuration of the object taking place.you can either use a build-time Ant or Maven task to do this (see for example the AspectJ Development Environment Guide) or load-time weaving (see the section called “Load-time weaving with AspectJ in the Spring Framework”). An example might be a bean in the Spring configuration that creates domain objects when it is initialized by Spring. via readResolve()). The AnnotationBeanConfigurerAspect itself needs configuring by Spring (in order to obtain a reference to the bean factory that is to be used to configure new objects).g.Spring Framework primitives or collections) have been set. Note One of the key phrases in the above paragraph is 'in essence'. configure the newly created object using Spring in accordance with the properties of the annotation". For this to work the annotated types must be woven with the AspectJ weaver . initialization refers to newly instantiated objects (e. objects instantiated with the 'new' operator) as well as to Serializable objects that are undergoing deserialization (e.beans.jar that acts on the presence of the annotation.g. In this case you can use the "depends-on" bean attribute to manually specify that the bean depends on the configuration aspect. then you need to define this on the @Configurable declaration like so: @Configurable(preConstruction=true) You can find out more information about the language semantics of the various pointcut types in AspectJ in this appendix of the AspectJ Programming Guide. The Spring context namespace defines a convenient tag for doing this: just include the following in your application context configuration: <context:spring-configured/> If you are using the DTD instead of schema. 3. Using the annotation on its own does nothing of course. For most cases.this means that the dependencies will not be available for use in the constructor bodies of the class. and thus be available for use in the body of the constructors.

1 Reference Documentation 241 . All of these contexts will co-exist within the same classloader hierarchy. Consider a typical Spring web-app configuration with a shared parent application context defining common business services and everything needed to support them. Working with multiple application contexts The AnnotationBeanConfigurerAspect used to implement the @Configurable support is an AspectJ singleton aspect.. ensure that each web-application loads the 3. In this case we recommend defining the <context:spring-configured/> bean in the shared (parent) application context: this defines the services that you are likely to want to inject into domain objects. Unit testing @Configurable objects One of the goals of the @Configurable support is to enable independent unit testing of domain objects without the difficulties associated with hard-coded lookups.. If @Configurable types have not been woven by AspectJ then the annotation has no affect during unit testing. The scope of a singleton aspect is the same as the scope of static members.beans.jar on the classpath.AnnotationBeanConfigurerAspect"> <!-. once through the container and once through the aspect. and so the AnnotationBeanConfigurerAspect can only hold a reference to one of them. In particular.factory. A consequence is that you cannot configure domain objects with references to beans defined in the child (servlet-specific) contexts using the @Configurable mechanism (probably not something you want to do anyway!). If @Configurable types have been woven by AspectJ then you can still unit test outside of the container as normal. that is to say there is one aspect instance per classloader that defines the type.Spring Framework <bean id="myService" class="com.springframework. --> </bean> Note Do not activate @Configurable processing through the bean configurer aspect unless you really mean to rely on its semantics at runtime..service.myapp. When deploying multiple web-apps within the same container. and you can simply set mock or stub property references in the object under test and proceed as normal. but you will see a warning message each time that you construct an @Configurable object indicating that it has not been configured by Spring.MyService" depends-on="org.aspectj. This means that if you define multiple application contexts within the same classloader hierarchy you need to consider where to define the <context:spring-configured/> bean and where to place spring-aspects. make sure that you do not use @Configurable on bean classes which are registered as regular Spring beans with the container: You would get double initialization otherwise. and one child application context per servlet containing definitions particular to that servlet.xzy.

Spring Framework types in spring-aspects. If spring-aspects.)) && SystemArchitecture. } // the creation of a new bean (any object in the domain model) protected pointcut beanCreation(Object beanInstance) : initialization(new(.1 Reference Documentation 242 .inDomainModel() && this(beanInstance). The aspect that interprets @Transactional annotations is the AnnotationTransactionAspect. } Configuring AspectJ aspects using Spring IoC 3. Other Spring aspects for AspectJ In addition to the @Configurable aspect.jar in 'WEB-INF/lib'). As an example. and default visibility may all be annotated. not the interface (if any) that the class implements. A @Transactional annotation on a method within the class overrides the default transaction semantics given by the class annotation (if present). When using this aspect. the following excerpt shows how you could write an aspect to configure all instances of objects defined in the domain model using prototype bean definitions that match the fully-qualified class names: public aspect DomainObjectConfiguration extends AbstractBeanConfigurerAspect { public DomainObjectConfiguration() { setBeanWiringInfoResolver(new ClassNameBeanWiringInfoResolver()). For AspectJ programmers that want to use the Spring configuration and transaction management support but don't want to (or cannot) use annotations. you must annotate the implementation class (and/or methods within that class). Methods with public. AspectJ follows Java's rule that annotations on interfaces are not inherited.jar using its own classloader (for example.jar is only added to the container wide classpath (and hence loaded by the shared parent classloader).jar contains an AspectJ aspect that can be used to drive Spring's transaction management for types and methods annotated with the @Transactional annotation. protected.jar also contains abstract aspects you can extend to provide your own pointcut definitions. A @Transactional annotation on a class specifies the default transaction semantics for the execution of any public operation in the class. by placing spring-aspects. See the sources for the AbstractBeanConfigurerAspect and AbstractTransactionAspect aspects for more information. Annotating protected and default visibility methods directly is the only way to get transaction demarcation for the execution of such methods. spring-aspects. all web applications will share the same aspect instance which is probably not what you want. spring-aspects.. This is primarily intended for users who want to use the Spring Framework's transaction support outside of the Spring container.

and include the bean attribute 'factory-method="aspectOf"'. and the means of configuring the AspectJ created aspects via Spring depends on the AspectJ instantiation model (the 'per-xxx' clause) used by the aspect. using load-time weaving for domain model types) and other @AspectJ aspects that you want to use with Spring AOP.jar to configure the aspect instances once they have bean created by the AspectJ runtime. and only beans with names matched by at least one of the patterns will be used for Spring AOP autoproxy configuration: <aop:aspectj-autoproxy> <aop:include name="thisBean"/> <aop:include name="thatBean"/> </aop:aspectj-autoproxy> Note Do not be misled by the name of the <aop:aspectj-autoproxy/> element: using it will result in the creation of Spring AOP proxies. For example: <bean id="profiler" class="com. then you will need to tell the Spring AOP @AspectJ autoproxying support which exact subset of the @AspectJ aspects defined in the configuration should be used for autoproxying. Load-time weaving with AspectJ in the Spring Framework Load-time weaving (LTW) refers to the process of weaving AspectJ aspects into an application's class files as they are being loaded into the Java virtual machine (JVM). it is natural to both want and expect to be able to configure such aspects using Spring.Profiler" factory-method="aspectOf"> <property name="profilingStrategy" ref="jamonProfilingStrategy"/> </bean> Non-singleton aspects are harder to configure: however it is possible to do so by creating prototype bean definitions and using the @Configurable support from spring-aspects.Spring Framework When using AspectJ aspects with Spring applications.profiler.xyz. but the AspectJ runtime is not involved. Configuration of these aspects is very easy: simply create a bean definition referencing the aspect type as normal. The majority of AspectJ aspects are singleton aspects. The AspectJ runtime itself is responsible for aspect creation. If you have some @AspectJ aspects that you want to weave with AspectJ (for example. and these aspects are all configured using Spring. Each <include/> element specifies a name pattern. You can do this by using one or more <include/> elements inside the <aop:aspectj-autoproxy/> declaration.1 Reference Documentation 243 . For full details on the specifics of LTW and configuring LTW with just AspectJ (with Spring not being involved at all). The focus of this section is on configuring and using LTW in the specific context of the Spring Framework: this section is not an introduction to LTW though. see the LTW section of the AspectJ Development 3. The @AspectJ style of aspect declaration is just being used here. This ensures that Spring obtains the aspect instance by asking AspectJ for it rather than trying to create an instance itself.

springframework.springframework. which is switched on by specifying a VM argument when starting up a JVM. followed by detailed specifics about elements introduced in the following example. org.Order. try { sw.lang.core. 'Vanilla' AspectJ LTW is effected using a Java (5+) agent.util.jar or (as we describe later in this section) -javaagent:path/to/org. } 3.StopWatch.proceed().ProceedingJoinPoint.stop().annotation.aspectj.annotation. @Aspect public class ProfilingAspect { @Around("methodsToBeProfiled()") public Object profile(ProceedingJoinPoint pjp) throws Throwable { StopWatch sw = new StopWatch(getClass(). which may be fine in some situations.aspectj.getName()). org.getSimpleName()). using the @AspectJ-style of aspect declaration. Nothing too fancy.Aspect. let us first walk through a quick example of AspectJ LTW using Spring. in certain environments. It is thus a JVM-wide setting. please see the Petclinic sample application.aspectj.springframework. org.out. For a complete example. Now that the sales pitch is over. import import import import import import org.lang. Developers simply modify one or more files that form the application context to enable load-time weaving instead of relying on administrators who typically are in charge of the deployment configuration such as the launch script. Further. so that we can then apply a finer-grained profiling tool to that specific area immediately afterwards. this support enables load-time weaving without making any modifications to the application server's launch script that will be needed to add -javaagent:path/to/aspectjweaver. which obviously is more fine-grained and which can make more sense in a 'single-JVM-multiple-application' environment (such as is found in a typical application server environment).1 Reference Documentation 244 .start(pjp.Around.prettyPrint()).getSignature().annotation. Here is the profiling aspect. Rather than break out a profiling tool.annotation.jar (previously named spring-agent. package foo.jar).aspectj. org. System.Spring Framework Environment Guide.lang. return pjp. Spring-enabled LTW enables you to switch on LTW on a per-ClassLoader basis. } finally { sw.Pointcut. just a quick-and-dirty time-based profiler. what we are going to do is switch on a simple profiling aspect that will enable us to very quickly get some performance metrics. org. The value-add that the Spring Framework brings to AspectJ LTW is in enabling much finer-grained control over the weaving process. but often is a little too coarse. A first example Let us assume that you are an application developer who has been tasked with diagnosing the cause of some performance problems in a system.println(sw.lang.instrument-{version}.

only weave classes in our application-specific packages --> <include within="foo.xml' files into the classes in your application.org/schema/context" xsi:schemaLocation=" http://www. we will be profiling its methods --> <bean id="entitlementCalculationService" class="foo.xml' file.1 Reference Documentation 245 .0" encoding="UTF-8"?> <beans xmlns="http://www. <?xml version="1.org/schema/beans" xmlns:xsi="http://www. This file convention.*(.0.0..dtd"> <aspectj> <weaver> <!-.org/2001/XMLSchema-instance" xmlns:context="http://www. just take it on trust for now).StubEntitlementCalculationService"/> <!-. This load-time weaver is the essential component responsible for weaving the aspect configuration in one or more 'META-INF/aop. and the Spring configuration -. The good thing is that it does not require a lot of configuration.org/schema/context/spring-context-3.springframework.) method to demonstrate the LTW in action.org/schema/beans/spring-beans-3.weave in just this aspect --> <aspect name="foo.a service object. 3.springframework.. <!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.this switches on the load-time weaving --> <context:load-time-weaver/> </beans> Now that all the required artifacts are in place . We need to configure a LoadTimeWeaver (all explained later.springframework. but these are detailed later). the 'META-INF/aop.springframework.springframework.org/schema/context http://www.the aspect.ProfilingAspect"/> </aspects> </aspectj> Now to the Spring-specific portion of the configuration.*"/> </weaver> <aspects> <!-.xsd http://www. namely the presence of a file (or files) on the Java classpath called ' META-INF/aop.eclipse. as can be seen below (there are some more options that you can specify.xml' is standard AspectJ..Spring Framework } @Pointcut("execution(public * foo.xsd"> <!-.*.w3. let us create a simple driver class with a main(.xml' file.org/schema/beans http://www. to inform the AspectJ weaver that we want to weave our ProfilingAspect into our classes.))") public void methodsToBeProfiled(){} } We will also need to create an 'META-INF/aop.springframework.org/aspectj/dtd/aspectj.

springframework. import org.----.xml". The Spring Framework ships with such an agent.) statement into the calculateEntitlement() implementation so that the profiler actually captures something other than 0 milliseconds . public final class Main { public static void main(String[] args) { new ClassPathXmlApplicationContext("beans.---------------------------01234 100% calculateEntitlement Since this LTW is effected using full-blown AspectJ. However. just for this example.springframework.----.calculateEntitlement(). The output from the execution of the Main program will look something like that below.1 Reference Documentation 246 . EntitlementCalculationService entitlementCalculationService = (EntitlementCalculationService) ctx. import org. public final class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans. Main. } } There is one last thing to do.class).class).Main The '-javaagent' is a Java 5+ flag for specifying and enabling agents to instrument programs running on the JVM. the InstrumentationSavingAgent. EntitlementCalculationService entitlementCalculationService = 3.Spring Framework package foo. we are going to use a Java agent (supplied with Spring) to switch on the LTW. (I have introduced a Thread. the following slight variation on the Main program will yield the same result.the 01234 milliseconds is not an overhead introduced by the AOP :) ) Calculating entitlement StopWatch 'ProfilingAspect': running time (millis) = 1234 -----.context.---------------------------ms % Task name -----. Main.getBean("entitlementCalculationService").ClassPathXmlApplicationContext.support.support.ClassPathXmlApplicationContext.sleep(. // the profiling aspect is 'woven' around this method execution entitlementCalculationService. package foo. we are not just limited to advising Spring beans. The introduction to this section did say that one could switch on LTW selectively on a per-ClassLoader basis with Spring. This is the command line we will use to run the above Main class: java -javaagent:C:/projects/foo/lib/global/spring-instrument.jar foo.context..jar that was supplied as the value of the -javaagent argument in the above example. and this is true.xml". which is packaged in the spring-instrument.

and so there is no extra value that I can contribute either as a result). 'META-INF/aop. They can be written in either the AspectJ language itself or you can write your aspects in the @AspectJ-style... spring-aop. } } Notice how in the above program we are simply bootstrapping the Spring container. and then quite easily exclude from builds of the application being deployed into UAT or production. Aspects The aspects that you use in LTW have to be AspectJ aspects. The structure and contents of this file is detailed in the main AspectJ reference documentation.) Required libraries (JARS) At a minimum you will need the following libraries to use the Spring Framework's support for AspectJ LTW: 1.calculateEntitlement(). plus all mandatory dependencies) 3. Note The ProfilingAspect used in this example may be basic.xml' files. and the interested reader is referred to that resource. the profiling advice still gets woven in.xml' file is 100% AspectJ . but it is quite useful. however the basics of the LTW support in Spring have all been introduced in the above example. but the 'aop.. that are on the Java classpath (either directly.jar (version 2.xml' The AspectJ LTW infrastructure is configured using one or more 'META-INF/aop. The latter option is of course only an option if you are using Java 5+. Furthermore. and then creating a new instance of the StubEntitlementCalculationService totally outside the context of Spring..Spring Framework new StubEntitlementCalculationService().1 Reference Documentation 247 . so rather than rehash the quite satisfactory section that the AspectJ developers wrote. // the profiling aspect will be 'woven' around this method execution entitlementCalculationService. the compiled aspect classes need to be available on the classpath. I am just directing you there. (I appreciate that this section is brief. The example admittedly is simplistic. but it does mean that your aspects are then both valid AspectJ and Spring AOP aspects.there is no Spring-specific information or semantics that apply to it. It is a nice example of a development-time aspect that developers can use during development (of course).5 or later. and the rest of this section will explain the 'why' behind each bit of configuration and usage in detail. or more typically in jar files).

org/schema/beans/spring-beans-3. aspectjweaver.xsd"> <context:load-time-weaver/> </beans> The above <context:load-time-weaver/> bean definition will define and register a number of LTW-specific infrastructure beans for you automatically.1 Reference Documentation 248 .instrument.0. which opens the door to all manner of interesting applications.springframework.Spring Framework 2. (Please note that you almost certainly will need to be using an ApplicationContext as your Spring container .instrument package before continuing.0" encoding="UTF-8"?> <beans xmlns="http://www.org/schema/context" xsi:schemaLocation=" http://www.org/schema/beans" xmlns:xsi="http://www.instrument.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.0..jar (version 1.jar Spring configuration The key component in Spring's LTW support is the LoadTimeWeaver interface (in the org.lang.6. Notice how the <context:load-time-weaver/> is defined in the 3. and the numerous implementations of it that ship with the Spring distribution. A LoadTimeWeaver is responsible for adding one or more java. which typically is done using the <context:load-time-weaver/> element. Find below a valid <context:load-time-weaver/> definition that uses default settings.rather annoyingly . you will also need: 1.w3.springframework.xsd http://www. spring-instrument.springframework.precious little documentation there.) To enable the Spring Framework's LTW support.springframework.typically a BeanFactory will not be enough because the LTW support makes use of BeanFactoryPostProcessors.org/schema/beans http://www.lang. one of which happens to be the LTW of aspects. the key interfaces and classes will at least be laid out in front of you for reference as you read through this section. such as a LoadTimeWeaver and an AspectJWeavingEnabler. Tip If you are unfamiliar with the idea of runtime class file transformation.ClassFileTransformers to a ClassLoader at runtime.org/schema/context/spring-context-3. <?xml version="1.8 or later) If you are using the Spring-provided agent to enable instrumentation. This is not a huge chore because there is ..classloading package).org/schema/context http://www. you need to configure a LoadTimeWeaver. Configuring a LoadTimeWeaver using XML for a particular ApplicationContext can be as easy as adding one line.springframework.springframework. you are encouraged to read the Javadoc API documentation for the java.

g.5 and later. expecting the underlying ClassLoader to ReflectiveLoadTimeWeaver follow common conventions (e.org/schema/beans" xmlns:xsi="http://www. Table 8.org/schema/context" xsi:schemaLocation=" 3.jar) Fallback.w3.1 Reference Documentation 249 .springframework. note also that the referenced XML Schema file is only available in versions of Spring 2.1.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.0" encoding="UTF-8"?> <beans xmlns="http://www. DefaultContextLoadTimeWeaver LoadTimeWeavers Runtime Environment Running in BEA's Weblogic 10 Running in IBM WebSphere Application Server 7 Running in Oracle's OC4J Running in GlassFish Running in JBoss AS JVM started with Spring InstrumentationSavingAgent LoadTimeWeaver implementation WebLogicLoadTimeWeaver WebSphereLoadTimeWeaver OC4JLoadTimeWeaver GlassFishLoadTimeWeaver JBossLoadTimeWeaver InstrumentationLoadTimeWeaver (java -javaagent:path/to/spring-instrument. which attempts to decorate an automatically detected LoadTimeWeaver: the exact type of LoadTimeWeaver that will be 'automatically detected' is dependent upon your runtime environment (summarised in the following table). Find below an example of doing just that: <?xml version="1. applicable to TomcatInstrumentableClassLoader and Resin) Note that these are just the LoadTimeWeavers that are autodetected when using the DefaultContextLoadTimeWeaver: it is of course possible to specify exactly which LoadTimeWeaver implementation that you wish to use by specifying the fully-qualified classname as the value of the 'weaver-class' attribute of the <context:load-time-weaver/> element. The default LoadTimeWeaver is the DefaultContextLoadTimeWeaver class.Spring Framework 'context' namespace. What the above configuration does is define and register a default LoadTimeWeaver bean for you.

else it is off. This is the default value. because the specifics of how the weaving is actually effected is beyond the scope of this section. It accepts one of three possible values.org/schema/context http://www. LTW is off. summarised below. Remember that the LoadTimeWeaver exists just as a mechanism for Spring's LTW infrastructure to add one or more ClassFileTransformers.springframework. The actual ClassFileTransformer that does the LTW is the ClassPreProcessorAgentAdapter (from the org.classloading.0. 'aspectj-weaving' attribute values Attribute Value on Explanation AspectJ weaving is on. then AspectJ weaving is on.0.org/schema/beans http://www. Tomcat Apache Tomcat's default class loader does not support class transformation which is why Spring provides 3. This is a simple attribute that controls whether LTW is enabled or not.springframework.. no aspect will be woven at load-time. and aspects will be woven at load-time as appropriate.xml' file. with the default value if the attribute is not present being ' autodetect' Table 8.2. off autodetect Environment-specific configuration This last section contains any additional settings and configuration that you will need when using Spring's LTW support in environments such as application servers and web containers. it is as simple as that.xsd http://www.springframework.loadtime package) class.xsd"> <context:load-time-weaver weaver-class="org.. If the Spring LTW infrastructure can find at least one 'META-INF/aop.1 Reference Documentation 250 . See the class-level Javadoc for the ClassPreProcessorAgentAdapter class for further details. There is one final attribute of the <context:load-time-weaver/> left to discuss: the 'aspectj-weaving' attribute.springframework.springframework.org/schema/beans/spring-beans-3.org/schema/context/spring-context-3.Spring Framework http://www.instrument.ReflectiveLoadTimeWeaver"/> </beans> The LoadTimeWeaver that is defined and registered by the <context:load-time-weaver/> element can be later retrieved from the Spring container using the well-known name 'loadTimeWeaver'.aspectj.weaver.

0.5.tomcat.springframework.xml .0. Instruct Tomcat to use the custom class loader (instead of the default) by editing the web application context file: <Context path="/myWebApp" docBase="/my/webApp/location"> <Loader loaderClass="org.springframework.x series supports several context locations: • server configuration file .instrument.0.that affects all deployed web applications • per-web application configuration which can be deployed either on the server-side at $CATALINA_HOME/conf/[enginename]/[hostname]/[webapp]-context.springframework.xml or embedded inside the web-app archive at META-INF/context.5. the loader works on Tomcat 5.xml 3.0 and above and can be registered individually for each web application as follows: • Tomcat 6. where $CATALINA_HOME represents the root of the Tomcat installation) 2.instrument. Copy org. Instruct Tomcat to use the custom class loader instead of the default one by editing the web application context file: <Context path="/myWebApp" docBase="/my/webApp/location"> <Loader loaderClass="org.classloading.0. Copy org.springframework. 2. Named TomcatInstrumentableClassLoader.TomcatInstrumentableClassLoader"/> </Context> Tomcat 5.xml For efficiency.x) series supports several context locations: • server configuration file . the embedded per-web-app configuration style is recommended because it will impact only applications that use the custom class loader and does not require any changes to the server configuration.1 Reference Documentation 251 .x and 5.x documentation for more details about available context locations.instrument.5.jar into $CATALINA_HOME/lib.$CATALINA_HOME/conf/server.jar into $CATALINA_HOME/server/lib.x/5.0.$CATALINA_HOME/conf/server.TomcatInstrumentableClassLoader"/> </Context> Apache Tomcat 6. • Tomcat 5.$CATALINA_HOME/conf/context.Spring Framework an enhanced implementation that addresses this need.tomcat.classloading.x or higher 1.x 1. where $CATALINA_HOME represents the root of the Tomcat installation.tomcat.instrument. See the Tomcat 6.x/5.tomcat.x (similar to 5.0.xml • default context configuration .

jar. You can enable LTW by simply activating context:load-time-weaver as described earlier. no matter what ClassLoader they happen to run on.xml configuration. Resin (3.1 and above). GlassFish. Specifically. follow the Tomcat setup instructions as outlined above.xml . you should set useSystemClassLoaderAsParent to false to fix this problem: <Context path="/myWebApp" docBase="/my/webApp/location"> <Loader loaderClass="org. consider the use of the Spring-provided generic VM agent.0"/> 3.classloading. For GlassFish web applications. the app server scanning needs to be disabled to prevent it from loading the classes before the application actually starts. you do not need to modify the launch script to add -javaagent:path/to/spring-instrument. WebLogic.Spring Framework • default context configuration .20 or later. In Tomcat 5.xml or embedded inside the web-app archive at META-INF/context.TomcatInstrumentableClassLoader" useSystemClassLoaderAsParent="false"/> </Context> This setting is not needed on Tomcat 6 or higher. WebSphere.instrument. See the Tomcat 5. This will make instrumentation available to all deployed web applications. A quick workaround is to add to your artifact a file named WEB-INF/jboss-scanning. See Tomcat's bugzilla for more details. Note that on JBoss 6. JBoss Recent versions of BEA WebLogic (version 10 and above). Note that GlassFish instrumentation-capable ClassLoader is available only in its EAR environment. OC4J.3.1 Reference Documentation 252 .1. Oracle Containers for Java EE (OC4J 10.x.20 contained a bug in the XML configuration parsing that prevented usage of the Loader tag inside server. the embedded web-app configuration style is recommended recommended because it will impact only applications that use the class loader.x. versions 5. Spring's native LTW leverages such ClassLoaders to enable AspectJ weaving.springframework.xml with the following content: <scanning xmlns="urn:jboss:scanning:1.5.1 and above) and JBoss (5. IBM WebSphere Application Server (version 7 and above).tomcat. regardless of whether a class loader is specified or whether it is the official or a custom one.$CATALINA_HOME/conf/context. Alternatively.x documentation for more details about available context locations.5.x or above) provide a ClassLoader that is capable of local instrumentation. Tomcat versions prior to 5.that affects all deployed web applications • per-web application configuration which can be deployed either on the server-side at $CATALINA_HOME/conf/[enginename]/[hostname]/[webapp]-context. Resin.5. to be specified in Tomcat's launch script (see above).xml For efficiency.

a JDK agent can be the only solution. the focus of the book is on AspectJ. For such cases. 2005) provides a comprehensive introduction and reference for the AspectJ language. which requires a Spring-specific (but very general) VM agent. al. you must start the virtual machine with the Spring agent.Spring Framework Generic Java applications When class instrumentation is required in environments that do not support or are not supported by the existing LoadTimeWeaver implementations. To use it. For performance reasons. 8. Spring provides InstrumentationLoadTimeWeaver. org. 2003) comes highly recommended. it is recommended to use this configuration only if your target environment (such as Jetty) does not have (or does not support) a dedicated LTW. by supplying the following JVM options: -javaagent:/path/to/org. the JDK agent will instrument the entire VM which can prove expensive.1 Reference Documentation 253 .9 Further Resources More information on AspectJ can be found on the AspectJ website. The book AspectJ in Action by Ramnivas Laddad (Manning.instrument-{version}.jar). Additionally. (Addison-Wesley.instrument-{version}. but a lot of general AOP themes are explored (in some depth).springframework.jar (previously named spring-agent.springframework. 3.jar Note that this requires modification of the VM launch script which may prevent you from using this in application server environments (depending on your operation policies). The book Eclipse AspectJ by Adrian Colyer et.

It's possible to target different advice using the same pointcut. you may come across Spring 1. and fine-grained composition operations (such as performing a "union" with another method matcher). Concepts Spring's pointcut model enables pointcut reuse independent of advice types.2 Pointcut API in Spring Let's look at how Spring handles the crucial pointcut concept. but when working with existing applications.1 Reference Documentation 254 .Pointcut interface is the central interface. The ClassFilter interface is used to restrict the pointcut to a given set of target classes. 9. all target classes will be matched: public interface ClassFilter { boolean matches(Class clazz).2 style examples.springframework. The org. If the matches() method always returns true. Spring AOP APIs 9.1 Introduction The previous chapter described the Spring 2. Spring 3.0 and later AOP support described in the previous chapter.aop. or when reading books and articles. } Splitting the Pointcut interface into two parts allows reuse of class and method matching parts. } The MethodMatcher interface is normally more important.0.2 and everything described in this chapter is fully supported in Spring 3. The complete interface is shown below: public interface MethodMatcher { 3.0 is backwards compatible with Spring 1.0 and later version's support for AOP using @AspectJ and schema-based aspect definitions. used to target advices to particular classes and methods. For new applications. MethodMatcher getMethodMatcher().2 applications.Spring Framework 9. In this chapter we discuss the lower-level Spring AOP APIs and the AOP support used in Spring 1. we recommend the use of the Spring 2. The complete interface is shown below: public interface Pointcut { ClassFilter getClassFilter().

the 3-argument matches method will be invoked on every method invocation.AspectJExpressionPointcut. • Union means the methods that either pointcut matches. } The matches(Method. If the 2-argument matches method returns true for a given method. meaning that their isRuntime() method returns false. allowing the AOP framework to cache the results of pointcut evaluation when an AOP proxy is created. using AspectJ pointcut expressions is usually a simpler approach. to avoid the need for a test on every method invocation.aop. try to make pointcuts static.Spring Framework boolean matches(Method m.springframework. Class targetClass.aspectj. and the isRuntime() method for the MethodMatcher returns true. In this case. Most MethodMatchers are static. • Intersection means the methods that both pointcuts match. boolean isRuntime().1 Reference Documentation 255 . Operations on pointcuts Spring supports operations on pointcuts: notably. the most important type of pointcut used by Spring is org. • Union is usually more useful.0. AspectJ expression pointcuts Since 2. This enables a pointcut to look at the arguments passed to the method invocation immediately before the target advice is to execute.springframework.support. union and intersection. boolean matches(Method m. or using the ComposablePointcut class in the same package.Pointcuts class. Class) method is used to test whether this pointcut will ever match a given method on a target class. This is a pointcut that uses an AspectJ supplied library to parse an AspectJ pointcut expression string.aop. Tip If possible. See the previous chapter for a discussion of supported AspectJ pointcut primitives. the 3-argument matches method will never be invoked. Object[] args). This evaluation can be performed when an AOP proxy is created. • Pointcuts can be composed using the static methods in the org. However. Class targetClass). Convenience pointcut implementations 3.

*set.for most usages. (So the result is effectively the union of these pointcuts. Behind the scenes.springframework.and best . there is no need to evaluate the pointcut again with each method invocation. as shown below: <bean id="settersAndAbsquatulateAdvisor" class="org.aop.aop. as the one bean encapsulates both pointcut and advice. Several AOP frameworks besides Spring make this possible.*</value> <value>. the pointcut will evaluate to true. throws advice etc. and cannot take into account the method's arguments. It's possible for Spring to evaluate a static pointcut only once.aop. that allows us to also reference an Advice (remember that an Advice can be an interceptor. If any of these is a match.4+. using the regular expression support in JDK 1. when a method is first invoked: after that. you can provide a list of pattern Strings.) The usage is shown below: <bean id="settersAndAbsquatulatePointcut" class="org. Let's consider some static pointcut implementations included with Spring.springframework.support. Using RegexpMethodPointcutAdvisor simplifies wiring.*absquatulate</value> </list> </property> </bean> Spring provides a convenience class. Some can be used out of the box.).support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="beanNameOfAopAllianceInterceptor"/> </property> <property name="patterns"> <list> <value>.Spring Framework Spring provides several convenient pointcut implementations. others are intended to be subclassed in application-specific pointcuts. Spring will use a JdkRegexpMethodPointcut. org. RegexpMethodPointcutAdvisor. Using the JdkRegexpMethodPointcut class.JdkRegexpMethodPointcut is a generic regular expression pointcut.*set. before advice.support.1 Reference Documentation 256 . Static pointcuts are sufficient .*</value> <value>. Regular expression pointcuts One obvious way to specify static pointcuts is regular expressions.*absquatulate</value> 3.JdkRegexpMethodPointcut"> <property name="patterns"> <list> <value>. Static pointcuts Static pointcuts are based on method and target class.springframework.

The main example is the control flow pointcut.4. Class targetClass) { // return true if custom criteria match 3. Control flow pointcuts Spring control flow pointcuts are conceptually similar to AspectJ cflow pointcuts. Attribute-driven pointcuts An important type of static pointcut is a metadata-driven pointcut. source-level metadata. Dynamic pointcuts Dynamic pointcuts are costlier to evaluate than static pointcuts.mycompany. as well as static information. This requires implementing just one abstract method (although it's possible to override other methods to customize behavior): class TestStaticPointcut extends StaticMethodMatcherPointcut { public boolean matches(Method m. it might fire if the join point was invoked by a method in the com.ControlFlowPointcut class. Pointcut superclasses Spring provides useful pointcut superclasses to help you to implement your own pointcuts.aop.1 Reference Documentation 257 .) A control flow pointcut matches the current call stack. Note Control flow pointcuts are significantly more expensive to evaluate at runtime than even other dynamic pointcuts.springframework. the result cannot be cached. as shown below. Control flow pointcuts are specified using the org. although less powerful.Spring Framework </list> </property> </bean> RegexpMethodPointcutAdvisor can be used with any Advice type. you'll probably subclass StaticMethodMatcherPointcut. They take into account method arguments. In Java 1. This uses the values of metadata attributes: typically.web package.support. or by the SomeCaller class. Because static pointcuts are most useful. as arguments will vary. For example. the cost is about 5 times that of other dynamic pointcuts. This means that they must be evaluated with every method invocation. (There is currently no way to specify that a pointcut executes below a join point matched by another pointcut.

It's possible to use a mix of shared and per-instance advice in the same AOP proxy. using the AspectJ pointcut expression language is recommended if possible. It is appropriate for generic advice such as transaction advisors. However. Custom pointcuts Because pointcuts in Spring AOP are Java classes. and is extensible to support arbitrary advice types. "all methods that change instance variables in the target object. These do not depend on the state of the proxied object or add new state.Spring Framework } } There are also superclasses for dynamic pointcuts. This corresponds to per-class or per-instance advice. Per-instance advice is appropriate for introductions. whether static or dynamic. Custom pointcuts in Spring can be arbitrarily complex. the advice adds state to the proxied object. You can use custom pointcuts with any advice type in Spring 1. Let us look at the basic concepts and standard advice types. Advice types in Spring Spring provides several advice types out of the box. Note Later versions of Spring may offer support for "semantic pointcuts" as offered by JAC: for example. to support mixins.3 Advice API in Spring Let's now look at how Spring AOP handles advice." 9.0 RC2 and above. or unique to each advised object. Per-class advice is used most often. they merely act on the method and arguments. Interception around advice 3. rather than language features (as in AspectJ) it's possible to declare custom pointcuts. In this case. An advice instance can be shared across all advised objects. Advice lifecycles Each advice is a Spring bean.1 Reference Documentation 258 .

like any around advice. This does not need a MethodInvocation object. A simple MethodInterceptor implementation looks as follows: public class DebugInterceptor implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { System. However.out. the target join point. Before advice A simpler advice type is a before advice. a MethodInterceptor. since it will only be called before entering the method. Most interceptors will invoke this method.println("Before: invocation=[" + invocation + "]"). } The MethodInvocation argument to the invoke() method exposes the method being invoked. but in a Spring-specific way. 3. can return a different value or throw an exception rather than invoke the proceed method. Spring is compliant with the AOP Alliance interface for around advice using method interception.Spring Framework The most fundamental advice type in Spring is interception around advice. Note that pointcuts are not currently interoperable between frameworks. and the AOP Alliance does not currently define pointcut interfaces. However.println("Invocation returned"). System. The other advice types discussed in the remainder of this section implement common AOP concepts. you don't want to do this without good reason! Note MethodInterceptors offer interoperability with other AOP Alliance-compliant AOP implementations. the AOP proxy. This proceeds down the interceptor chain towards the join point.1 Reference Documentation 259 . return rval.proceed(). Object rval = invocation.out. stick with MethodInterceptor around advice if you are likely to want to run the aspect in another AOP framework. The main advantage of a before advice is that there is no need to invoke the proceed() method. and therefore no possibility of inadvertently failing to proceed down the interceptor chain. and return its return value. } } Note the call to the MethodInvocation's proceed() method. and the arguments to the method. MethodInterceptors implementing around advice should implement the following interface: public interface MethodInterceptor extends Interceptor { Object invoke(MethodInvocation invocation) throws Throwable. While there is an advantage in using the most specific advice type. The invoke() method should return the invocation's result: the return value of the join point.

although the usual objects apply to field interception and it's unlikely that Spring will ever implement it). subclassOfThrowable) Only the last argument is required. These should be in the form of: afterThrowing([Method. this will abort further execution of the interceptor chain.springframework. or on the signature of the invoked method. The exception will propagate back up the interceptor chain. } Note the return type is void. args. public interface MethodBeforeAdvice extends BeforeAdvice { void before(Method m. Throws advice Throws advice is invoked after the return of the join point if the join point threw an exception. target]. Object target) throws Throwable { ++count. depending on whether the advice method is interested in the method and arguments. which counts all method invocations: public class CountingBeforeAdvice implements MethodBeforeAdvice { private int count. Object target) throws Throwable.Spring Framework The MethodBeforeAdvice interface is shown below. Before advice can insert custom behavior before the join point executes.aop. The advice below is invoked if a RemoteException is thrown (including subclasses): 3. An example of a before advice in Spring. Object[] args. } public int getCount() { return count.1 Reference Documentation 260 . (Spring's API design would allow for field before advice. The following classes are examples of throws advice.ThrowsAdvice interface does not contain any methods: It is a tag interface identifying that the given object implements one or more typed throws advice methods. Spring offers typed throws advice. If it is unchecked. Object[] args. Note that this means that the org. The method signatures may have either one or four arguments. it will be passed directly to the client. otherwise it will be wrapped in an unchecked exception by the AOP proxy. public void before(Method m. If a before advice throws an exception. } } Tip Before advice can be used with any pointcut. but cannot change the return value.

Object target. Object[] args. Method m. However. After Returning advice An after returning advice in Spring must implement the org. Object[] args.e.aop. method arguments and target object: public class ServletThrowsAdviceWithArguments implements ThrowsAdvice { public void afterThrowing(Method m. shown below: public interface AfterReturningAdvice extends Advice { void afterReturning(Object returnValue.1 Reference Documentation 261 . if a throws-advice method throws a checked exception. ServletException ex) { // Do something with all arguments } } The final example illustrates how these two methods could be used in a single class. Object target) throws Throwable. public static class CombinedThrowsAdvice implements ThrowsAdvice { public void afterThrowing(RemoteException ex) throws Throwable { // Do something with remote exception } public void afterThrowing(Method m. The overriding exception will typically be a RuntimeException. Any number of throws advice methods can be combined in a single class. change the exception thrown to the user). this is compatible with any method signature. Object[] args.springframework. it will have to match the declared exceptions of the target method and is hence to some degree coupled to specific target method signatures.Spring Framework public class RemoteThrowsAdvice implements ThrowsAdvice { public void afterThrowing(RemoteException ex) throws Throwable { // Do something with remote exception } } The following advice is invoked if a ServletException is thrown. } 3. it declares 4 arguments. Do not throw an undeclared checked exception that is incompatible with the target method's signature! Tip Throws advice can be used with any pointcut. ServletException ex) { // Do something with all arguments } } Note: If a throws-advice method throws an exception itself. which handles both RemoteException and ServletException. Object target.AfterReturningAdvice interface. so that it has access to the invoked method. Unlike the above advice. it will override the original exception (i.

methods arguments and target. the introduction interceptor is responsible for handling the method call . Object target) throws Throwable { ++count. public void afterReturning(Object returnValue. IntroductionInfo { ClassFilter getClassFilter(). void validateInterfaces() throws IllegalArgumentException. invoked method. which has the following methods: public interface IntroductionAdvisor extends Advisor. implementing the following interface: public interface IntroductionInterceptor extends MethodInterceptor { boolean implementsInterface(Class intf). this will be thrown up the interceptor chain instead of the return value. as it applies only at class. Introduction advice Spring treats introduction advice as a special kind of interception advice. } public int getCount() { return count. and an IntroductionInterceptor. Introduction advice cannot be used with any pointcut.it cannot invoke proceed(). Introduction requires an IntroductionAdvisor. if the invoked method is on an introduced interface. } } This advice doesn't change the execution path. If it throws an exception. rather than method.1 Reference Documentation 262 . level. } 3. Method m. Tip After returning advice can be used with any pointcut. The following after returning advice counts all successful method invocations that have not thrown exceptions: public class CountingAfterReturningAdvice implements AfterReturningAdvice { private int count. Object[] args.Spring Framework An after returning advice has access to the return value (which it cannot modify). You can only use introduction advice with the IntroductionAdvisor. } The invoke() method inherited from the AOP Alliance MethodInterceptor interface must implement the introduction: that is.

we extend the org. and hence no Pointcut. but using DelegatingIntroductionInterceptor is best for most cases.support. concealing the use of interception to do so. Thus we can add an aspect that provides the ability to make objects immutable. We want to be able to cast advised objects to Lockable.aop. Only class filtering is logical. Let's suppose we want to introduce the following interface to one or more objects: public interface Lockable { void lock(). Thus in the example below. boolean locked(). The DelegatingIntroductionInterceptor is designed to delegate an introduction to an actual implementation of the introduced interface(s). However. we want all setter methods to throw a LockedException. associated with introduction advice. Firstly. the default delegate (when the no-arg constructor is used) is this. The superclass automatically picks up that Lockable can be supported for introduction. The getInterfaces() method returns the interfaces introduced by this advisor. without them having any knowledge of it: a good example of AOP. we'll need an IntroductionInterceptor that does the heavy lifting. so we don't 3. whatever their type. a DelegatingIntroductionInterceptor instance looks for all interfaces implemented by the delegate (other than IntroductionInterceptor). An introduced interface will conceal any implementation of the same interface by the target. It's possible for subclasses such as LockMixin to call the suppressInterface(Class intf) method to suppress interfaces that should not be exposed. In this case. } There is no MethodMatcher. If we call the lock() method. the IntroductionAdvisor used will control which interfaces are actually exposed.springframework. and call lock and unlock methods. the delegate is the LockMixin subclass of DelegatingIntroductionInterceptor. } This illustrates a mixin. Given a delegate (by default itself). We could implement IntroductionInterceptor directly. void unlock(). The validateInterfaces() method is used internally to see whether or not the introduced interfaces can be implemented by the configured IntroductionInterceptor .DelegatingIntroductionInterceptor convenience class.1 Reference Documentation 263 . Let's look at a simple example from the Spring test suite. and will support introductions against any of them. Thus LockMixin subclasses DelegatingIntroductionInterceptor and implements Lockable itself. The delegate can be set to any object using a constructor argument. no matter how many interfaces an IntroductionInterceptor is prepared to support.Spring Framework public interface IntroductionInfo { Class[] getInterfaces().

public class LockMixinAdvisor extends DefaultIntroductionAdvisor { public LockMixinAdvisor() { super(new LockMixin().) As usual with introductions. it is necessary: It's impossible to use an IntroductionInterceptor without an IntroductionAdvisor. } public boolean locked() { return this. A more complex example might take a reference to the introduction interceptor (which would be defined as a prototype): in this case. In the present case. using the Advised. All it needs to do is hold a distinct LockMixin instance. Note the use of the locked instance variable. return super.getMethod().locked = false. This effectively adds additional state to that held in the target object.locked = true. We could introduce any number of interfaces in this way. } } Often it isn't necessary to override the invoke() method: the DelegatingIntroductionInterceptor implementation . public void lock() { this.indexOf("set") == 0) throw new LockedException().Spring Framework need to specify that. } public Object invoke(MethodInvocation invocation) throws Throwable { if (locked() && invocation. The advisor comprises part of the advised object's state.in this case. and hence LockMixin. The introduction advisor required is simple. public class LockMixin extends DelegatingIntroductionInterceptor implements Lockable { private boolean locked.1 Reference Documentation 264 .class). the advisor must be per-instance.addAdvisor() method. We need a different instance of LockMixinAdvisor. for each advised object.is usually sufficient. so we simply create it using new. } } We can apply this advisor very simply: it requires no configuration.locked. or (the 3. as it is stateful. Lockable. and specify the introduced interfaces . We can apply this advisor programmatically. } public void unlock() { this. we need to add a check: no setter method can be invoked if in locked mode.which calls the delegate method if the method is introduced.invoke(invocation). otherwise proceeds towards the join point . just Lockable. there's no configuration relevant for a LockMixin.getName(). (However.

but an object created by the ProxyFactoryBean's implementation of the getObject() method. For 3. enabling certain approaches that are hard to achieve with other AOP frameworks.framework. enabling it to create objects of a different type. it can be used with a MethodInterceptor.ProxyFactoryBean. 9.springframework. One of the most important benefits of using a ProxyFactoryBean or another IoC-aware class to create AOP proxies.) Note The Spring 2." correctly handle introductions and stateful mixins. is that it means that advices and pointcuts can also be managed by IoC. an Advisor is an aspect that contains just a single advice object associated with a pointcut expression. For example.DefaultPointcutAdvisor is the most commonly used advisor class. This is a powerful feature. like any other advisor.1 Reference Documentation 265 . including "auto proxy creators.aop. All proxy creation choices discussed below. Basics The ProxyFactoryBean.Spring Framework recommended way) in XML configuration. 9. This gives complete control over the pointcuts and advice that will apply. org. and their ordering. there are simpler options that are preferable if you don't need such control. If you define a ProxyFactoryBean with name foo. Apart from the special case of introductions.you will want to use one of Spring's AOP FactoryBeans. However. what objects referencing foo see is not the ProxyFactoryBean instance itself. (Remember that a factory bean introduces a layer of indirection.and you should be! .5 Using the ProxyFactoryBean to create AOP proxies If you're using the Spring IoC container (an ApplicationContext or BeanFactory) for your business objects . like other Spring FactoryBean implementations.4 Advisor API in Spring In Spring. The basic way to create an AOP proxy in Spring is to use the org. BeforeAdvice or ThrowsAdvice.aop.support. any advisor can be used with any advice. For example. It is possible to mix advisor and advice types in Spring in the same AOP proxy. throws advice and before advice in one proxy configuration: Spring will automatically create the necessary interceptor chain.0 AOP support also uses factory beans under the covers. you could use a interception around advice. This method will create an AOP proxy wrapping a target object. introduces a level of indirection.springframework.

3. an advice may itself reference application objects (besides the target. a CGLIB proxy for the target class will be used (but see also the section called “JDK. interceptor or other advice names to apply. on a first come-first served basis.ProxyConfig (the superclass for all AOP proxy factories in Spring). Some key properties are inherited from org. That is to say that the first interceptor in the list will be the first to be able to intercept the invocation. • frozen: if a proxy configuration is frozen. it has no effect with JDK dynamic proxies.framework.currentProxy() method. If a target needs to obtain the proxy and the exposeProxy property is set to true. If this isn't supplied. • optimize: controls whether or not aggressive optimizations are applied to proxies created via CGLIB. which should be available in any AOP framework). You can't mention bean references here since doing so would result in the ProxyFactoryBean ignoring the singleton setting of the advice. This is useful both as a slight optimization and for those cases when you don't want callers to be able to manipulate the proxy (via the Advised interface) after the proxy has been created. One should not blithely use this setting unless one fully understands how the relevant AOP proxy handles optimization.springframework. including bean names from ancestor factories.and CGLIB-based proxies”). The default value of this property is false. Its properties are used to: • Specify the target you want to proxy. so changes such as adding additional advice are allowed. the . • interceptorNames: String array of Advisor.and CGLIB-based proxies”).aop. then changes to the configuration are no longer allowed. rather than the target class' interfaces. then CGLIB proxies will be created (but see also the section called “JDK. The names are bean names in the current factory. Ordering is significant.and CGLIB-based proxies”).Spring Framework example. Other properties specific to ProxyFactoryBean include: • proxyInterfaces: array of String interface names. • exposeProxy: determines whether or not the current proxy should be exposed in a ThreadLocal so that it can be accessed by the target. the target can use the AopContext. If this property value is set to true. benefiting from all the pluggability provided by Dependency Injection. This is currently used only for CGLIB proxies.1 Reference Documentation 266 with Spring. • Specify whether to use CGLIB (see below and also the section called “JDK. These key properties include: • proxyTargetClass: true if the target class is to be proxied. JavaBean properties In common with most FactoryBean implementations provided ProxyFactoryBean class is itself a JavaBean.

use prototype advices along with a singleton value of false.2. If the class of a target object that is to be proxied (hereafter simply referred to as the target class) doesn't implement any interfaces. 3. for stateful mixins . if the target class happens to implement a whole lot more interfaces than those specified in the proxyInterfaces property. then a JDK-based proxy will be created. that is all well and good but those additional interfaces will not be implemented by the returned proxy. If the proxyInterfaces property of the ProxyFactoryBean has been set to one or more fully qualified interface names. An example of using this feature can be found in the section called “Using 'global' advisors”. and is best removed from the bean definition because it is at best redundant. The default value is true.and CGLIB-based proxy for a particular target object (that is to be proxied). This will result in the application of all advisor beans with names starting with the part before the asterisk to be applied.and CGLIB-based proxies This section serves as the definitive documentation on how the ProxyFactoryBean chooses to create one of either a JDK.1 Reference Documentation 267 . Several FactoryBean implementations offer such a method. because JDK proxies are interface based. then a CGLIB-based proxy will be created. Note The behavior of the ProxyFactoryBean with regard to creating JDK. One simply plugs in the target bean. JDK. If the proxyTargetClass property of the ProxyFactoryBean has been set to true. This makes sense. no matter how often the getObject() method is called. the fact that the proxyTargetClass property is set to true will cause CGLIB-based proxying to be in effect. The created proxy will implement all of the interfaces that were specified in the proxyInterfaces property.0 of Spring.Spring Framework You can append an interceptor name with an asterisk (*). (Obviously this makes no sense. Note that a CGLIB-based proxy will be created even if the proxyTargetClass property of the ProxyFactoryBean has been set to false. The ProxyFactoryBean now exhibits similar semantics with regard to auto-detecting interfaces as those of the TransactionProxyFactoryBean class.or CGLIB-based proxies changed between versions 1. and at worst confusing.for example. and is in keeping with the principle of least surprise. • singleton: whether or not the factory should return a single object. and specifies the list of interceptors via the interceptorNames property. then the type of proxy that is created depends on the configuration of the ProxyFactoryBean. and no interfaces means JDK proxying isn't even possible.) If the target class implements one (or more) interfaces. Even if the proxyInterfaces property of the ProxyFactoryBean has been set to one or more fully qualified interface names. then a CGLIB-based proxy will be created. This is the easiest scenario. If you want to use stateful advice .x and 2.

Note You might be wondering why the list doesn't hold bean references. Proxying interfaces Let's look at a simple example of ProxyFactoryBean in action.mycompany.Spring Framework If the proxyInterfaces property of the ProxyFactoryBean has not been set.aop. but the target class does implement one (or more) interfaces. Advisors. The reason for this is that if the ProxyFactoryBean's singleton property is set to false. • An AOP proxy bean definition specifying the target object (the personTarget bean) and the interfaces to proxy.springframework. after returning and throws advice objects can be used.Person"/> <property name="target" ref="personTarget"/> <property name="interceptorNames"> <list> <value>myAdvisor</value> <value>debugInterceptor</value> </list> </property> </bean> Note that the interceptorNames property takes a list of String: the bean names of the interceptor or advisors in the current factory. • An Advisor and an Interceptor used to provide advice. The ordering of advisors is significant. it is significantly less work. in effect. This example involves: • A target bean that will be proxied. before. and a JDK-based proxy will be created.DebugInterceptor"> </bean> <bean id="person" class="org. However. then the ProxyFactoryBean will auto-detect the fact that the target class does actually implement at least one interface. <bean id="personTarget" class="com. and less prone to typos. this is the same as simply supplying a list of each and every interface that the target class implements to the proxyInterfaces property.MyAdvisor"> <property name="someProperty" value="Custom string property value"/> </bean> <bean id="debugInterceptor" class="org. it must be able to return 3.mycompany. interceptors.springframework.aop.1 Reference Documentation 268 . This is the "personTarget" bean definition in the example below. The interfaces that are actually proxied will be all of the interfaces that the target class implements. along with the advices to apply.ProxyFactoryBean"> <property name="proxyInterfaces" value="com.PersonImpl"> <property name="name" value="Tony"/> <property name="age" value="51"/> </bean> <bean id="myAdvisor" class="com.framework.interceptor.mycompany.

springframework.mycompany. It would be possible to cast it to the Advised interface (discussed below). so it's necessary to be able to obtain an instance of the prototype from the factory.Use inner bean. or need to avoid any ambiguity with Spring IoC autowiring.aop.1 Reference Documentation 269 .framework. As far as it's concerned. The "person" bean definition above can be used in place of a Person implementation. not local reference to target --> <property name="target"> <bean class="com.Spring Framework independent proxy instances.mycompany. Other beans in the same IoC context can express a strongly typed dependency on it. It's possible to conceal the distinction between target and proxy using an anonymous inner bean.aop.getBean("person").mycompany. an independent instance would need to be returned. There's also arguably an advantage in that the ProxyFactoryBean 3. the advice is included only for completeness: <bean id="myAdvisor" class="com.PersonImpl"> <property name="name" value="Tony"/> <property name="age" value="51"/> </bean> </property> <property name="interceptorNames"> <list> <value>myAdvisor</value> <value>debugInterceptor</value> </list> </property> </bean> This has the advantage that there's only one object of type Person: useful if we want to prevent users of the application context from obtaining a reference to the un-advised object.MyAdvisor"> <property name="someProperty" value="Custom string property value"/> </bean> <bean id="debugInterceptor" class="org. If any of the advisors is itself a prototype. Only the ProxyFactoryBean definition is different. as follows. as with an ordinary Java object: <bean id="personUser" class="com. as follows: Person person = (Person) factory.ProxyFactoryBean"> <property name="proxyInterfaces" value="com.PersonUser"> <property name="person"><ref local="person"/></property> </bean> The PersonUser class in this example would expose a property of type Person. holding a reference isn't sufficient.DebugInterceptor"/> <bean id="person" class="org.Person"/> <!-. However.mycompany. its class would be a dynamic proxy class.interceptor.springframework. the AOP proxy can be used transparently in place of a "real" person implementation.

springframework.interceptor. there was no Person interface: we needed to advise a class called Person that didn't implement any business interface.framework. Spring isn't prescriptive. will be added to the advisor chain. in certain test scenarios. Spring configures this generated subclass to delegate method calls to the original target: the subclass is used to implement the Decorator pattern.) If you want to. There's little performance difference between CGLIB proxying and dynamic proxies. CGLIB proxying works by generating a subclass of the target class at runtime. rather than dynamic proxies. Using 'global' advisors By appending an asterisk to an interceptor name.interceptor. While it's best to program to interfaces. it avoids forcing a particular approach. as they can't be overridden. dynamic proxies are slightly faster. • You'll need the CGLIB 2 binaries on your classpath.1 Reference Documentation 270 . the ability to advise classes that don't implement interfaces can be useful when working with legacy code. Proxying classes What if you need to proxy a class. there are times when being able to obtain the un-advised target from the factory might actually be an advantage: for example.Spring Framework definition is self-contained. (In general.aop. you can configure Spring to use CGLIB proxying.aop. there are some issues to consider: • Final methods can't be advised.DebugInterceptor"/> <bean id="global_performance" class="org. Performance should not be a decisive consideration in this case.0. all advisors with bean names matching the part before the asterisk. However. CGLIB proxying should generally be transparent to users. While it makes it easy to apply good practices.aop.springframework. rather than one or more interfaces? Imagine that in our example above. However. This can come in handy if you need to add a standard set of 'global' advisors: <bean id="proxy" class="org. rather than classes. However. even if you do have interfaces. As of Spring 1.ProxyFactoryBean"> <property name="target" ref="service"/> <property name="interceptorNames"> <list> <value>global*</value> </list> </property> </bean> <bean id="global_debug" class="org. you can force the use of CGLIB in any case. this may change in the future. dynamic proxies are available with the JDK. In this case. Simply set the proxyTargetClass property on the ProxyFactoryBean above to true.PerformanceMonitorInterceptor"/> 3. weaving in the advice.springframework.

readOnly</prop> <prop key="load*">PROPAGATION_REQUIRED. along with inner bean definitions.springframework. which wraps the target of the proxy as an inner bean definition. The use of parent and child bean definitions.readOnly</prop> <prop key="store*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> Note that in the example above. Then each proxy which needs to be created is just a child bean definition. the transaction propagation settings: <bean id="mySpecialService" parent="txProxyTemplate"> <property name="target"> <bean class="org. so that it may not actually ever be instantiated.springframework. Application contexts (but not simple bean factories) will by default pre-instantiate all singletons. so may actually be incomplete. since the target will never be used on its own anyway.samples. bean definition is created for the proxy: <bean id="txProxyTemplate" abstract="true" class="org.TransactionProxyFactoryBean"> <property name="transactionManager" ref="transactionManager"/> <property name="transactionAttributes"> <props> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> This will never be instantiated itself.readOnly</prop> <prop key="find*">PROPAGATION_REQUIRED.Spring Framework 9.interceptor. First a parent. It is therefore important (at least for singleton beans) that if you have a (parent) bean definition which you intend to use only as a template. as described previously.MySpecialServiceImpl"> </bean> </property> <property name="transactionAttributes"> <props> <prop key="get*">PROPAGATION_REQUIRED. and this definition specifies a class.MyServiceImpl"> </bean> </property> </bean> It is of course possible to override properties from the parent template. 3. you must make sure to set the abstract attribute to true. you may end up with many similar proxy definitions. can result in much cleaner and more concise proxy definitions. template.1 Reference Documentation 271 . <bean id="myService" parent="txProxyTemplate"> <property name="target"> <bean class="org. otherwise the application context will actually try to pre-instantiate it. such as in this case. we have explicitly marked the parent bean definition as abstract by using the abstract attribute.springframework.6 Concise proxy definitions Especially when defining transactional proxies.samples.transaction.

Spring Framework 9.1 Reference Documentation 272 . This interface includes the following methods: Advisor[] getAdvisors(). You can create this with a target object. 3. This enables you to use Spring AOP without dependency on Spring IoC.Advised interface.addAdvisor(myAdvisor). with one interceptor and one advisor.aop.getProxy(). AdvisedSupport is the superclass of both ProxyFactory and ProxyFactoryBean. void addAdvice(int pos.framework. You can add advices (with interceptors as a specialized kind of advice) and/or advisors.framework.ProxyFactory. The following listing shows creation of a proxy for a target object.springframework. 9. factory. MyBusinessInterface tb = (MyBusinessInterface) factory. and manipulate them for the life of the ProxyFactory. Any AOP proxy can be cast to this interface. void addAdvice(Advice advice) throws AopConfigException. There are also convenience methods on ProxyFactory (inherited from AdvisedSupport) which allow you to add other advice types such as before and throws advice. If you add an IntroductionInterceptionAroundAdvisor. We recommend that you externalize configuration from Java code with AOP.7 Creating AOP proxies programmatically with the ProxyFactory It's easy to create AOP proxies programmatically using Spring.addAdvice(myMethodInterceptor). factory.springframework. void addAdvisor(Advisor advisor) throws AopConfigException. The first step is to construct an object of type org. Tip Integrating AOP proxy creation with the IoC framework is best practice in most applications. Advice advice) throws AopConfigException. as in the above example. you can cause the proxy to implement additional interfaces. The interfaces implemented by the target object will automatically be proxied: ProxyFactory factory = new ProxyFactory(myBusinessInterfaceImpl).aop. you can manipulate them using the org. whichever other interfaces it implements.8 Manipulating advised objects However you create AOP proxies. as in general. or specify the interfaces to be proxied in an alternate constructor.

By default. If you added an interceptor or other advice type. in tests. boolean replaceAdvisor(Advisor a. The addAdvisor() methods can be used to add any Advisor.getAdvisors(). Note It's questionable whether it's advisable (no pun intended) to modify advice on a business object in production. The only restriction is that it's impossible to add or remove an introduction advisor. However. int oldAdvisorCount = advisors.Spring Framework void addAdvisor(int pos. // Add an advice like an interceptor without a pointcut // Will match all proxied methods // Can use for interceptors.addAdvisor(new DefaultPointcutAdvisor(mySpecialPointcut.addAdvice(new DebugInterceptor()).length). The getAdvisors() method will return an Advisor for every advisor. If you added an Advisor. boolean removeAdvisor(Advisor advisor) throws AopConfigException. the returned advisor at this index will be the object that you added. int indexOf(Advisor advisor).) A simple example of casting an AOP proxy to the Advised interface and examining and manipulating its advice: Advised advised = (Advised) myObject. void removeAdvisor(int index) throws AopConfigException. Spring will have wrapped this in an advisor with a pointcut that always returns true.out. it can be very useful in development: for example. Advisor b) throws AopConfigException. myAdvice)). (You can obtain a new proxy from the factory to avoid this problem.println(oldAdvisorCount + " advisors"). Thus if you added a MethodInterceptor. although there are no doubt legitimate usage cases. getting inside a method 3. oldAdvisorCount + 2. assertEquals("Added two advisors". boolean isFrozen(). I have sometimes found it very useful to be able to add test code in the form of an interceptor or other advice. it's possible to add or remove advisors or interceptors even once a proxy has been created. interceptor or other advice type that has been added to the factory. before. System. the advisor returned for this index will be an DefaultPointcutAdvisor returning your MethodInterceptor and a pointcut that matches all classes and methods. as existing proxies from the factory will not show the interface change. which can be used with any advice or pointcut (but not for introductions). Advisor advisor) throws AopConfigException.getAdvisors(). after returning or throws advice advised. // Add selective advice using a pointcut advised. Usually the advisor holding pointcut and advice will be the generic DefaultPointcutAdvisor. Advisor[] advisors = advised.1 Reference Documentation 273 .length. advised.

This allows you just to declare the targets eligible for autoproxying: you don't need to use ProxyFactoryBean.springframework.1 to allow aggressive optimization if runtime advice modification is known not to be required.) Depending on how you created the proxy.aop. BeanNameAutoProxyCreator The BeanNameAutoProxyCreator class is a BeanPostProcessor that automatically creates AOP proxies for beans with names matching literal values or wildcards.framework. (For example. The ability to freeze the state of an advised object is useful in some cases.BeanNameAutoProxyCreator"> <property name="beanNames" value="jdk*. the advice can get inside a transaction created for that method: for example.1 Reference Documentation 274 . 9. and any attempts to modify advice through addition or removal will result in an AopConfigException. In this model.framework. you can usually set a frozen flag.springframework.autoproxy package provides the following standard autoproxy creators. you set up some special bean definitions in your XML bean definition file to configure the auto proxy infrastructure. which enables modification of any bean definition as the container loads. There are two ways to do this: • Using an autoproxy creator that refers to specific beans in the current context.autoproxy.Spring Framework invocation I want to test. • A special case of autoproxy creation that deserves to be considered separately. This is built on Spring "bean post processor" infrastructure. to run SQL to check that a database was correctly updated. before marking the transaction for roll back. <bean class="org. which can automatically proxy selected bean definitions. It may also be used in Spring 1. in which case the Advised isFrozen() method will return true. to prevent calling code removing a security interceptor.aop. autoproxy creation driven by source-level metadata attributes. for example. Autoproxy bean definitions The org. Spring also allows us to use "autoproxy" bean definitions.9 Using the "autoproxy" facility So far we've considered explicit creation of AOP proxies using a ProxyFactoryBean or similar factory bean.onlyJdk"/> 3.

Calling getBean("businessObject1") on this ApplicationContext will return an AOP proxy. It is a popular choice for applying declarative transactions to multiple objects.1 Reference Documentation 275 . with minimal volume of configuration. to check the eligibility of each advice to candidate bean definitions. Bean definitions whose names match. This means that any number of advisors can be applied automatically to each business object. The DefaultAdvisorAutoProxyCreator will automatically evaluate the pointcut contained in each advisor. If no pointcut in any of the advisors matches any method in a business object. As with auto proxying in general. without the need to include specific bean names in the autoproxy advisor's bean definition. This is necessary because there must be a pointcut to evaluate. the pointcuts may apply differently to different beans. are plain old bean definitions with the target class. DefaultAdvisorAutoProxyCreator A more general and extremely powerful auto proxy creator is DefaultAdvisorAutoProxyCreator. The same advice will be applied to all matching beans. not just interceptors or other advices. they will automatically be proxied if necessary. to see what (if any) advice it should apply to each business object (such as "businessObject1" and "businessObject2" in the example). not the target business object. An AOP proxy will be created automatically by the BeanNameAutoProxyCreator. such as "jdkMyBean" and "onlyJdk" in the above example. • Specifying any number of Advisors in the same or related contexts. As bean definitions are added for new business objects. (The "inner bean" idiom shown earlier also offers this benefit. It offers the same merit of consistent configuration and avoidance of duplication as BeanNameAutoProxyCreator. Autoproxying in general has the advantage of making it impossible for callers or dependencies to obtain an un-advised object.) 3. Note that these must be Advisors. the main point of using BeanNameAutoProxyCreator is to apply the same configuration consistently to multiple objects. Named "interceptors" can be advisors or any advice type. the object will not be proxied.Spring Framework <property name="interceptorNames"> <list> <value>myInterceptor</value> </list> </property> </bean> As with ProxyFactoryBean. Note that if advisors are used (rather than the interceptor in the above example). This will automagically apply eligible advisors in the current context. to allow correct behavior for prototype advisors. Using this mechanism involves: • Specifying a DefaultAdvisorAutoProxyCreator bean definition. there is an interceptorNames property rather than a list of interceptors.

Once the infrastructure definitions are in place. in the unlikely event that advisor definitions offer insufficient customization to the behavior of the framework DefaultAdvisorAutoProxyCreator. AbstractAdvisorAutoProxyCreator This is the superclass of DefaultAdvisorAutoProxyCreator.BusinessObject1"> <!-.DefaultAdvisorAutoProxyCreator"/> <bean class="org.mycompany.springframework. Instead of using XML deployment descriptors as in EJB. In this case.aop. in combination with Advisors that understand metadata attributes. but deserves consideration on its own. The metadata specifics are held in the pointcut part of the candidate advisors. (The metadata-aware code is in the pointcuts contained in the advisors. The DefaultAdvisorAutoProxyCreator offers support for filtering (using a naming convention so that only certain advisors are evaluated.transaction. configuration for transaction management and other enterprise services is held in source-level attributes. The TransactionAttributeSourceAdvisor used in the above example has a configurable order value. Using metadata-driven auto-proxying A particularly important type of autoproxying is driven by metadata. AdvisorAutoProxyCreators in the same factory) and ordering. This is really a special case of the DefaultAdvisorAutoProxyCreator. you can simply add new business objects without including specific proxy configuration.with minimal change to configuration. you use the DefaultAdvisorAutoProxyCreator.1 Reference Documentation 276 .framework.core.BusinessObject2"/> The DefaultAdvisorAutoProxyCreator is very useful if you want to apply the same advice consistently to many business objects.Ordered interface to ensure correct ordering if this is an issue. tracing or performance monitoring aspects . the default setting is unordered.interceptor.) 3. allowing use of multiple.for example. differently configured. Advisors can implement the org. rather than in the autoproxy creation class itself.autoproxy.NET ServicedComponents. You can also drop in additional aspects very easily . You can create your own autoproxy creators by subclassing this class.mycompany. not the AOP framework itself.mycompany.TransactionAttributeSourceAdvisor"> <property name="transactionInterceptor" ref="transactionInterceptor"/> </bean> <bean id="customAdvisor" class="com. This produces a similar programming model to .MyAdvisor"/> <bean id="businessObject1" class="com.springframework.Spring Framework <bean class="org.Properties omitted --> </bean> <bean id="businessObject2" class="com.springframework.

the "attributes" bean satisfies this.transaction. there's no need to use the TransactionProxyFactoryBean.metadata. of type TransactionAttributeSourceAdvisor.springframework.springframework. The AttributesTransactionAttributeSource depends on an implementation of the org. because of the use of metadata-aware pointcuts. and can be used outside the JPetStore: <bean class="org.aop.autoproxy.DefaultAdvisorAutoProxyCreator"/> <bean class="org. The bean definitions include the following code. The TransactionAttributeSourceAdvisor depends on a TransactionInterceptor.springframework.AttributesTransactionAttributeSource"> <property name="attributes" ref="attributes"/> </bean> </property> </bean> <bean id="attributes" class="org.framework.framework.springframework. via constructor dependency.springframework.interceptor.aop.AnnotationTransactionAttributeSource"/> </property> </bean> 3. In this case.xml.1 Reference Documentation 277 .springframework.TransactionAttributeSourceAdvisor"> <property name="transactionInterceptor" ref="transactionInterceptor"/> </bean> <bean id="transactionInterceptor" class="org.transaction.interceptor.autoproxy.TransactionInterceptor"> <property name="transactionManager" ref="transactionManager"/> <property name="transactionAttributeSource"> <bean class="org. hence it can even be omitted) will pick up all eligible pointcuts in the current application context.Spring Framework The /attributes directory of the JPetStore sample application shows the use of attribute-driven autoproxying. In this fragment. will apply to classes or methods carrying a transaction attribute.springframework. In this case.transaction.interceptor.5+ annotations.springframework. in /WEB-INF/declarativeServices. (The application code must have been compiled using the Commons Attributes compilation task. The example resolves this via autowiring.Attributes interface.springframework.transaction.CommonsAttributes"/> The DefaultAdvisorAutoProxyCreator bean definition (the name is not significant.TransactionAttributeSourceAdvisor"> <property name="transactionInterceptor" ref="transactionInterceptor"/> </bean> <bean id="transactionInterceptor" class="org.commons.transaction.interceptor. using the Jakarta Commons Attributes API to obtain attribute information. the "transactionAdvisor" bean definition. Simply defining transactional attributes on business objects is sufficient.metadata.DefaultAdvisorAutoProxyCreator"/> <bean class="org.interceptor. The following configuration enables automatic detection of Spring's Transactional annotation.springframework. Note that this is generic.TransactionInterceptor"> <property name="transactionManager" ref="transactionManager"/> <property name="transactionAttributeSource"> <bean class="org.transaction.) The /annotation directory of the JPetStore sample application contains an analogous example for auto-proxying driven by JDK 1. leading to implicit proxies for beans containing that annotation: <bean class="org.annotation.

10 Using TargetSources 3. rather than singleton. It's possible for such advisors to be unique to each advised class (for example.transaction. This mechanism is extensible.aop. We use the generic DefaultPointcutAdvisor. If the attribute aware pointcut matches any methods in the anyBean or other bean definitions.aop. You need to: • Define your custom attribute. using these generic XML definitions will result in Spring automatically proxying all classes or methods with transaction attributes. including a pointcut that is triggered by the presence of the custom attribute on a class or method. You may be able to use an existing advice.support. the mixin will be applied. as in this example.springframework. and the programming model is similar to that of .1 Reference Documentation 278 .JtaTransactionManager"/> Tip If you require only declarative transaction management.springframework. the LockMixin introduction interceptor from the Spring test suite.jta. mixins): they simply need to be defined as prototype. as shown here. shown above. For example. bean definitions. It's possible to do autoproxying based on custom attributes.DefaultPointcutAdvisor" scope="prototype"> <property name="pointcut" ref="myAttributeAwarePointcut"/> <property name="advice" ref="lockMixin"/> </bean> <bean id="anyBean" class="anyclass" ... • Specify an Advisor with the necessary advice. could be used in conjunction with an attribute-driven pointcut to target a mixin. or Hibernate. which is not included in this generic file (although it could be) because it will be specific to the application's transaction requirements (typically JTA.springframework.Spring Framework The TransactionInterceptor defined here depends on a PlatformTransactionManager definition.LockMixin" scope="prototype"/> <bean id="lockableAdvisor" class="org. as it doesn't hold state for individual advised objects. Note that both lockMixin and lockableAdvisor definitions are prototypes. merely implementing a static pointcut that picks up the custom attribute.NET ServicedComponents. configured using JavaBean properties: <bean id="lockMixin" class="org. You won't need to work directly with AOP. 9. The myAttributeAwarePointcut pointcut can be a singleton definition. JDO or JDBC): <bean id="transactionManager" class="org.

The HotSwappableTargetSource is threadsafe.framework. Clients who hold a reference to that 3. You can change the target via the swap() method on HotSwappableTargetSource as follows: HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory. Changing the target source's target takes effect immediately. using a pool to manage instances.aop.HotSwappableTargetSource"> <constructor-arg ref="initialTarget"/> </bean> <bean id="swappable" class="org. Let's look at the standard target sources provided with Spring. a pooling TargetSource can return a different target instance for each invocation. This allows Spring to create a new target instance when required.getBean("swapper"). a default implementation is used that wraps a local object.springframework. and how you can use them. expressed in the org.aop.aop.target.1 Reference Documentation 279 .OldTarget"/> <bean id="swapper" class="org.target.Spring Framework Spring offers the concept of a TargetSource.springframework. Object oldTarget = swapper.ProxyFactoryBean"> <property name="targetSource" ref="swapper"/> </bean> The above swap() call changes the target of the swappable bean. Tip When using a custom target source. Hot swappable target sources The org. For example. hot swappable and other sophisticated targets. your target will usually need to be a prototype rather than a singleton bean definition.HotSwappableTargetSource exists to allow the target of an AOP proxy to be switched while allowing callers to keep their references to it.TargetSource interface. The same target is returned for each invocation (as you would expect).aop. The XML definitions required look as follows: <bean id="initialTarget" class="mycompany.springframework. but this provides a powerful means of supporting pooling.swap(newTarget).springframework. If you do not specify a TargetSource. The TargetSource implementation is asked for a target instance each time the AOP proxy handles a method invocation. Developers using Spring AOP don't normally need to work directly with TargetSources. This interface is responsible for returning the "target object" implementing the join point.

in which a pool of identical instances is maintained. As with Spring in general.aop. This allows the PoolingTargetSource implementation to create new instances of the target to grow the pool as necessary. properties omitted </bean> <bean id="poolTargetSource" class="org.mycompany.. Pooling target sources Using a pooling target source provides a similar programming model to stateless session EJBs.. this service can be applied in a non-invasive way.AbstractPoolingTargetSource to support any other pooling API. "myInterceptor" is the name of an interceptor that would need to be defined in the same IoC context.MyBusinessObject" scope="prototype"> . Although this example doesn't add any advice .springframework.framework. with method invocations going to free objects in the pool.aop.3. A crucial difference between Spring pooling and SLSB pooling is that Spring pooling can be applied to any POJO. and always guaranteed to be present.springframework.CommonsPoolTargetSource"> <property name="targetBeanName" value="businessObjectTarget"/> <property name="maxSize" value="25"/> </bean> <bean id="businessObject" class="org. which exposes information about the configuration and current size of the pool through an introduction.aop.target.PoolingConfig interface. Sample configuration is shown below: <bean id="businessObjectTarget" class="com.springframework. It's possible to configure Spring so as to be able to cast any pooled object to the org. don't set the interceptorNames property at all. See the javadoc for AbstractPoolingTargetSource and the concrete subclass you wish to use for information about its properties: "maxSize" is the most basic."businessObjectTarget" in the example . You'll need the commons-pool Jar on your application's classpath to use this feature. However.of course any TargetSource can be used in conjunction with arbitrary advice.aop.must be a prototype.1 Reference Documentation 280 .target.Spring Framework bean will be unaware of the change. which provides a fairly efficient pooling implementation. but will immediately start hitting the new target. You'll need to define an advisor like this: 3.springframework.and it's not necessary to add advice to use a TargetSource . In this case.ProxyFactoryBean"> <property name="targetSource" ref="poolTargetSource"/> <property name="interceptorNames" value="myInterceptor"/> </bean> Note that the target object .target. it isn't necessary to specify interceptors to use pooling. and no other advice. If you want only pooling. Spring provides out-of-the-box support for Jakarta Commons Pool 1. It's also possible to subclass org.

) <bean id="prototypeTargetSource" class="org. Inheritance is used in the TargetSource implementations to ensure consistent naming. hence the use of MethodInvokingFactoryBean.target. as most stateless objects are naturally thread safe.Spring Framework <bean id="poolConfigAdvisor" class="org. Although the cost of creating a new object isn't high in a modern JVM.factory.PrototypeTargetSource"> <property name="targetBeanName" ref="businessObjectTarget"/> </bean> There's only one property: the name of the target bean. We don't believe it should be the default choice. for clarity. Note Pooling stateless service objects is not usually necessary.1 Reference Documentation 281 . System. To do this.beans. The cast will look as follows: PoolingConfig conf = (PoolingConfig) beanFactory. Thus you shouldn't use this approach without very good reason.springframework. (I've also changed the name. Prototype target sources Setting up a "prototype" target source is similar to a pooling TargetSource.aop. The concept of a ThreadLocal provide a JDK-wide facility to transparently store 3.out.springframework. the cost of wiring up the new object (satisfying its IoC dependencies) may be more expensive. As with the pooling target source. ThreadLocal target sources ThreadLocal target sources are useful if you need an object to be created for each incoming request (per thread that is). In this case. a new instance of the target will be created on every method invocation. and instance pooling is problematic if resources are cached.getMaxSize()). the target bean must be a prototype bean definition. This advisor's name ("poolConfigAdvisor" here) must be in the list of interceptors names in the ProxyFactoryBean exposing the pooled object.config.println("Max pool size is " + conf.getBean("businessObject"). you could modify the poolTargetSource definition shown above as follows. Simpler pooling is available using autoproxying. It's possible to set the TargetSources used by any autoproxy creator.MethodInvokingFactoryBean"> <property name="targetObject" ref="poolTargetSource"/> <property name="targetMethod" value="getPoolingConfigMixin"/> </bean> This advisor is obtained by calling a convenience method on the AbstractPoolingTargetSource class.

aop.springframework. throws advice and after returning advice.aop.ThreadLocalTargetSource"> <property name="targetBeanName" value="businessObjectTarget"/> </bean> Note ThreadLocals come with serious issues (potentially resulting in memory leaks) when incorrectly using them in a multi-threaded and multi-classloader environments. Also.springframework. before.aop.framework. • The /attributes directory of the JPetStore illustrates the use of attribute-driven declarative transaction management.aopalliance. one should always remember to correctly set and unset (where the latter simply involved a call to ThreadLocal.1 Reference Documentation 282 . Spring's ThreadLocal support does this for you and should always be considered in favor of using ThreadLocals without other proper handling code. The org. Unsetting should be done in any case since not unsetting it might result in problematic behavior.target.springframework.adapter package is an SPI package allowing support for new custom advice types to be added without changing the core framework.adapter package's Javadocs for further information.framework.12 Further resources Please refer to the Spring sample applications for further examples of Spring AOP: • The JPetStore's default configuration illustrates the use of the TransactionProxyFactoryBean for declarative transaction management.set(null)) the resource local to the thread. Setting up a ThreadLocalTargetSource is pretty much the same as was explained for the other types of target source: <bean id="threadlocalTargetSource" class="org. 9. Please refer to the org.Spring Framework resource alongside a thread. One should always consider wrapping a threadlocal in some other class and never directly use the ThreadLocal itself (except of course in the wrapper class).Advice tag interface. 3. it is possible to support arbitrary advice types in addition to the out-of-the-box interception around advice.11 Defining new Advice types Spring AOP is designed to be extensible. 9. The only constraint on a custom Advice type is that it must implement the org.aop. While the interception implementation strategy is presently used internally.

mock. (A thorough treatment of testing in the enterprise is beyond the scope of this reference manual. 3. which you can use to set up a simple JNDI environment for test suites or stand-alone applications.springframework. These mock objects are generally more convenient to use than dynamic mock objects such as EasyMock or existing Servlet API mock objects such as MockObjects.mock. for example. you can test service layer objects by stubbing or mocking DAO or Repository interfaces. without Spring or any other container. you can reuse both application code and configuration in testing scenarios without modification. however.web package contains a comprehensive set of Servlet API mock objects.springframework.Spring Framework 10. If. with objects simply instantiated using the new operator.1 Introduction to Spring Testing Testing is an integral part of enterprise software development. Servlet API The org. the resulting clean layering and componentization of your codebase will facilitate easier unit testing. You can use mock objects (in conjunction with other valuable testing techniques) to test your code in isolation.1 Reference Documentation 283 . For example. which are useful for testing web contexts and controllers. This chapter focuses on the value-add of the IoC principle to unit testing and on the benefits of the Spring Framework's support for integration testing. JDBC DataSources get bound to the same JNDI names in test code as within a Java EE container.jndi package contains an implementation of the JNDI SPI. as there is no runtime infrastructure to set up. If you follow the architecture recommendations for Spring. True unit tests typically run extremely quickly. targeted at usage with Spring's Web MVC framework. without needing to access persistent data while running unit tests.) 10. Mock Objects JNDI The org. Emphasizing true unit tests as part of your development methodology will boost your productivity. Testing 10.2 Unit Testing Dependency Injection should make your code less dependent on the container than it would be with traditional Java EE development. the Spring Framework provides the following mock objects and testing support classes. You may not need this section of the testing chapter to help you write effective unit tests for your IoC-based applications. The POJOs that make up your application should be testable in JUnit or TestNG tests. For certain unit testing scenarios.

mock. MockHttpSession. 3.test. • Spring's support for annotations such as @Autowired. This will enable you to test things such as: • The correct wiring of your Spring IoC container contexts.test. and configuration methods. targeted at usage with Spring's Portlet MVC framework.springframework. for example: • ORM frameworks such as JPA and Hibernate that condone private or protected field access as opposed to public setter methods for properties in a domain entity.mock. which provides dependency injection for private or protected fields. which is a collection of reflection-based utility methods.1 Reference Documentation 284 . @Inject.3 Integration Testing Overview It is important to be able to perform some integration testing without requiring deployment to your application server or connecting to other enterprise infrastructure.portlet package contains a set of Portlet API mock objects. Developers use these methods in unit and integration testing scenarios in which they need to set a non-public field or invoke a non-public setter method when testing application code involving. Spring MVC The org.springframework. Unit Testing support Classes General utilities The org. or any other testing framework for unit tests dealing with Spring MVC ModelAndView objects.springframework.util package contains ReflectionTestUtils. which you can use in combination with JUnit.web.web package.web package contains ModelAndViewAssert. TestNG. Unit testing Spring MVC Controllers To test your Spring MVC Controllers. setter methods.Spring Framework Portlet API The org. and so on from the org. and @Resource. use ModelAndViewAssert combined with MockHttpServletRequest. 10.springframework.

AbstractDependencyInjectionSpringContextTests.test package. The TestContext framework is agnostic of the actual testing framework in use. • To supply Spring-specific base classes that assist developers in writing integration tests. In Spring 2.1.e. and so on. unit and integration testing support is provided in the form of the annotation-driven Spring TestContext Framework. This testing does not rely on an application server or other deployment environment.springframework. Similarly.1 Reference Documentation 285 . any test methods annotated with @ExpectedException should be modified to use the built-in support for expected exceptions in JUnit and TestNG..8 base class hierarchy (i. As of Spring 3.test form. which contains valuable classes for integration testing with a Spring container. The Spring Framework provides first-class support for integration testing in the spring-test module.springframework.e. The name of the actual JAR file might include the release version and might also be in the long org.8 support is deprecated As of Spring 3. Hibernate queries. the JUnit 3. Any test classes based on this code should be migrated to the JUnit 4 or TestNG support provided by the Spring TestContext Framework. Goals of Integration Testing Spring's integration testing support has the following primary goals: • To manage Spring IoC container caching between test execution. etc. the legacy JUnit 3.0. depending on where you get it from (see the section on Dependency Management for an explanation). AbstractJUnit38SpringContextTests and AbstractTransactionalJUnit38SpringContextTests) and @ExpectedException have been officially deprecated and will be removed in a later release.Spring Framework • Data access using JDBC or an ORM tool. This library includes the org.5 and later.) is officially deprecated and will be removed in a later release. AbstractTransactionalDataSourceSpringContextTests.. TestNG. JUnit 3. etc. Any test classes based on this code should be migrated to the Spring TestContext Framework. • To provide Dependency Injection of test fixture instances. thus allowing instrumentation of tests in various environments including JUnit. JPA entity mappings. This would include such things as the correctness of SQL statements. 3. Such tests are slower to run than unit tests but much faster than the equivalent Cactus tests or remote tests that rely on deployment to an application server.8 base classes in the Spring TestContext Framework (i. • To provide transaction management appropriate to integration testing.

that performs data access logic for a Title domain entity. once loaded. is everything related to the configuration of the HibernateTitleRepository bean correct and present? • The Hibernate mapping file configuration: is everything mapped correctly.). but because the objects instantiated by the Spring container take time to instantiate.Spring Framework The next few sections describe each goal and provide links to implementation and configuration details. thus avoiding the need to duplicate complex test fixture set up for individual test cases. Context management and caching The Spring TestContext Framework provides consistent loading of Spring ApplicationContexts and caching of those contexts. transactional proxies. by modifying a bean definition or the state of an application object — the TestContext framework can be configured to reload the configuration and rebuild the application context before executing the next test. for configuring Spring-managed object graphs. This provides a convenient mechanism for setting up test fixtures using preconfigured beans from your application context. As an example.xml or other deployment configuration files. etc. These locations or classes are the same as or similar to those specified in web. In the unlikely case that a test corrupts the application context and requires reloading — for example. consider the scenario where we have a class. See context management and caching with the TestContext framework. HibernateTitleRepository. because startup time can become an issue — not because of the overhead of Spring itself.g.1 Reference Documentation 286 . In this context. By default. Dependency Injection of test fixtures When the TestContext framework loads your application context. Support for the caching of loaded contexts is important. A strong benefit here is that you can reuse application contexts across various testing scenarios (e. a project with 50 to 100 Hibernate mapping files might take 10 to 20 seconds to load the mapping files. and incurring that cost before running every test in every test fixture leads to slower overall test runs that could reduce productivity. Thus the setup cost is incurred only once (per test suite).. For example. We want to write integration tests that test the following areas: • The Spring configuration: basically. and are the correct lazy-loading settings in place? 3. it can optionally configure instances of your test classes via Dependency Injection. DataSources. the term test suite means all tests run in the same JVM — for example. all tests run from an Ant or Maven build for a given project or module. and subsequent test execution is much faster. the configured ApplicationContext is reused for each test. Test classes can provide either an array containing the resource locations of XML configuration metadata — typically in the classpath — or an array containing @Configuration classes that is used to configure the application.

In addition. Support classes for integration testing The Spring TestContext Framework provides several abstract support classes that simplify the writing of integration tests. changes to the state may affect future tests. When used in conjunction with an ORM tool.Spring Framework • The logic of the HibernateTitleRepository: does the configured instance of this class perform as anticipated? See dependency injection of test fixtures with the TestContext framework. In addition. • A SimpleJdbcTemplate.1 Reference Documentation 287 . which enable you to access: • The ApplicationContext. for executing SQL statements to query the database. and the database will return to its state prior to execution of the test. The TestContext framework addresses this issue. If you call transactionally proxied objects in your tests. for performing explicit bean lookups or testing the state of the context as a whole. be sure to avoid false positives. By default. application-wide superclass with instance variables and methods specific to your project. but occasionally useful when you want a particular test to populate or modify the database — the TestContext framework can be instructed to cause the transaction to commit instead of roll back via the @TransactionConfiguration and @Rollback annotations. 3. the transaction will roll back by default. you may want to create your own custom. and Spring ensures that such queries run in the scope of the same transaction as the application code. the framework will create and roll back a transaction for each test. they will behave correctly. many operations — such as inserting or modifying persistent data — cannot be performed (or verified) outside a transaction. If you want a transaction to commit — unusual. according to their configured transactional semantics. Even when you're using a development database. These base test classes provide well-defined hooks into the testing framework as well as convenient instance variables and methods. See support classes for the TestContext framework. if test methods delete the contents of selected tables while running within a transaction. You simply write code that can assume the existence of a transaction. Also. Such queries can be used to confirm database state both prior to and after execution of database-related application code. Transaction management One common issue in tests that access a real database is their affect on the state of the persistence store. Transactional support is provided to your test class via a PlatformTransactionManager bean defined in the test's application context. See transaction management with the TestContext framework.

class) public class XmlApplicationContextTests { // class body.xml". } @ContextConfiguration(classes=MyConfig.. @ContextConfiguration declares either the application context resource locations or the @Configuration classes (but not both) to load as well as the ContextLoader strategy to use for loading the context. } Note @ContextConfiguration provides support for inheriting resource locations or configuration classes declared by superclasses by default.test. and so on. @ContextConfiguration(locations="example/test-context. Refer to the respective Javadoc for further information.class) public class ConfigClassApplicationContextTests { // class body. • @ContextConfiguration Defines class-level metadata that is used to determine how to load and configure an ApplicationContext for test classes. which is a collection of JDBC related utility functions intended to simplify standard database testing scenarios... • @ActiveProfiles A class-level annotation that is used to declare which bean definition profiles should be active when loading an ApplicationContext for test classes. attribute aliases. however. Specifically.. loader=CustomContextLoader. Annotations Spring Testing Annotations The Spring Framework provides the following set of Spring-specific annotations that you can use in your unit and integration tests in conjunction with the TestContext framework. that you typically do not need to explicitly configure the loader since the default loader supports either resource locations or configuration classes. See Context management and caching and Javadoc for examples and further details.Spring Framework JDBC Testing Support The org.jdbc package contains SimpleJdbcTestUtils. Note that AbstractTransactionalJUnit4SpringContextTests and AbstractTransactionalTestNGSpringContextTests provide convenience methods which delegate to SimpleJdbcTestUtils internally.1 Reference Documentation 288 .springframework. 3. including default attribute values. Note.

.e. the ApplicationContext is marked as dirty after any such annotated method as well as after the entire class. In such scenarios. the context is marked dirty after each test method in the class.1 Reference Documentation 289 . If the ClassMode is set to AFTER_EACH_TEST_METHOD. by replacing a bean definition).. • After each test method in the current test class. Use this annotation if a test has modified the context (for example. when declared on a method. @DirtiesContext is supported in the following scenarios: • After the current test class. "integration"}) public class DeveloperIntegrationTests { // class body.. modified or corrupted in some manner) during the execution of a test and should be closed. @DirtiesContext public class ContextDirtyingTests { // some tests that result in the Spring container being dirtied } @DirtiesContext(classMode = ClassMode. • After the current test. regardless of whether the test passed. which is the default class mode..5+ or TestNG you can use @DirtiesContext as both a class-level and method-level annotation within the same test class. when declared on a class with class mode set to AFTER_EACH_TEST_METHOD. when declared on a class with class mode set to AFTER_CLASS. } @ContextConfiguration @ActiveProfiles({"dev". See Context configuration with environment profiles and the Javadoc for @ActiveProfiles for examples and further details. Subsequent tests are supplied a new context. With JUnit 4. • @DirtiesContext Indicates that the underlying Spring ApplicationContext has been dirtied (i.AFTER_EACH_TEST_METHOD) public class ContextDirtyingTests { // some tests that result in the Spring container being dirtied 3.. } Note @ActiveProfiles provides support for inheriting active bean definition profiles declared by superclasses classes by default.Spring Framework @ContextConfiguration @ActiveProfiles("dev") public class DeveloperTests { // class body.

} Note If the default conventions are sufficient for your test configuration.1 Reference Documentation 290 . Specifically. 3.Spring Framework } @DirtiesContext @Test public void testProcessWhichDirtiesAppCtx() { // some logic that results in the Spring container being dirtied } When an application context is marked dirty.. defaultRollback=false) public class CustomConfiguredTransactionalTests { // class body. thus the underlying Spring container is rebuilt for any subsequent test that requires a context with the same set of resource locations. • @TestExecutionListeners Defines class-level metadata for configuring which TestExecutionListeners should be registered with the TestContextManager. } @TestExecutionListeners supports inherited listeners by default. @TransactionConfiguration is used in conjunction with @ContextConfiguration.class}) public class CustomTestExecutionListenerTests { // class body. the bean name of the PlatformTransactionManager that is to be used to drive transactions can be explicitly configured if the bean name of the desired PlatformTransactionManager is not "transactionManager".. In addition. @TestExecutionListeners is used in conjunction with @ContextConfiguration. you can change the defaultRollback flag to false... @ContextConfiguration @TransactionConfiguration(transactionManager="txMgr". In other words. @ContextConfiguration @TestExecutionListeners({CustomTestExecutionListener. See the Javadoc for an example and further details. you can avoid using @TransactionConfiguration altogether. if your transaction manager bean is named "transactionManager" and if you want transactions to roll back automatically. there is no need to annotate your test class with @TransactionConfiguration. Typically. AnotherTestExecutionListener. Typically.class. it is removed from the testing framework's cache and closed. • @TransactionConfiguration Defines class-level metadata for configuring transactional tests.

the transaction is committed. @BeforeTransaction public void beforeTransaction() { // logic to be executed before a transaction is started } • @AfterTransaction Indicates that the annotated public void method should be executed after a transaction has ended for test methods configured to run within a transaction via the @Transactional annotation. } • @BeforeTransaction Indicates that the annotated public void method should be executed before a transaction is started for test methods configured to run within a transaction via the @Transactional annotation. @NotTransactional @Test public void testProcessWithoutTransaction() { // ..Spring Framework • @Rollback Indicates whether the transaction for the annotated test method should be rolled back after the test method has completed.. Use @Rollback to override the default rollback flag configured at the class level. doing so allows a mix of transactional and non-transactional methods in the same test class without the need for using 3.0. consider annotating individual methods with @Transactional. As an alternative to annotating an entire class with @Transactional. @AfterTransaction public void afterTransaction() { // logic to be executed after a transaction has ended } • @NotTransactional The presence of this annotation indicates that the annotated test method must not execute in a transactional context. @NotTransactional is deprecated in favor of moving the non-transactional test method to a separate (non-transactional) test class or to a @BeforeTransaction or @AfterTransaction method. } @NotTransactional is deprecated As of Spring 3. @Rollback(false) @Test public void testProcessWithoutRollback() { // ..1 Reference Documentation 291 .. the transaction is rolled back. If true. otherwise.

the test is enabled.persistence) if JPA is present • @PersistenceUnit (javax. If the configured ProfileValueSource returns a matching value for the provided name. @IfProfileValue(name="java. • @IfProfileValue Indicates that the annotated test is enabled for a specific testing environment.annotation) if JSR-250 is present • @Inject (javax. Standard Annotation Support The following annotations are supported with standard semantics for all configurations of the Spring TestContext Framework.Spring Framework @NotTransactional. Class-level usage overrides method-level usage.persistence) if JPA is present • @Required • @Transactional Spring JUnit Testing Annotations The following annotations are only supported SpringJUnit4ClassRunner or the JUnit support classes. you can configure @IfProfileValue with a list of values (with OR semantics) to achieve TestNG-like support for test groups in a JUnit environment.vendor". • @Autowired • @Qualifier • @Resource (javax.inject) if JSR-330 is present • @PersistenceContext (javax. value="Sun Microsystems Inc.1 Reference Documentation 292 . Note that these annotations are not specific to tests and can be used anywhere in the Spring Framework. Consider the following example: 3.inject) if JSR-330 is present • @Named (javax.") @Test public void testProcessWhichRunsOnlyOnSunJvm() { // some logic that should run only on Java VMs from Sun Microsystems } when used in conjunction with the Alternatively. This annotation can be applied to an entire class or to individual methods.

class) public class CustomProfileValueSourceTests { // class body. } • @Timed Indicates that the annotated test method must finish execution in a specified time period (in milliseconds). @ProfileValueSourceConfiguration(CustomProfileValueSource.. The scope of execution to be repeated includes execution of the test method itself as well as any set up or tear down of the test fixture.1 Reference Documentation 293 .Spring Framework @IfProfileValue(name="test-groups".) support.. The time period includes execution of the test method itself. The number of times that the test method is to be executed is specified in the annotation.. } 3. @Test(timeout=. by executing the test method in a separate Thread). Specifically. SystemProfileValueSource is used by default. • @Repeat Indicates that the annotated test method must be executed repeatedly. values={"unit-tests". as well as any set up or tear down of the test fixture.. on the other hand.. Spring's @Timed. "integration-tests"}) @Test public void testProcessWhichRunsForUnitOrIntegrationTestGroups() { // some logic that should run only for unit and integration test groups } • @ProfileValueSourceConfiguration Class-level annotation that specifies what type of ProfileValueSource to use when retrieving profile values configured through the @IfProfileValue annotation. due to the manner in which JUnit handles test execution timeouts (that is.) applies to each iteration in the case of repetitions and preemptively fails the test if the test takes too long. the test fails. any repetitions of the test (see @Repeat). @Repeat(10) @Test public void testProcessRepeatedly() { // .... times the total test execution time (including all repetitions) and does not preemptively fail the test but rather waits for the test to complete before failing. If the text execution time exceeds the specified time period. @Timed(millis=1000) public void testProcessWithOneSecondTimeout() { // some logic that should not take longer than 1 second to execute } Spring's @Timed annotation has different semantics than JUnit's @Test(timeout=. If @ProfileValueSourceConfiguration is not declared for a test.

whether JUnit or TestNG. If you are only interested in using the framework and not necessarily interested in extending it with your own custom listeners or custom loaders. The TestContext framework also places a great deal of importance on convention over configuration with reasonable defaults that can be overridden through annotation-based configuration.Spring Framework Spring TestContext Framework The Spring TestContext Framework (located in the org..springframework. In addition to generic testing infrastructure. which instrument the actual test execution by providing dependency injection. agnostic of the actual testing framework in use. The following section provides an overview of the internals of the TestContext framework. transaction management). for the execution of a single test method in JUnit).test. Key abstractions The core of the framework consists of the TestContext and TestContextManager classes and the TestExecutionListener. which manages a single TestContext and signals events to all registered TestExecutionListeners at well-defined test execution points: • prior to any before class methods of a particular testing framework • test instance preparation • prior to any before methods of a particular testing framework 3. and provides context management and caching support for the test instance for which it is responsible. The TestContext also delegates to a ContextLoader (or SmartContextLoader) to load an ApplicationContext if requested. support classes. managing transactions. ContextLoader. and SmartContextLoader interfaces. A ContextLoader (or SmartContextLoader) is responsible for loading an ApplicationContext for a given test class.g. Spring also provides a custom JUnit Runner that allows one to write so called POJO test classes. POJO test classes are not required to extend a particular class hierarchy. For JUnit. and so on.context package) provides generic. The TestContextManager in turn manages a TestContext that holds the context of the current test. the TestContext framework provides explicit support for JUnit and TestNG in the form of abstract support classes.1 Reference Documentation 294 . annotation-driven unit and integration testing support that is agnostic of the testing framework in use. • TestContext: Encapsulates the context in which a test is executed. feel free to go directly to the configuration (context management. • TestContextManager: The main entry point into the Spring TestContext Framework. Consult the Javadoc and the Spring test suite for further information and examples of various implementations. and annotation support sections. dependency injection. A TestContextManager is created on a per-test basis (e. The TestContextManager also updates the state of the TestContext as the test progresses and delegates to TestExecutionListeners.

• SmartContextLoader: Extension of the ContextLoader interface introduced in Spring 3. • AnnotationConfigContextLoader: loads an application context from @Configuration classes. Specifically.1. an As of Spring 3. a SmartContextLoader can choose to process either resource locations or configuration classes.5. The following sections explain how to configure the TestContext framework through annotations and provide working examples of how to write unit and integration tests with the framework. Spring provides three TestExecutionListener implementations that are configured by default: DependencyInjectionTestExecutionListener. DirtiesContextTestExecutionListener.5 for loading ApplicationContext for an integration test managed by the Spring TestContext Framework. and transactional test execution with default rollback semantics. they support dependency injection of the test instance. implement SmartContextLoader instead of this interface in order to provide support for configuration classes and active bean definition profiles.1. Furthermore. Respectively. a SmartContextLoader can set active bean definition profiles in the context that it loads. and TransactionalTestExecutionListener. • ContextLoader: Strategy interface introduced in Spring 2. • GenericXmlContextLoader: loads an application context from XML resource locations. handling of the @DirtiesContext annotation.Spring Framework • after any after methods of a particular testing framework • after any after class methods of a particular testing framework • TestExecutionListener: Defines a listener API for reacting to test execution events published by the TestContextManager with which the listener is registered. • GenericPropertiesContextLoader: loads an application context from Java Properties files.1 Reference Documentation 295 . Spring provides the following out-of-the-box implementations: • DelegatingSmartContextLoader: the default loader which delegates internally to an AnnotationConfigContextLoader or a GenericXmlContextLoader depending either on the configuration declared for the test class or on the presence of default locations or default configuration classes. Context management 3. The SmartContextLoader SPI supersedes the ContextLoader SPI that was introduced in Spring 2.

class) @ContextConfiguration public class MyTest { @Autowired private ApplicationContext applicationContext. The following sections explain how to configure an ApplicationContext via XML configuration files or @Configuration classes using Spring's @ContextConfiguration annotation.xml" — will be treated as a classpath resource that is relative to the package in which the test class is defined. a path prefixed with classpath:. Test classes that use the TestContext framework do not need to extend any particular class or implement a specific interface to configure their application context. you can inject the application context for your test class through the @Autowired annotation on either a field or setter method. Note that AbstractJUnit4SpringContextTests and AbstractTestNGSpringContextTests implement ApplicationContextAware and therefore provide access to the ApplicationContext out-of-the-box. a reference to the ApplicationContext is supplied to the test instance. // class body. @Autowired ApplicationContext As an alternative to implementing the ApplicationContextAware interface... Alternatively. configuration is achieved simply by declaring the @ContextConfiguration annotation at the class level. For example: @RunWith(SpringJUnit4ClassRunner.1 Reference Documentation 296 . the configured ContextLoader determines how to load a context from a default location or default configuration classes. http:.. } Dependency injection via @Autowired is provided by the DependencyInjectionTestExecutionListener which is configured by default (see the section called “Dependency injection of test fixtures”). A path starting with a slash is treated as an absolute classpath location. Instead. Test instances do not automatically receive access to the configured ApplicationContext. However.Spring Framework Each TestContext provides context management and caching support for the test instance it is responsible for. you can implement and configure 3. A path which represents a resource URL (i.) will be used as is. if a test class implements the ApplicationContextAware interface.xml". annotate your test class with @ContextConfiguration and configure the locations attribute with an array that contains the resource locations of XML configuration metadata. for example "/org/example/config.e. A plain path — for example "context. file:. Context configuration with XML resources To load an ApplicationContext for your tests using XML configuration files. If your test class does not explicitly declare application context resource locations or configuration classes. etc.

Spring Framework your own custom ContextLoader or SmartContextLoader for advanced use cases.example. "/test-config. } If you omit both the locations and value attributes from the @ContextConfiguration annotation.example. you can omit the declaration of the locations attribute name and declare the resource locations by using the shorthand format demonstrated in the following example.xml" and // "/test-config.xml" @ContextConfiguration public class MyTest { // class body.class}) public class MyTest { // class body. Specifically. @RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be loaded from AppConfig and TestConfig @ContextConfiguration(classes={AppConfig.xml"}) public class MyTest { // class body. } Context configuration with @Configuration classes To load an ApplicationContext for your tests using @Configuration classes (see Section 4.class) @ContextConfiguration({"/app-config.class) // ApplicationContext will be loaded from "classpath:/com/example/MyTest-context.. TestConfig. } If you omit the classes attribute from the @ContextConfiguration annotation. Thus.. Specifically.class) // ApplicationContext will be loaded from "/app-config..1 Reference Documentation 297 . If your class is named com.. AnnotationConfigContextLoader will detect all static inner classes of the annotated test class 3..xml".. package com. @RunWith(SpringJUnit4ClassRunner.xml"}) public class MyTest { // class body.. "/test-config. GenericXmlContextLoader detects a default location based on the name of the test class. annotate your test class with @ContextConfiguration and configure the classes attribute with an array that contains references to configuration classes. } @ContextConfiguration supports an alias for the locations attribute through the standard Java value attribute. GenericXmlContextLoader loads your application context from "classpath:/com/example/MyTest-context.MyTest.xml".12. the TestContext framework will attempt to detect a default XML resource location.xml" in the root of the classpath @ContextConfiguration(locations={"/app-config. “Java-based container configuration”). Alternatively.. you can implement and configure your own custom ContextLoader or SmartContextLoader for advanced use cases. the TestContext framework will attempt to detect the presence of default configuration classes.xml".class. @RunWith(SpringJUnit4ClassRunner. if you do not need to configure a custom ContextLoader. @RunWith(SpringJUnit4ClassRunner.

class) // ApplicationContext will be loaded from the static inner Config class @ContextConfiguration public class OrderServiceTest { @Configuration static class Config { // this bean will be injected into the OrderServiceTest class @Bean public OrderService orderService() { OrderService orderService = new OrderServiceImpl().Spring Framework that meet the requirements for configuration class implementations as specified in the Javadoc for @Configuration. but you still have the freedom to include or import the other type of configuration. If you want to use XML and @Configuration classes to configure your tests. } } @Autowired private OrderService orderService. a test class can contain more than one static inner configuration class if desired. in a @Configuration class you can use @ImportResource to import XML configuration files. you may decide that you want to use @Configuration classes to configure specific Spring-managed components for your tests. whereas. Note that the name of the configuration class is arbitrary. For example. As mentioned in the section called “Spring Testing Annotations” the TestContext framework does not allow you to declare both via @ContextConfiguration.1 Reference Documentation 298 . or vice versa. but this does not mean that you cannot use both. // set properties. return orderService. In addition. you will have to pick one as the entry point. Context configuration inheritance 3.example. and that one will have to include or import the other. package com. In the following example. For example. in XML you can include @Configuration classes via component scanning or define them as normal Spring beans in XML. @Test public void testOrderService() { // test the orderService } } Mixing XML resources and @Configuration classes It may sometimes be desirable to mix XML resources and @Configuration classes to configure an ApplicationContext for your tests. etc. Note that this behavior is semantically equivalent to how you configure your application in production: in production configuration you will define either a set of XML resource locations or a set of @Configuration classes that your production ApplicationContext will be loaded from. if you use XML configuration in production. @RunWith(SpringJUnit4ClassRunner. the OrderServiceTest class declares a static inner configuration class named Config that will be automatically used to load the ApplicationContext for the test class.

xml". This is achieved by annotating a test class with the new 3. Beans defined in ExtendedConfig may therefore override (i..class) // ApplicationContext will be loaded from "/base-config.xml".. the ApplicationContext for ExtendedTest will be loaded from "base-config. } Context configuration with environment profiles Spring 3.. subclasses have the option of extending the list of resource locations or configuration classes.xml" in the root of the classpath @ContextConfiguration("/base-config.xml" // in the root of the classpath @ContextConfiguration("/extended-config.xml") public class ExtendedTest extends BaseTest { // class body.k.xml" and "/extended-config. and integration tests can now be configured to activate particular bean definition profiles for various testing scenarios.1 introduces first-class support in the framework for the notion of environments and profiles (a. @RunWith(SpringJUnit4ClassRunner..class) public class BaseTest { // class body.1 Reference Documentation 299 .xml" may therefore override (i. If @ContextConfiguration's inheritLocations attribute is set to false.. } // ApplicationContext will be loaded from "/base-config. replace) those defined in "base-config. } Similarly.class) public class ExtendedTest extends BaseTest { // class body. in that order. This means that an annotated class inherits the resource locations or configuration classes declared by any annotated superclasses. Beans defined in "extended-config.e.xml" and "extended-config. bean definition profiles)... the resource locations or configuration classes for an annotated test class are appended to the list of resource locations or configuration classes declared by annotated superclasses.. in that order. The default value is true. Specifically.. replace) those defined in BaseConfig.class) // ApplicationContext will be loaded from BaseConfig @ContextConfiguration(classes=BaseConfig. the ApplicationContext for ExtendedTest will be loaded from the BaseConfig and ExtendedConfig configuration classes. In the following example that uses XML resource locations.e.a. the resource locations or configuration classes for the annotated class shadow and effectively replace any resource locations or configuration classes defined by superclasses...Spring Framework @ContextConfiguration supports a boolean inheritLocations attribute that denotes whether resource locations or configuration classes declared by superclasses should be inherited.xml") public class BaseTest { // class body. Thus. in the following example that uses configuration classes. } // ApplicationContext will be loaded from BaseConfig and ExtendedConfig @ContextConfiguration(classes=ExtendedConfig. @RunWith(SpringJUnit4ClassRunner.

. @Test public void testTransferService() { // test the transferService 3.springframework.Spring Framework @ActiveProfiles annotation and supplying a list of profiles that should be activated when loading the ApplicationContext for the test.repository.org/schema/jdbc" xmlns:jee="http://www.ZeroFeePolicy"/> <beans profile="dev"> <jdbc:embedded-database id="dataSource"> <jdbc:script location="classpath:com/bank/config/sql/schema. Note @ActiveProfiles may be used with any implementation of the SmartContextLoader SPI.class) // ApplicationContext will be loaded from "classpath:/app-config.DefaultTransferService"> <constructor-arg ref="accountRepository"/> <constructor-arg ref="feePolicy"/> </bean> <bean id="accountRepository" class="com.bank.internal.bank.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.org/schema/jee" xsi:schemaLocation=".bank.. Let's take a look at some examples with XML configuration and @Configuration classes.org/schema/beans" xmlns:xsi="http://www.sql"/> <jdbc:script location="classpath:com/bank/config/sql/test-data.internal. <!-.w3. but @ActiveProfiles is not supported implementations of the older ContextLoader SPI.service.1 Reference Documentation 300 .xml") @ActiveProfiles("dev") public class TransferServiceTest { @Autowired private TransferService transferService.xml --> <beans xmlns="http://www.JdbcAccountRepository"> <constructor-arg ref="dataSource"/> </bean> <bean id="feePolicy" class="com. @RunWith(SpringJUnit4ClassRunner.internal.springframework.service.springframework.app-config."> <bean id="transferService" class="com.bank.xml" @ContextConfiguration("/app-config.sql"/> </jdbc:embedded-database> </beans> <beans profile="production"> <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/> </beans> </beans> new with package com.service.

lookup("java:comp/env/jdbc/datasource"). @Configuration @Profile("dev") public class StandaloneDataConfig { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() . } @Bean public AccountRepository accountRepository() { return new JdbcAccountRepository(dataSource). The following code listings demonstrate how to implement the same configuration and integration test but using @Configuration classes instead of XML.sql") .xml you'll notice that the accountRepository bean has a dependency on a dataSource bean.addScript("classpath:com/bank/config/sql/schema.build(). dataSource is not defined as a top-level bean. feePolicy()).sql") . dataSource is defined twice: once in the production profile and once in the dev profile. If you inspect app-config. By annotating TransferServiceTest with @ActiveProfiles("dev") we instruct the Spring TestContext Framework to load the ApplicationContext with the active profiles set to {"dev"}.addScript("classpath:com/bank/config/sql/test-data.Spring Framework } } When TransferServiceTest is run. As a result. and the accountRepository bean will be wired with a reference to the development DataSource. an embedded database will be created. } } @Configuration @Profile("production") public class JndiDataConfig { @Bean public DataSource dataSource() throws Exception { Context ctx = new InitialContext(). @Bean public TransferService transferService() { return new DefaultTransferService(accountRepository().1 Reference Documentation 301 . } } @Configuration public class TransferServiceConfig { @Autowired DataSource dataSource. And that's likely what we want in an integration test.HSQL) . Instead.xml configuration file in the root of the classpath. } @Bean 3.setType(EmbeddedDatabaseType. however. its ApplicationContext will be loaded from the app-config. return (DataSource) ctx.

we still annotate TransferServiceTest with @ActiveProfiles("dev").class}) @ActiveProfiles("dev") public class TransferServiceTest { @Autowired private TransferService transferService.class) @ContextConfiguration( classes={ TransferServiceConfig. but this time we specify all three configuration classes via the @ContextConfiguration annotation.class. The TestContext framework uses the following configuration parameters to build the context cache key: 3.1 Reference Documentation 302 . The body of the test class itself remains completely unchanged. An ApplicationContext can be uniquely identified by the combination of configuration parameters that are used to load it.class. @Test public void testTransferService() { // test the transferService } } In this variation.service. the unique combination of configuration parameters are used to generate a key under which the context is cached. @RunWith(SpringJUnit4ClassRunner. JndiDataConfig.bank. To understand how caching works.Spring Framework public FeePolicy feePolicy() { return new ZeroFeePolicy(). it is important to understand what is meant by unique and test suite. } } package com. we have split the XML configuration into three independent @Configuration classes: • TransferServiceConfig: @Autowired acquires a dataSource via dependency injection using • StandaloneDataConfig: defines a dataSource for an embedded database suitable for developer tests • JndiDataConfig: defines a dataSource that is retrieved from JNDI in a production environment As with the XML-based configuration example. Context caching Once the TestContext framework loads an ApplicationContext for a test. Consequently. StandaloneDataConfig. that context will be cached and reused for all subsequent tests that declare the same unique context configuration within the same test suite.

or 3. if the forkMode for the Maven Surefire plug-in is set to always or pertest. and this will effectively disable the caching mechanism.xml"} for the locations (or value) attribute of @ContextConfiguration. "test-config. field injection. You may use setter injection. So if TestClassB also defines {"app-config. For example. This can be achieved by executing all tests as a group within an IDE. by modifying a bean definition or the state of an application object — you can annotate your test class or test method with @DirtiesContext (see the discussion of @DirtiesContext in the section called “Spring Testing Annotations”).xml".Spring Framework • locations (from @ContextConfiguration) • classes (from @ContextConfiguration) • contextLoader (from @ContextConfiguration) • activeProfiles (from @ActiveProfiles) For example. This means that the setup cost for loading an application context is incurred only once (per test suite). This means that the context is literally stored in a static variable. Note that support for the @DirtiesContext annotation is provided by the DirtiesContextTestExecutionListener which is enabled by default. if TestClassA specifies {"app-config.1 Reference Documentation 303 . and subsequent test execution is much faster. To benefit from the caching mechanism. if tests execute in separate processes the static cache will be cleared between each test execution. Dependency injection of test fixtures When you use the DependencyInjectionTestExecutionListener — which is configured by default — the dependencies of your test instances are injected from beans in the application context that you configured with @ContextConfiguration. Test suites and forked processes The Spring TestContext framework stores application contexts in a static cache. Similarly. then the same ApplicationContext will be shared by both test classes. "test-config. This instructs Spring to remove the context from the cache and rebuild the application context before executing the next test. the TestContext framework will not be able to cache application contexts between test classes and the build process will run significantly slower as a result. the TestContext framework will load the corresponding ApplicationContext and store it in a static context cache under a key that is based solely on those locations.xml"} for its locations (either explicitly or implicitly through inheritance) and does not define a different ContextLoader or different active profiles. when executing tests with a build framework such as Ant or Maven it is important to make sure that the build framework does not fork between tests. all tests must run within the same process or test suite. In the unlikely case that a test corrupts the application context and requires reloading — for example. In other words.xml".

if your test class has access to its ApplicationContext. For consistency with the annotation support introduced in Spring 2.class) // specifies the Spring configuration to load for this test fixture @ContextConfiguration("repository-config. Tip The TestContext framework does not instrument the manner in which a test instance is instantiated. you can perform an explicit lookup by using (for example) a call to applicationContext. If you do not want dependency injection applied to your test instances. simply do not annotate fields or setter methods with @Autowired or @Inject.5 and 3. In that case.0 you may also choose to use @Inject in conjunction with @Named. @RunWith(SpringJUnit4ClassRunner. depending on which annotations you choose and whether you place them on setter methods or fields. you can disable dependency injection altogether by explicitly configuring your class with @TestExecutionListeners and omitting DependencyInjectionTestExecutionListener. The same DI techniques can be used in conjunction with any testing framework. Alternatively. you can use Spring's @Autowired annotation or the @Inject annotation from JSR 300. In such cases.0. The next two code listings demonstrate the use of @Autowired on fields and setter methods. as outlined in the Goals section. you cannot rely on this approach for those particular beans. The following examples make calls to static assertion methods such as assertNotNull() but without prepending the call with Assert.xml") public class HibernateTitleRepositoryTests { // this instance will be dependency injected by type @Autowired private HibernateTitleRepository titleRepository.1 Reference Documentation 304 . Consider the scenario of testing a HibernateTitleRepository class. Alternatively.Spring Framework both. Thus the use of @Autowired or @Inject for constructors has no effect for test classes. Note The dependency injection behavior in the following code listings is not specific to JUnit. you can use @Autowired in conjunction with @Qualifier. The application context configuration is presented after all sample code listings. Because @Autowired is used to perform autowiring by type. if you have multiple bean definitions of the same type. assume that the method was properly imported through an import static declaration that is not shown in the example. As of Spring 3. The first code listing shows a JUnit-based implementation of the test class that uses @Autowired for field injection.class from the list of listeners. @Test 3.getBean("titleRepository").

@RunWith(SpringJUnit4ClassRunner.titleRepository = titleRepository.this bean will be injected into the HibernateTitleRepositoryTests class --> <bean id="titleRepository" class="com.configuration elided for brevity --> </bean> </beans> Note If you are extending from a Spring-provided test base class that happens to use @Autowired on one of its setter methods. @Autowired public void setTitleRepository(HibernateTitleRepository titleRepository) { this.org/schema/beans http://www.findById(new Long(10)). multiple DataSource beans.springframework.hibernate.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.0.class) // specifies the Spring configuration to load for this test fixture @ContextConfiguration("repository-config. which looks like this: <?xml version="1. } } Alternatively.hibernate3. you can override the setter method and use the @Qualifier annotation to indicate a specific target bean as follows. } } The preceding code listings use the same XML context file referenced by the @ContextConfiguration annotation (that is. assertNotNull(title).springframework. In such a case.0" encoding="UTF-8"?> <beans xmlns="http://www. but make sure to delegate to the overridden method in the superclass as well.springframework.orm. repository-config.xml). } @Test public void findById() { Title title = titleRepository.springframework.foo.HibernateTitleRepository"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="sessionFactory" class="org. you can configure the class to use @Autowired for setter injection as seen below.xml") public class HibernateTitleRepositoryTests { // this instance will be dependency injected by type private HibernateTitleRepository titleRepository.LocalSessionFactoryBean"> <!-. 3.findById(new Long(10)).org/schema/beans/spring-beans-3.Spring Framework public void findById() { Title title = titleRepository. assertNotNull(title).1 Reference Documentation 305 . you might have multiple beans of the affected type defined in your application context: for example.repository.xsd"> <!-.org/schema/beans" xmlns:xsi="http://www.w3.

For class-level transaction configuration (i. setting the bean name for the transaction manager and the default rollback flag).. see the @TransactionConfiguration entry in the annotation support section.. To enable support for transactions. transactions are managed by the TransactionalTestExecutionListener. so you may effectively also point to a specific bean by name there (as shown above. The specified qualifier value indicates the specific DataSource bean to inject.1 Reference Documentation 306 . Occasionally you need to execute certain code before or after a transactional test method but outside the transactional context. you can use the @Rollback annotation to override the class-level default rollback setting.Spring Framework // .setDataSource(dataSource). assuming that "myDataSource" is the bean id). AbstractTransactionalJUnit4SpringContextTests and AbstractTransactionalTestNGSpringContextTests are preconfigured for transactional support at the class level. you can annotate methods explicitly with @Transactional. } // . you must declare @Transactional either at the class or method level for your tests.. Simply annotate any public void method in your test class with one of these annotations. To control whether a transaction should commit for a particular test method. even if you do not explicitly declare @TestExecutionListeners on your test class. In addition. 3. The bean name is used as a fallback qualifier value.. to verify the initial database state prior to execution of your test or to verify expected transactional commit behavior after test execution (if the test was configured not to roll back the transaction). @Autowired @Override public void setDataSource(@Qualifier("myDataSource") DataSource dataSource) { super.. TransactionalTestExecutionListener supports the @BeforeTransaction and @AfterTransaction annotations exactly for such scenarios. for example. Its value is matched against <qualifier> declarations within the corresponding <bean> definitions. you must provide a PlatformTransactionManager bean in the application context loaded by @ContextConfiguration semantics. narrowing the set of type matches to a specific bean. Note that TransactionalTestExecutionListener is configured by default. If transactions are not enabled for the entire test class. and the TransactionalTestExecutionListener ensures that your before transaction method or after transaction method is executed at the appropriate time. Transaction management In the TestContext framework. however.e.

methods annotated with @BeforeTransaction or @AfterTransaction are naturally not executed for tests annotated with @NotTransactional. @RunWith(SpringJUnit4ClassRunner. However. In addition. defaultRollback=false) @Transactional public class FictitiousTransactionalTest { @BeforeTransaction public void verifyInitialDatabaseState() { // logic to verify the initial state before a transaction is started } @Before public void setUpTestDataWithinTransaction() { // set up test data within the transaction } @Test // overrides the class-level defaultRollback setting @Rollback(true) public void modifyDatabaseWithinTransaction() { // logic which uses the test data and modifies database state } @After public void tearDownWithinTransaction() { // execute "tear down" logic within the transaction } @AfterTransaction public void verifyFinalDatabaseState() { // logic to verify the final state after transaction has rolled back } } Avoid false positives when testing ORM code When you test application code that manipulates the state of the Hibernate session. Failing to flush the underlying session can produce false positives: your test may pass.0.1 Reference Documentation 307 .Spring Framework Tip Any before methods (such as methods annotated with JUnit's @Before) and any after methods (such as methods annotated with JUnit's @After) are executed within a transaction. @NotTransactional is deprecated as of Spring 3. and the other method correctly exposes the results of flushing the session. but the same code throws an exception in a live.class) @ContextConfiguration @TransactionConfiguration(transactionManager="txMgr". Note that this applies to JPA and any other ORM 3. In the following Hibernate-based example test case. one method demonstrates a false positive. make sure to flush the underlying session within test methods that execute that code. Consult the annotation support section for further information and configuration examples. The following JUnit-based example displays a fictitious integration testing scenario highlighting several transaction-related annotations. production environment.

in production code) } @Test(expected = GenericJDBCException. • AbstractTransactionalJUnit4SpringContextTests: Abstract transactional extension of AbstractJUnit4SpringContextTests that also adds some convenience functionality for JDBC access. // False positive: an exception will be thrown once the session is // finally flushed (i. Expects a javax.DataSource bean and a PlatformTransactionManager bean to be defined in the ApplicationContext.5+ based test cases.sql.junit4 package provides support classes for JUnit 4.. • AbstractJUnit4SpringContextTests: Abstract base test class that integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a JUnit 4.springframework.class) public void updateWithSessionFlush() { updateEntityInHibernateSession().Spring Framework frameworks that maintain an in-memory unit of work. } // . TestContext support classes JUnit support classes The org. you can access the following protected instance variable: • applicationContext: Use this variable to perform explicit bean lookups or to test the state of the context as a whole.getCurrentSession().1 Reference Documentation 308 .5+ environment. When you extend AbstractJUnit4SpringContextTests... @Autowired private SessionFactory sessionFactory. Use this variable to perform explicit bean lookups or to test the state of the context as a whole.e.flush(). // ... @Test // no expected exception! public void falsePositive() { updateEntityInHibernateSession().test.context. // Manual flush is required to avoid false positive in test sessionFactory. 3. When you extend AbstractTransactionalJUnit4SpringContextTests you can access the following protected instance variables: • applicationContext: Inherited from the AbstractJUnit4SpringContextTests superclass.

@ContextConfiguration.5+ through a custom runner (tested on JUnit 4.9). you can access the following protected instance variable: 3. dependency injection of test instances. and so on. @TestExecutionListeners. } } TestNG support classes The org. @RunWith(SpringJUnit4ClassRunner. The following code listing displays the minimal requirements for configuring a test class to run with the custom Spring Runner. be sure to avoid false positives. • AbstractTestNGSpringContextTests: Abstract base test class that integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a TestNG environment. Tip These classes are a convenience for extension. and Spring ensures that such queries run in the scope of the same transaction as the application code. Such queries can be used to confirm database state both prior to and after execution of database-related application code. By annotating test classes with @RunWith(SpringJUnit4ClassRunner.5 – 4. which otherwise would require an ApplicationContext to be configured through @ContextConfiguration. @TestExecutionListeners is configured with an empty list in order to disable the default listeners.test. If you do not want your test classes to be tied to a Spring-specific class hierarchy — for example. transactional test method execution. and so on.testng package provides support classes for TestNG based test cases. Spring JUnit Runner The Spring TestContext Framework offers full integration with JUnit 4.springframework. developers can implement standard JUnit-based unit and integration tests and simultaneously reap the benefits of the TestContext framework such as support for loading application contexts.. if you want to directly extend the class you are testing — you can configure your own custom test classes by using @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({}) public class SimpleTest { @Test public void testMethod() { // execute test logic.1 Reference Documentation 309 .context.class). When you extend AbstractTestNGSpringContextTests.. When used in conjunction with an ORM tool.Spring Framework • simpleJdbcTemplate: Use this variable to execute SQL statements to query the database.class).

1 Reference Documentation 310 . @Test public void getVets() { Collection<Vet> vets = this. for which a partial listing is shown below: import static org. @TestExecutionListeners. assertEquals("JDBC query must show the same number of vets". and Spring ensures that such queries run in the scope of the same transaction as the application code.Assert. Use this variable to perform explicit bean lookups or to test the state of the context as a whole. illustrates several features of the Spring TestContext Framework in a JUnit 4. If you do not want your test classes to be tied to a Spring-specific class hierarchy — for example. // import .Spring Framework • applicationContext: Use this variable to perform explicit bean lookups or to test the state of the context as a whole. available from the samples repository. you can access the following protected instance variables: • applicationContext: Inherited from the AbstractTestNGSpringContextTests superclass.getVets(). PetClinic Example The PetClinic application.junit. See the source code of AbstractTestNGSpringContextTests for an example of how to instrument your test class.. Expects a javax. Such queries can be used to confirm database state both prior to and after execution of database-related application code. if you want to directly extend the class you are testing — you can configure your own custom test classes by using @ContextConfiguration. and so on. • simpleJdbcTemplate: Use this variable to execute SQL statements to query the database.5+ environment. be sure to avoid false positives.clinic. Tip These classes are a convenience for extension.sql. When you extend AbstractTransactionalTestNGSpringContextTests.assertEquals. 3. When used in conjunction with an ORM tool. • AbstractTransactionalTestNGSpringContextTests: Abstract transactional extension of AbstractTestNGSpringContextTests that adds some convenience functionality for JDBC access. and by manually instrumenting your test class with a TestContextManager. @ContextConfiguration public abstract class AbstractClinicTests extends AbstractTransactionalJUnit4SpringContextTests { @Autowired protected Clinic clinic.DataSource bean and a PlatformTransactionManager bean to be defined in the ApplicationContext.. Most test functionality is included in the AbstractClinicTests.

Spring Framework

super.countRowsInTable("VETS"), vets.size()); Vet v1 = EntityUtils.getById(vets, Vet.class, 2); assertEquals("Leary", v1.getLastName()); assertEquals(1, v1.getNrOfSpecialties()); assertEquals("radiology", (v1.getSpecialties().get(0)).getName()); // ... } // ... }

Notes: • This test case extends the AbstractTransactionalJUnit4SpringContextTests class, from which it inherits configuration for Dependency Injection (through the DependencyInjectionTestExecutionListener) and transactional behavior (through the TransactionalTestExecutionListener). • The clinic instance variable — the application object being tested — is set by Dependency Injection through @Autowired semantics. • The testGetVets() method illustrates how you can use the inherited countRowsInTable() method to easily verify the number of rows in a given table, thus verifying correct behavior of the application code being tested. This allows for stronger tests and lessens dependency on the exact test data. For example, you can add additional rows in the database without breaking tests. • Like many integration tests that use a database, most of the tests in AbstractClinicTests depend on a minimum amount of data already in the database before the test cases run. Alternatively, you might choose to populate the database within the test fixture set up of your test cases — again, within the same transaction as the tests. The PetClinic application supports three data access technologies: JDBC, Hibernate, and JPA. By declaring @ContextConfiguration without any specific resource locations, the AbstractClinicTests class will have its application context loaded from the default location, AbstractClinicTests-context.xml, which declares a common DataSource. Subclasses specify additional context locations that must declare a PlatformTransactionManager and a concrete implementation of Clinic. For example, the Hibernate implementation of the PetClinic tests contains the following implementation. For this example, HibernateClinicTests does not contain a single line of code: we only need to declare @ContextConfiguration, and the tests are inherited from AbstractClinicTests. Because @ContextConfiguration is declared without any specific resource locations, the Spring TestContext Framework loads an application context from all the beans defined in AbstractClinicTests-context.xml (i.e., the inherited locations) and HibernateClinicTests-context.xml, with HibernateClinicTests-context.xml possibly overriding beans defined in AbstractClinicTests-context.xml.
@ContextConfiguration public class HibernateClinicTests extends AbstractClinicTests { }

3.1

Reference Documentation

311

Spring Framework

In a large-scale application, the Spring configuration is often split across multiple files. Consequently, configuration locations are typically specified in a common base class for all application-specific integration tests. Such a base class may also add useful instance variables — populated by Dependency Injection, naturally — such as a SessionFactory in the case of an application using Hibernate. As far as possible, you should have exactly the same Spring configuration files in your integration tests as in the deployed environment. One likely point of difference concerns database connection pooling and transaction infrastructure. If you are deploying to a full-blown application server, you will probably use its connection pool (available through JNDI) and JTA implementation. Thus in production you will use a JndiObjectFactoryBean or <jee:jndi-lookup> for the DataSource and JtaTransactionManager. JNDI and JTA will not be available in out-of-container integration tests, so you should use a combination like the Commons DBCP BasicDataSource and DataSourceTransactionManager or HibernateTransactionManager for them. You can factor out this variant behavior into a single XML file, having the choice between application server and a 'local' configuration separated from all other configuration, which will not vary between the test and production environments. In addition, it is advisable to use properties files for connection settings. See the PetClinic application for an example.

10.4 Further Resources
Consult the following resources for more information about testing: • JUnit: “A programmer-oriented testing framework for Java”. Used by the Spring Framework in its test suite. • TestNG: A testing framework inspired by JUnit with added support for Java 5 annotations, test groups, data-driven testing, distributed testing, etc. • MockObjects.com: Web site dedicated to mock objects, a technique for improving the design of code within test-driven development. • "Mock Objects": Article in Wikipedia. • EasyMock: Java library “that provides Mock Objects for interfaces (and objects through the class extension) by generating them on the fly using Java's proxy mechanism.” Used by the Spring Framework in its test suite. • JMock: Library that supports test-driven development of Java code with mock objects. • Mockito: Java mock library based on the test spy pattern. • DbUnit: JUnit extension (also usable with Ant and Maven) targeted for database-driven projects that, among other things, puts your database into a known state between test runs. • Grinder: Java load testing framework.

3.1

Reference Documentation

312

Part IV. Data Access
This part of the reference documentation is concerned with data access and the interaction between the data access layer and the business or service layer. Spring's comprehensive transaction management support is covered in some detail, followed by thorough coverage of the various data access frameworks and technologies that the Spring Framework integrates with. • Chapter 11, Transaction Management • Chapter 12, DAO support • Chapter 13, Data access with JDBC • Chapter 14, Object Relational Mapping (ORM) Data Access • Chapter 15, Marshalling XML using O/X Mappers

Spring Framework

11. Transaction Management
11.1 Introduction to Spring Framework transaction management
Comprehensive transaction support is among the most compelling reasons to use the Spring Framework. The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits: • Consistent programming model across different transaction APIs such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO). • Support for declarative transaction management. • Simpler API for programmatic transaction management than complex transaction APIs such as JTA. • Excellent integration with Spring's data access abstractions. The following sections describe the Spring Framework's transaction value-adds and technologies. (The chapter also includes discussions of best practices, application server integration, and solutions to common problems.) • Advantages of the Spring Framework's transaction support model describes why you would use the Spring Framework's transaction abstraction instead of EJB Container-Managed Transactions (CMT) or choosing to drive local transactions through a proprietary API such as Hibernate. • Understanding the Spring Framework transaction abstraction outlines the core classes and describes how to configure and obtain DataSource instances from a variety of sources. • Synchronizing resources with transactions describes how the application code ensures that resources are created, reused, and cleaned up properly. • Declarative transaction management describes support for declarative transaction management. • Programmatic transaction management covers support for programmatic (that is, explicitly coded) transaction management.

11.2 Advantages of the Spring Framework's transaction support model
Traditionally, Java EE developers have had two choices for transaction management: global or local transactions, both of which have profound limitations. Global and local transaction management is

3.1

Reference Documentation

314

Spring Framework

reviewed in the next two sections, followed by a discussion of how the Spring Framework's transaction management support addresses the limitations of the global and local transaction models.

Global transactions
Global transactions enable you to work with multiple transactional resources, typically relational databases and message queues. The application server manages global transactions through the JTA, which is a cumbersome API to use (partly due to its exception model). Furthermore, a JTA UserTransaction normally needs to be sourced from JNDI, meaning that you also need to use JNDI in order to use JTA. Obviously the use of global transactions would limit any potential reuse of application code, as JTA is normally only available in an application server environment. Previously, the preferred way to use global transactions was via EJB CMT (Container Managed Transaction): CMT is a form of declarative transaction management (as distinguished from programmatic transaction management). EJB CMT removes the need for transaction-related JNDI lookups, although of course the use of EJB itself necessitates the use of JNDI. It removes most but not all of the need to write Java code to control transactions. The significant downside is that CMT is tied to JTA and an application server environment. Also, it is only available if one chooses to implement business logic in EJBs, or at least behind a transactional EJB facade. The negatives of EJB in general are so great that this is not an attractive proposition, especially in the face of compelling alternatives for declarative transaction management.

Local transactions
Local transactions are resource-specific, such as a transaction associated with a JDBC connection. Local transactions may be easier to use, but have significant disadvantages: they cannot work across multiple transactional resources. For example, code that manages transactions using a JDBC connection cannot run within a global JTA transaction. Because the application server is not involved in transaction management, it cannot help ensure correctness across multiple resources. (It is worth noting that most applications use a single transaction resource.) Another downside is that local transactions are invasive to the programming model.

Spring Framework's consistent programming model
Spring resolves the disadvantages of global and local transactions. It enables application developers to use a consistent programming model in any environment. You write your code once, and it can benefit from different transaction management strategies in different environments. The Spring Framework provides both declarative and programmatic transaction management. Most users prefer declarative transaction management, which is recommended in most cases. With programmatic transaction management, developers work with the Spring Framework transaction abstraction, which can run over any underlying transaction infrastructure. With the preferred declarative model, developers typically write little or no code related to transaction management, and hence do not depend on the Spring Framework transaction API, or any other transaction API. 3.1 Reference Documentation 315

Spring Framework

Do you need an application server for transaction management? The Spring Framework's transaction management support changes traditional rules as to when an enterprise Java application requires an application server. In particular, you do not need an application server simply for declarative transactions through EJBs. In fact, even if your application server has powerful JTA capabilities, you may decide that the Spring Framework's declarative transactions offer more power and a more productive programming model than EJB CMT. Typically you need an application server's JTA capability only if your application needs to handle transactions across multiple resources, which is not a requirement for many applications. Many high-end applications use a single, highly scalable database (such as Oracle RAC) instead. Standalone transaction managers such as Atomikos Transactions and JOTM are other options. Of course, you may need other application server capabilities such as Java Message Service (JMS) and J2EE Connector Architecture (JCA). The Spring Framework gives you the choice of when to scale your application to a fully loaded application server. Gone are the days when the only alternative to using EJB CMT or JTA was to write code with local transactions such as those on JDBC connections, and face a hefty rework if you need that code to run within global, container-managed transactions. With the Spring Framework, only some of the bean definitions in your configuration file, rather than your code, need to change.

11.3 Understanding the Spring Framework transaction abstraction
The key to the Spring transaction abstraction is the notion of a transaction strategy. A transaction strategy is defined by the org.springframework.transaction.PlatformTransactionManager interface:
public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; }

This is primarily a service provider interface (SPI), although it can be used programmatically from your application code. Because PlatformTransactionManager is an interface, it can be easily mocked or stubbed as necessary. It is not tied to a lookup strategy such as JNDI. PlatformTransactionManager implementations are defined like any other object (or bean) in the 3.1 Reference Documentation 316

Spring Framework

Spring Framework IoC container. This benefit alone makes Spring Framework transactions a worthwhile abstraction even when you work with JTA. Transactional code can be tested much more easily than if it used JTA directly. Again in keeping with Spring's philosophy, the TransactionException that can be thrown by any of the PlatformTransactionManager interface's methods is unchecked (that is, it extends the java.lang.RuntimeException class). Transaction infrastructure failures are almost invariably fatal. In rare cases where application code can actually recover from a transaction failure, the application developer can still choose to catch and handle TransactionException. The salient point is that developers are not forced to do so. The getTransaction(..) method returns a TransactionStatus object, depending on a TransactionDefinition parameter. The returned TransactionStatus might represent a new transaction, or can represent an existing transaction if a matching transaction exists in the current call stack. The implication in this latter case is that, as with Java EE transaction contexts, a TransactionStatus is associated with a thread of execution. The TransactionDefinition interface specifies: • Isolation: The degree to which this transaction is isolated from the work of other transactions. For example, can this transaction see uncommitted writes from other transactions? • Propagation: Typically, all code executed within a transaction scope will run in that transaction. However, you have the option of specifying the behavior in the event that a transactional method is executed when a transaction context already exists. For example, code can continue running in the existing transaction (the common case); or the existing transaction can be suspended and a new transaction created. Spring offers all of the transaction propagation options familiar from EJB CMT. To read about the semantics of transaction propagation in Spring, see the section called “Transaction propagation”. • Timeout: How long this transaction runs before timing out and being rolled back automatically by the underlying transaction infrastructure. • Read-only status: A read-only transaction can be used when your code reads but does not modify data. Read-only transactions can be a useful optimization in some cases, such as when you are using Hibernate. These settings reflect standard transactional concepts. If necessary, refer to resources that discuss transaction isolation levels and other core transaction concepts. Understanding these concepts is essential to using the Spring Framework or any transaction management solution. The TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status. The concepts should be familiar, as they are common to all transaction APIs:
public interface TransactionStatus extends SavepointManager { boolean isNewTransaction();

3.1

Reference Documentation

317

Spring Framework

boolean hasSavepoint(); void setRollbackOnly(); boolean isRollbackOnly(); void flush(); boolean isCompleted(); }

Regardless of whether you opt for declarative or programmatic transaction management in Spring, defining the correct PlatformTransactionManager implementation is absolutely essential. You typically define this implementation through dependency injection. PlatformTransactionManager implementations normally require knowledge of the environment in which they work: JDBC, JTA, Hibernate, and so on. The following examples show how you can define a local PlatformTransactionManager implementation. (This example works with plain JDBC.) You define a JDBC DataSource
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean>

The related PlatformTransactionManager bean definition will then have a reference to the DataSource definition. It will look like this:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean>

If you use JTA in a Java EE container then you use a container DataSource, obtained through JNDI, in conjunction with Spring's JtaTransactionManager. This is what the JTA and JNDI lookup version would look like:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"> <jee:jndi-lookup id="dataSource" jndi-name="jdbc/jpetstore"/> <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" /> <!-- other <bean/> definitions here --> </beans>

3.1

Reference Documentation

318

Spring Framework

The JtaTransactionManager does not need to know about the DataSource, or any other specific resources, because it uses the container's global transaction management infrastructure.

Note
The above definition of the dataSource bean uses the <jndi-lookup/> tag from the jee namespace. For more information on schema-based configuration, see Appendix C, XML Schema-based configuration, and for more information on the <jee/> tags see the section entitled the section called “The jee schema”. You can also use Hibernate local transactions easily, as shown in the following examples. In this case, you need to define a Hibernate LocalSessionFactoryBean, which your application code will use to obtain Hibernate Session instances. The DataSource bean definition will be similar to the local JDBC example shown previously and thus is not shown in the following example.

Note
If the DataSource, used by any non-JTA transaction manager, is looked up via JNDI and managed by a Java EE container, then it should be non-transactional because the Spring Framework, rather than the Java EE container, will manage the transactions. The txManager bean in this case is of the HibernateTransactionManager type. In the same way as the DataSourceTransactionManager needs a reference to the DataSource, the HibernateTransactionManager needs a reference to the SessionFactory.
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mappingResources"> <list> <value>org/springframework/samples/petclinic/hibernate/petclinic.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=${hibernate.dialect} </value> </property> </bean> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>

If you are using Hibernate and Java EE container-managed JTA transactions, then you should simply use the same JtaTransactionManager as in the previous JTA example for JDBC.
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>

3.1

Reference Documentation

319

Spring Framework

Note
If you use JTA , then your transaction manager definition will look the same regardless of what data access technology you use, be it JDBC, Hibernate JPA or any other supported technology. This is due to the fact that JTA transactions are global transactions, which can enlist any transactional resource. In all these cases, application code does not need to change. You can change how transactions are managed merely by changing configuration, even if that change means moving from local to global transactions or vice versa.

11.4 Synchronizing resources with transactions
It should now be clear how you create different transaction managers, and how they are linked to related resources that need to be synchronized to transactions (for example DataSourceTransactionManager to a JDBC DataSource, HibernateTransactionManager to a Hibernate SessionFactory, and so forth). This section describes how the application code, directly or indirectly using a persistence API such as JDBC, Hibernate, or JDO, ensures that these resources are created, reused, and cleaned up properly. The section also discusses how transaction synchronization is triggered (optionally) through the relevant PlatformTransactionManager.

High-level synchronization approach
The preferred approach is to use Spring's highest level template based persistence integration APIs or to use native ORM APIs with transaction- aware factory beans or proxies for managing the native resource factories. These transaction-aware solutions internally handle resource creation and reuse, cleanup, optional transaction synchronization of the resources, and exception mapping. Thus user data access code does not have to address these tasks, but can be focused purely on non-boilerplate persistence logic. Generally, you use the native ORM API or take a template approach for JDBC access by using the JdbcTemplate. These solutions are detailed in subsequent chapters of this reference documentation.

Low-level synchronization approach
Classes such as DataSourceUtils (for JDBC), EntityManagerFactoryUtils (for JPA), SessionFactoryUtils (for Hibernate), PersistenceManagerFactoryUtils (for JDO), and so on exist at a lower level. When you want the application code to deal directly with the resource types of the native persistence APIs, you use these classes to ensure that proper Spring Framework-managed instances are obtained, transactions are (optionally) synchronized, and exceptions that occur in the process are properly mapped to a consistent API. For example, in the case of JDBC, instead of the traditional JDBC approach of calling the 3.1 Reference Documentation 320

Spring Framework

getConnection() method on the DataSource, you instead use org.springframework.jdbc.datasource.DataSourceUtils class as follows:
Connection conn = DataSourceUtils.getConnection(dataSource);

Spring's

If an existing transaction already has a connection synchronized (linked) to it, that instance is returned. Otherwise, the method call triggers the creation of a new connection, which is (optionally) synchronized to any existing transaction, and made available for subsequent reuse in that same transaction. As mentioned, any SQLException is wrapped in a Spring Framework CannotGetJdbcConnectionException, one of the Spring Framework's hierarchy of unchecked DataAccessExceptions. This approach gives you more information than can be obtained easily from the SQLException, and ensures portability across databases, even across different persistence technologies. This approach also works without Spring transaction management (transaction synchronization is optional), so you can use it whether or not you are using Spring for transaction management. Of course, once you have used Spring's JDBC support, JPA support or Hibernate support, you will generally prefer not to use DataSourceUtils or the other helper classes, because you will be much happier working through the Spring abstraction than directly with the relevant APIs. For example, if you use the Spring JdbcTemplate or jdbc.object package to simplify your use of JDBC, correct connection retrieval occurs behind the scenes and you won't need to write any special code.

TransactionAwareDataSourceProxy
At the very lowest level exists the TransactionAwareDataSourceProxy class. This is a proxy for a target DataSource, which wraps the target DataSource to add awareness of Spring-managed transactions. In this respect, it is similar to a transactional JNDI DataSource as provided by a Java EE server. It should almost never be necessary or desirable to use this class, except when existing code must be called and passed a standard JDBC DataSource interface implementation. In that case, it is possible that this code is usable, but participating in Spring managed transactions. It is preferable to write your new code by using the higher level abstractions mentioned above.

11.5 Declarative transaction management
Note
Most Spring Framework users choose declarative transaction management. This option has the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container. The Spring Framework's declarative transaction management is made possible with Spring 3.1 Reference Documentation 321

Spring Framework

aspect-oriented programming (AOP), although, as the transactional aspects code comes with the Spring Framework distribution and may be used in a boilerplate fashion, AOP concepts do not generally have to be understood to make effective use of this code. The Spring Framework's declarative transaction management is similar to EJB CMT in that you can specify transaction behavior (or lack of it) down to individual method level. It is possible to make a setRollbackOnly() call within a transaction context if necessary. The differences between the two types of transaction management are: • Unlike EJB CMT, which is tied to JTA, the Spring Framework's declarative transaction management works in any environment. It can work with JTA transactions or local transactions using JDBC, JPA, Hibernate or JDO by simply adjusting the configuration files. • You can apply the Spring Framework declarative transaction management to any class, not merely special classes such as EJBs. • The Spring Framework offers declarative rollback rules, a feature with no EJB equivalent. Both programmatic and declarative support for rollback rules is provided. • The Spring Framework enables you to customize transactional behavior, by using AOP. For example, you can insert custom behavior in the case of transaction rollback. You can also add arbitrary advice, along with the transactional advice. With EJB CMT, you cannot influence the container's transaction management except with setRollbackOnly(). • The Spring Framework does not support propagation of transaction contexts across remote calls, as do high-end application servers. If you need this feature, we recommend that you use EJB. However, consider carefully before using such a feature, because normally, one does not want transactions to span remote calls. Where is TransactionProxyFactoryBean? Declarative transaction configuration in versions of Spring 2.0 and above differs considerably from previous versions of Spring. The main difference is that there is no longer any need to configure TransactionProxyFactoryBean beans. The pre-Spring 2.0 configuration style is still 100% valid configuration; think of the new <tx:tags/> as simply defining TransactionProxyFactoryBean beans on your behalf.

The concept of rollback rules is important: they enable you to specify which exceptions (and throwables) should cause automatic rollback. You specify this declaratively, in configuration, not in Java code. So, although you can still call setRollbackOnly()on the TransactionStatus object to roll back the current transaction back, most often you can specify a rule that MyApplicationException must always result in rollback. The significant advantage to this option is that business objects do not depend on the transaction infrastructure. For example, they typically do not need to import Spring transaction APIs or other Spring APIs. 3.1 Reference Documentation 322

Spring Framework

Although EJB container default behavior automatically rolls back the transaction on a system exception (usually a runtime exception), EJB CMT does not roll back the transaction automatically on an application exception (that is, a checked exception other than java.rmi.RemoteException). While the Spring default behavior for declarative transaction management follows EJB convention (roll back is automatic only on unchecked exceptions), it is often useful to customize this behavior.

Understanding the Spring Framework's declarative transaction implementation
It is not sufficient to tell you simply to annotate your classes with the @Transactional annotation, add the line (<tx:annotation-driven/>) to your configuration, and then expect you to understand how it all works. This section explains the inner workings of the Spring Framework's declarative transaction infrastructure in the event of transaction-related issues. The most important concepts to grasp with regard to the Spring Framework's declarative transaction support are that this support is enabled via AOP proxies, and that the transactional advice is driven by metadata (currently XML- or annotation-based). The combination of AOP with transactional metadata yields an AOP proxy that uses a TransactionInterceptor in conjunction with an appropriate PlatformTransactionManager implementation to drive transactions around method invocations.

Note
Spring AOP is covered in Chapter 8, Aspect Oriented Programming with Spring. Conceptually, calling a method on a transactional proxy looks like this...

3.1

Reference Documentation

323

Spring Framework

Example of declarative transaction implementation
Consider the following interface, and its attendant implementation. This example uses Foo and Bar classes as placeholders so that you can concentrate on the transaction usage without focusing on a particular domain model. For the purposes of this example, the fact that the DefaultFooService class throws UnsupportedOperationException instances in the body of each implemented method is good; it allows you to see transactions created and then rolled back in response to the UnsupportedOperationException instance.
// the service interface that we want to make transactional package x.y.service; public interface FooService { Foo getFoo(String fooName); Foo getFoo(String fooName, String barName); void insertFoo(Foo foo); void updateFoo(Foo foo); }

// an implementation of the above interface package x.y.service; public class DefaultFooService implements FooService {

3.1

Reference Documentation

324

Spring Framework

public Foo getFoo(String fooName) { throw new UnsupportedOperationException(); } public Foo getFoo(String fooName, String barName) { throw new UnsupportedOperationException(); } public void insertFoo(Foo foo) { throw new UnsupportedOperationException(); } public void updateFoo(Foo foo) { throw new UnsupportedOperationException(); } }

Assume that the first two methods of the FooService interface, getFoo(String) and getFoo(String, String), must execute in the context of a transaction with read-only semantics, and that the other methods,insertFoo(Foo) and updateFoo(Foo), must execute in the context of a transaction with read-write semantics. The following configuration is explained in detail in the next few paragraphs.
<!-- from the file 'context.xml' --> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- this is the service object that we want to make transactional --> <bean id="fooService" class="x.y.service.DefaultFooService"/> <!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) --> <tx:advice id="txAdvice" transaction-manager="txManager"> <!-- the transactional semantics... --> <tx:attributes> <!-- all methods starting with 'get' are read-only --> <tx:method name="get*" read-only="true"/> <!-- other methods use the default transaction settings (see below) --> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- ensure that the above transactional advice runs for any execution of an operation defined by the FooService interface --> <aop:config> <aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.FooService.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/> </aop:config> <!-- don't forget the DataSource --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@rj-t42:1521:elvis"/>

3.1

Reference Documentation

325

Spring Framework

<property name="username" value="scott"/> <property name="password" value="tiger"/> </bean> <!-- similarly, don't forget the PlatformTransactionManager --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- other <bean/> definitions here --> </beans>

Examine the preceding configuration. You want to make a service object, the fooService bean, transactional. The transaction semantics to apply are encapsulated in the <tx:advice/> definition. The <tx:advice/> definition reads as “... all methods on starting with 'get' are to execute in the context of a read-only transaction, and all other methods are to execute with the default transaction semantics”. The transaction-manager attribute of the <tx:advice/> tag is set to the name of the PlatformTransactionManager bean that is going to drive the transactions, in this case, the txManager bean.

Tip
You can omit the transaction-manager attribute in the transactional advice (<tx:advice/>) if the bean name of the PlatformTransactionManager that you want to wire in has the name transactionManager. If the PlatformTransactionManager bean that you want to wire in has any other name, then you must use the transaction-manager attribute explicitly, as in the preceding example. The <aop:config/> definition ensures that the transactional advice defined by the txAdvice bean executes at the appropriate points in the program. First you define a pointcut that matches the execution of any operation defined in the FooService interface (fooServiceOperation). Then you associate the pointcut with the txAdvice using an advisor. The result indicates that at the execution of a fooServiceOperation, the advice defined by txAdvice will be run. The expression defined within the <aop:pointcut/> element is an AspectJ pointcut expression; see Chapter 8, Aspect Oriented Programming with Spring for more details on pointcut expressions in Spring 2.0. A common requirement is to make an entire service layer transactional. The best way to do this is simply to change the pointcut expression to match any operation in your service layer. For example:
<aop:config> <aop:pointcut id="fooServiceMethods" expression="execution(* x.y.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceMethods"/> </aop:config>

Note
3.1 Reference Documentation 326

FooService. and so on.insertFoo (new Foo()).UnsupportedOperationException [TransactionInterceptor] .apache. but what does all this configuration actually do?”. --> [DataSourceTransactionManager] ..) method is now being invoked on the proxy --> [TransactionInterceptor] .Rolling back JDBC transaction on Connection [org.FooService.y. Consider the following program that test drives the above configuration: public final class Boot { public static void main(final String[] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("context.service.service..java:14) <!-. so that when an appropriate method is invoked on the proxy..service..FooService.the Spring container is starting up. FooService fooService = (FooService) ctx.the transactional advice kicks in here.) method of the DefaultFooService class have been truncated for clarity.lang.and the transaction is rolled back (by default.insertFoo(DefaultFooService. depending on the transaction configuration associated with that method... marked as read-only. the insertFoo(..1 Reference Documentation 327 .Getting transaction for x. The proxy will be configured with the transactional advice. (The Log4J output and the stack trace from the UnsupportedOperationException thrown by the insertFoo(.Creating new transaction with name [x.getBean("fooService"). “Okay.lang.dbcp.PoolableConnection@a53de4] for JDBC transaction <!-. The above configuration will be used to create a transactional proxy around the object that is created from the fooService bean definition.Invoking rollback for transaction on x.insertFoo due to throwable [java.. --> [RuleBasedTransactionAttribute] . a transaction is started.UnsupportedOperationException] <!-.insertFoo <!-.class).PoolableConnection@a53de4] [DataSourceTransactionManager] .insertFoo(Unknown Source) 3.y.DefaultFooService. see Chapter 8.dbcp.y. RuntimeException instances cause rollback) --> [DataSourceTransactionManager] ..Creating implicit proxy for bean 'fooService' with 0 common interceptors and 1 specific interceptors <!-.the insertFoo(. suspended.the DefaultFooService is actually proxied --> [JdkDynamicAopProxy] .Acquired Connection [org.commons.Releasing JDBC Connection after transaction [DataSourceUtils] .lang. --> [AspectJInvocationContextExposingAdvisorAutoProxyCreator] .service.commons..AOP infrastructure stack trace elements removed for clarity --> at $Proxy0..y.service package. fooService.xml".UnsupportedOperationException at x. Aspect Oriented Programming with Spring for more details.apache.service. you may be asking yourself.Applying rules to determine whether transaction should rollback on java.. } } The output from running the preceding program will resemble the following.Creating JDK dynamic proxy for [x.insertFoo] [DataSourceTransactionManager] .Returning JDBC Connection to DataSource Exception in thread "main" java.Spring Framework In this example it is assumed that all your service interfaces are defined in the x.. Now that we've analyzed the configuration.) method from DefaultFooService throws an exception.y.y.) <!-..DefaultFooService] <!-. Boot.

The following example tells the Spring Framework's transaction infrastructure to commit the attendant transaction even in the face of an unhandled InstrumentNotFoundException.result in a rollback).by default . <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true" rollback-for="NoProductInStockException"/> <tx:method name="*"/> </tx:attributes> </tx:advice> You can also specify 'no rollback rules'. and make a determination whether to mark the transaction for rollback. the strongest matching rule wins. <tx:advice id="txAdvice"> <tx:attributes> <tx:method name="*" rollback-for="Throwable" no-rollback-for="InstrumentNotFoundException"/> </tx:attributes> 3. application-specific Exception type. You can configure exactly which Exception types mark a transaction for rollback. declaratively in your application. when the thrown exception is an instance or subclass of RuntimeException. unchecked exceptions. The following XML snippet demonstrates how you configure rollback for a checked.Spring Framework at Boot.main(Boot.java:11) Rolling back a declarative transaction The previous section outlined the basics of how to specify transactional settings for classes. the Spring Framework's transaction infrastructure code only marks a transaction for rollback in the case of runtime. This section describes how you can control the rollback of transactions in a simple declarative fashion. (Errors will also . So in the case of the following configuration. that is. typically service layer classes. including checked exceptions. any exception other than an InstrumentNotFoundException results in a rollback of the attendant transaction. The Spring Framework's transaction infrastructure code will catch any unhandled Exception as it bubbles up the call stack.1 Reference Documentation 328 . <tx:advice id="txAdvice"> <tx:attributes> <tx:method name="updateStock" no-rollback-for="InstrumentNotFoundException"/> <tx:method name="*"/> </tx:attributes> </tx:advice> When the Spring Framework's transaction infrastructure catches an exception and is consults configured rollback rules to determine whether to mark the transaction for rollback. The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction. In its default configuration. if you do not want a transaction rolled back when an exception is thrown. Checked exceptions that are thrown from a transactional method do not result in rollback in the default configuration.

service.org/schema/aop http://www.springframework. you would write the following: <?xml version="1.extras.springframework.(not in the right package) --> 3.xsd http://www.org/schema/beans" xmlns:xsi="http://www.y. first assume that all of your service layer classes are defined in a root x. } catch (NoProductInStockException ex) { // trigger rollback programmatically TransactionAspectSupport. and these two beans won't --> <bean id="anotherService" class="org.springframework. } } You are strongly encouraged to use the declarative approach to rollback if at all possible.these two beans will be transactional.1 Reference Documentation 329 ...Spring Framework </tx:advice> You can also indicate a required rollback programmatically.w3.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.DefaultFooService"/> <bean id="barService" class="x. Although very simple.springframework.org/schema/tx/spring-tx-3.. --> <bean id="fooService" class="x..org/schema/tx http://www..*(.y. Configuring different transactional semantics for different beans Consider the scenario where you have a number of service layer objects.currentTransactionStatus().xsd"> <aop:config> <aop:pointcut id="serviceOperation" expression="execution(* x.org/2001/XMLSchema-instance" xmlns:aop="http://www. As a point of comparison.org/schema/tx" xsi:schemaLocation=" http://www..springframework.service. and you want to apply a totally different transactional configuration to each of them.org/schema/beans/spring-beans-3.0.SimpleBarService"/> <!-.service..))"/> <aop:advisor pointcut-ref="serviceOperation" advice-ref="txAdvice"/> </aop:config> <!-. You do this by defining distinct <aop:advisor/> elements with differing pointcut and advice-ref attribute values.SomeService"/> <!-.*Service.y. and tightly couples your code to the Spring Framework's transaction infrastructure: public void resolvePosition() { try { // some business logic..setRollbackOnly().service package. To make all beans that are instances of classes defined in that package (or in subpackages) and that have names ending in Service have the default transactional configuration.xsd http://www.xyz.0. but its usage flies in the face of achieving a clean POJO-based architecture.org/schema/aop" xmlns:tx="http://www.springframework.. Programmatic rollback is available should you absolutely need it.org/schema/beans http://www.springframework. this process is quite invasive.y.springframework.0.org/schema/aop/spring-aop-3.

org/schema/aop http://www.0" encoding="UTF-8"?> <beans xmlns="http://www.DefaultFooService"/> <!-..org/schema/tx" xsi:schemaLocation=" http://www.org/schema/beans/spring-beans-3.xsd"> <aop:config> <aop:pointcut id="defaultServiceOperation" expression="execution(* x.springframework.service.springframework.1 Reference Documentation 330 .this bean will be transactional (see the 'defaultServiceOperation' pointcut) --> <bean id="fooService" class="x.*Service..springframework.other transaction infrastructure beans such as a PlatformTransactionManager omitted.other transaction infrastructure beans such as a PlatformTransactionManager omitted.0.DefaultDdlManager"/> <tx:advice id="defaultTxAdvice"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <tx:advice id="noTxAdvice"> <tx:attributes> <tx:method name="*" propagation="NEVER"/> </tx:attributes> </tx:advice> <!-.Spring Framework <bean id="barManager" class="x.service.org/schema/tx/spring-tx-3.w3.ddl.org/2001/XMLSchema-instance" xmlns:aop="http://www.0.springframework.DefaultDdlManager.springframework.))"/> <aop:pointcut id="noTxServiceOperation" expression="execution(* x.y.(doesn't end in 'Service') --> <tx:advice id="txAdvice"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-.y..SimpleBarManager"/> <!-.springframework.y.y.springframework.org/schema/tx http://www.*(...service.this bean will also be transactional.0.service..org/schema/beans http://www.))"/> <aop:advisor pointcut-ref="defaultServiceOperation" advice-ref="defaultTxAdvice"/> <aop:advisor pointcut-ref="noTxServiceOperation" advice-ref="noTxAdvice"/> </aop:config> <!-. --> </beans> The following example shows how to configure two distinct beans with totally different transactional settings.org/schema/beans" xmlns:xsi="http://www. <?xml version="1. but with totally different transactional settings --> <bean id="anotherFooService" class="x.service.springframework.xsd http://www.ddl. --> </beans> 3.org/schema/aop" xmlns:tx="http://www.org/schema/aop/spring-aop-3.*(.xsd http://www.springframework.y.

get*. the various attributes of the <tx:method/> tags that are nested within <tx:advice/> and <tx:attributes/> tags are summarized below: Table 11. For example.foo.1 Reference Documentation 331 . Transaction isolation level. com. The default <tx:advice/> settings are: • Propagation setting is REQUIRED. propagation isolation timeout read-only rollback-for No No No No No Exception(s) that trigger rollback. for example.MyBusinessException.foo. Transaction timeout value (in seconds). <tx:method/> settings Attribute name Required? Default Yes Method name(s) with which the transaction attributes are to be associated. or none if timeouts are not supported. • Any RuntimeException triggers rollback. REQUIRED DEFAULT -1 false Transaction propagation behavior. and so forth. • Transaction timeout defaults to the default timeout of the underlying transaction system.ServletException. on*Event.MyBusinessException. • Transaction is read/write. comma-delimited. and any checked Exception does not. For example. com.Spring Framework <tx:advice/> settings This section summarizes the various transactional settings that can be specified using the <tx:advice/> tag. no-rollback-for No Exception(s) that do not trigger rollback. • Isolation level is DEFAULT. handle*. Is this transaction read-only? Description 3. The wildcard (*) character can be used to associate the same transaction attribute settings with a number of methods. You can change these default settings.ServletException. comma-delimited.1.

org/schema/tx http://www.springframework.org/schema/beans http://www.org/schema/tx/spring-tx-3.w3.enable the configuration of transactional behavior based on annotations --> <tx:annotation-driven transaction-manager="txManager"/> <!-.Spring Framework Using @Transactional In addition to the XML-based declarative approach to transaction configuration. because code that is meant to be used transactionally is almost always deployed that way anyway.springframework.from the file 'context. Foo getFoo(String fooName.DefaultFooService"/> <!-.0. you can use an annotation-based approach. Consider the following class definition: // the service class that we want to make transactional @Transactional public class DefaultFooService implements FooService { Foo getFoo(String fooName). which is explained in the text that follows.y.this is the service object that we want to make transactional --> <bean id="fooService" class="x. String barName).1 Reference Documentation 332 .xml' --> <?xml version="1. } When the above POJO is defined as a bean in a Spring IoC container.service.springframework.springframework. void updateFoo(Foo foo).jdbc.0.xsd http://www.springframework.xsd"> <!-. The ease-of-use afforded by the use of the @Transactional annotation is best illustrated with an example.0.DataSourceTransactionManager"> <!-.org/schema/aop http://www.other <bean/> definitions here --> </beans> Tip 3.xsd http://www.springframework.springframework. There is not much danger of undue coupling. Declaring transaction semantics directly in the Java source code puts the declarations much closer to the affected code.org/schema/tx" xsi:schemaLocation=" http://www.org/schema/aop" xmlns:tx="http://www.a PlatformTransactionManager is still required --> <bean id="txManager" class="org.org/schema/aop/spring-aop-3. the bean instance can be made transactional by adding merely one line of XML configuration: <!-.org/schema/beans/spring-beans-3.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.datasource.springframework.org/schema/beans" xmlns:xsi="http://www.(this dependency is defined somewhere else) --> <property name="dataSource" ref="dataSource"/> </bean> <!-. void insertFoo(Foo foo).springframework.org/2001/XMLSchema-instance" xmlns:aop="http://www.

no error is raised. However. will not lead to an actual transaction at runtime 3. This means that self-invocation. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies (proxy-target-class="true") or the weaving-based aspect (mode="aspectj"). as opposed to annotating interfaces. You can place the @Transactional annotation before an interface definition. Consider the use of AspectJ (see below) if you need to annotate non-public methods. but this works only as you would expect it to if you are using interface-based proxies. In the preceding example.1 Reference Documentation 333 . a class definition. only external method calls coming in through the proxy are intercepted. or a public method on a class. the mere presence of the @Transactional annotation is not enough to activate the transactional behavior. If you do annotate protected. Note In proxy mode (which is the default). The @Transactional annotation is simply metadata that can be consumed by some runtime infrastructure that is @Transactional-aware and that can use the metadata to configure the appropriate beans with transactional behavior. which would be decidedly bad. the <tx:annotation-driven/> element switches on the transactional behavior. private or package-visible methods with the @Transactional annotation. then you have to use the transaction-manager attribute explicitly. as in the preceding example. If the PlatformTransactionManager bean that you want to dependency-inject has any other name. Tip Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @Transactional annotation. a method within the target object calling another method of the target object. you should apply the @Transactional annotation only to methods with public visibility.Spring Framework You can omit the transaction-manager attribute in the <tx:annotation-driven/> tag if the bean name of the PlatformTransactionManager that you want to wire in has the name transactionManager. Method visibility and @Transactional When using proxies. but the annotated method does not exhibit the configured transactional settings. in effect. You certainly can place the @Transactional annotation on an interface (or an interface method). a method on an interface. then the transaction settings are not recognized by the proxying and weaving infrastructure. and the object will not be wrapped in a transactional proxy.

In this case. as in the example above. <tx:annotation-driven/> settings Attribute transaction-manager Default transactionManager Name of transaction manager to use. Only required if the name of the transaction manager is not transactionManager. there will not be a proxy in the first place. The alternative mode "aspectj" instead weaves the affected classes with Spring's AspectJ transaction aspect. (See the section called “Spring configuration” for details on how to set up load-time weaving. applying to method calls coming in through the proxy only). as discussed above. AspectJ weaving requires spring-aspects. Consider the use of AspectJ mode (see mode attribute in table below) if you expect self-invocations to be wrapped with transactions as well.jar in the classpath as well as load-time weaving (or compile-time weaving) enabled.) proxy-target-class false Applies to proxy mode only. instead. Table 11. its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.Spring Framework even if the invoked method is marked with @Transactional. modifying the target class byte code to apply to any kind of method call. Controls what type of transactional proxies are created for classes annotated with the 3. mode proxy The default mode "proxy" processes annotated beans to be proxied using Spring's AOP framework (following proxy semantics.1 Reference Documentation 334 Description . the target class will be weaved (that is.2.

(See Section 8.LOWEST_PRECEDENCE Defines the order of the transaction advice that is applied to beans annotated with @Transactional.6.) Note <tx:annotation-driven/> only looks for @Transactional on beans in the same application context it is defined in. If the proxy-target-class attribute is set to true.2. 3. If proxy-target-class attribute is set to true.1 Reference Documentation 335 . class-based proxies are created. see the section called “Advice ordering”. if you put <tx:annotation-driven/> in a WebApplicationContext for a DispatcherServlet. This means that. “Proxying mechanisms” for a detailed examination of the different proxy types. and not your services.Spring Framework Attribute Default Description @Transactional annotation.) No specified ordering means that the AOP subsystem determines the order of the advice. (See Section 8. it only checks for @Transactional beans in your controllers. “The DispatcherServlet” for more information. (For more information about the rules related to ordering of AOP advice. Note The proxy-target-class attribute on the <tx:annotation-driven/> element controls what type of transactional proxies are created for classes annotated with the @Transactional annotation. See Section 16. “Proxying mechanisms” for a discussion of the different proxy types. If proxy-target-class is false or if the attribute is omitted. standard JDK interface-based proxies are created. If proxy-target-class is false or if the attribute is omitted.) order Ordered. then standard JDK interface-based proxies are created.6. then class-based proxies are created.

• Any RuntimeException triggers rollback. propagation = Propagation.3. These default settings can be changed. class. but the @Transactional annotation on the updateFoo(Foo) method in the same class takes precedence over the transactional settings defined at the class level. @Transactional(readOnly = true) public class DefaultFooService implements FooService { public Foo getFoo(String fooName) { // do something } // these settings have precedence for this method @Transactional(readOnly = false. In the case of the following example. propagation isolation 3. • Transaction timeout defaults to the default timeout of the underlying transaction system. The default @Transactional settings are as follows: • Propagation setting is PROPAGATION_REQUIRED. • Transaction is read/write.1 Reference Documentation 336 . suspending any existing transaction”. the DefaultFooService class is annotated at the class level with the settings for a read-only transaction. @Transactional properties Property value Type String enum: Propagation enum: Isolation Description Optional qualifier specifying the transaction manager to be used. or to none if timeouts are not supported.Spring Framework The most derived location takes precedence when evaluating the transactional settings for a method.REQUIRES_NEW) public void updateFoo(Foo foo) { // do something } } @Transactional settings The @Transactional annotation is metadata that specifies that an interface. “start a brand new read-only transaction when this method is invoked. Optional isolation level. Optional propagation setting. or method must have transactional semantics. the various properties of the @Transactional annotation are summarized in the following table: Table 11. • Isolation level is ISOLATION_DEFAULT. for example. and any checked Exception does not.

.BusinessService. } @Transactional("account") public void doSomething() { .handlePayment. Array of Class objects. For example. } } could be combined with the following transaction manager bean declarations in the application context.. rollback. WebLogic's transaction monitor). and in logging output. where 'name' means the transaction name that will be shown in a transaction monitor. Multiple Transaction Managers with @Transactional Most Spring applications only need a single transaction manager. read-only timeout rollbackFor Transaction timeout.1 Reference Documentation 337 . For example. cause rollback.Spring Framework Property readOnly Type boolean int (in seconds granularity) Description Read/write transaction vs.. the following Java code public class TransactionalService { @Transactional("order") public void setSomething(String name) { . the name of the transaction would be: com. Classes Optional array of names of must be derived from exception classes that must Throwable...) method of the BusinessService class started a transaction." + method name of the transactionally-advised class. Throwable. the transaction name is always the fully-qualified class name + ". cause rollback. For declarative transactions. The value attribute of the @Transactional annotation can be used to optionally specify the identity of the PlatformTransactionManager to be used. if the handlePayment(. using the qualifier notation. This can either be the bean name or the qualifier value of the transaction manager bean.foo. if applicable (for example. Optional array of names of which must be derived from exception classes that must not Throwable. but there may be situations where you want multiple independent transaction managers in a single application. which Optional array of exception must be derived from classes that must cause rollback. Array of class names. Array of Class objects. 3. which Optional array of exception must be derived from classes that must not cause Throwable. Currently you cannot have explicit control over the name of a transaction. rollbackForClassname noRollbackFor noRollbackForClassname Array of String class names.

ElementType.RUNTIME) @Transactional("account") public @interface AccountTx { } allows us to write the example from the previous section as public class TransactionalService { @OrderTx public void setSomething(String name) { . } } Here we have used the syntax to define the transaction manager qualifier. } @AccountTx public void doSomething() { . rather it details some of the semantics regarding 3.springframework. but could also have included propagation behavior.. then Spring's meta-annotation support allows you to define custom shortcut annotations for your specific use cases. Please note that this section is not an introduction to transaction propagation proper. <qualifier value="account"/> </bean> In this case.DataSourceTransactionManager"> . <qualifier value="order"/> </bean> <bean id="transactionManager2" class="org. defining the following annotations @Target({ElementType..METHOD. For example. The default <tx:annotation-driven> target bean name transactionManager will still be used if no specifically qualified PlatformTransactionManager bean is found.RUNTIME) @Transactional("order") public @interface OrderTx { } @Target({ElementType.TYPE}) @Retention(RetentionPolicy. ElementType. Custom shortcut annotations If you find you are repeatedly using the same attributes with @Transactional on many different methods..DataSourceTransactionManager"> .1 Reference Documentation 338 .Spring Framework <tx:annotation-driven/> <bean id="transactionManager1" class="org.springframework. rollback rules...TYPE}) @Retention(RetentionPolicy. timeouts etc.jdbc. the two methods on TransactionalService will run under separate transaction managers.. Transaction propagation This section describes some semantics of transaction propagation in Spring..jdbc. differentiated by the "order" and "account" qualifiers..METHOD.

RequiresNew 3.Spring Framework transaction propagation in Spring. In Spring-managed transactions. and how the propagation setting applies to this difference. Required PROPAGATION_REQUIRED When the propagation setting is PROPAGATION_REQUIRED. in the case where an inner transaction scope sets the rollback-only marker. all these scopes will be mapped to the same physical transaction. Of course. the outer transaction has not decided on the rollback itself. The outer caller needs to receive an UnexpectedRollbackException to indicate clearly that a rollback was performed instead. Each such logical transaction scope can determine rollback-only status individually. with an outer transaction scope being logically independent from the inner transaction scope. A corresponding UnexpectedRollbackException is thrown at that point. be aware of the difference between physical and logical transactions. in case of standard PROPAGATION_REQUIRED behavior. the outer caller still calls commit. So if an inner transaction (of which the outer caller is not aware) silently marks a transaction as rollback-only. This is expected behavior so that the caller of a transaction can never be misled to assume that a commit was performed when it really was not. a logical transaction scope is created for each method upon which the setting is applied. However.1 Reference Documentation 339 . So a rollback-only marker set in the inner transaction scope does affect the outer transaction's chance to actually commit (as you would expect it to). and so the rollback (silently triggered by the inner transaction scope) is unexpected.

Spring Framework PROPAGATION_REQUIRES_NEW PROPAGATION_REQUIRES_NEW. 2. 3. the underlying physical transactions are different and hence can commit or roll back independently.1 Reference Documentation 340 . Configured profiling aspect starts up. Nested PROPAGATION_NESTED uses a single physical transaction with multiple savepoints that it can roll back to. Profiling aspect reports exact duration of the whole transactional method invocation. you want to see the following actions: 1. in contrast to PROPAGATION_REQUIRED. uses a completely independent transaction for each affected transaction scope. Method on the advised object executes. 5. This setting is typically mapped onto JDBC savepoints. Advising transactional operations Suppose you want to execute both transactional and some basic profiling advice. with the outer transaction being able to continue the physical transaction despite some operations having been rolled back. 4. so will only work with JDBC resource transactions. Transactional advice executes. See Spring's DataSourceTransactionManager. Such partial rollbacks allow an inner transaction scope to trigger a rollback for its scope. In that case. Transaction commits. 3. with an outer transaction not affected by an inner transaction's rollback status. How do you effect this in the context of <tx:annotation-driven/>? When you invoke the updateFoo(Foo) method.

springframework.out.springframework.org/schema/aop/spring-aop-3. returnValue = call.prettyPrint()). } public void setOrder(int order) { this. Aspect Oriented Programming with Spring for detailed coverage of the following AOP configuration and AOP in general. } } <?xml version="1. System. import org.y.util. } return returnValue.order. See Chapter 8.DefaultFooService"/> <!-.org/schema/tx http://www.org/schema/beans http://www.println(clock. public class SimpleProfiler implements Ordered { private int order.springframework.getName()). } finally { clock.order = order.springframework.StopWatch.y.y.springframework.start(call.SimpleProfiler"> 3.0.Ordered. try { clock. The ordering of advice is controlled through the Ordered interface.org/schema/aop" xmlns:tx="http://www.xsd http://www.0. // allows us to control the ordering of advice public int getOrder() { return this.w3. package x.this is the aspect --> <bean id="profiler" class="x.org/schema/tx/spring-tx-3.org/schema/beans" xmlns:xsi="http://www.ProceedingJoinPoint.aspectj.springframework.Spring Framework Note This chapter is not concerned with explaining AOP in any great detail (except as it applies to transactions).0. import org.springframework.org/schema/beans/spring-beans-3.stop().1 Reference Documentation 341 . StopWatch clock = new StopWatch(getClass().toShortString()). } // this method is the around advice public Object profile(ProceedingJoinPoint call) throws Throwable { Object returnValue.springframework.springframework.service.org/schema/aop http://www. see the section called “Advice ordering”.org/schema/tx" xsi:schemaLocation=" http://www.lang.core.xsd http://www. import org.org/2001/XMLSchema-instance" xmlns:aop="http://www.0" encoding="UTF-8"?> <beans xmlns="http://www.proceed().springframework.xsd"> <bean id="fooService" class="x. For full details on advice ordering. Here is the code for a simple profiling aspect discussed above.springframework.

springframework.*(. <?xml version="1. The following example effects the same setup as above.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> </beans> The result of the above configuration is a fooService bean that has profiling and transactional aspects applied to it in the desired order.springframework.springframework.order value is higher than the profiling aspect --> <aop:aspect id="profilingAspect" ref="profiler"> 3.datasource.org/schema/tx http://www.SimpleProfiler"> <!-.1 Reference Documentation 342 .xsd"> <bean id="fooService" class="x.0.this advice will execute around the transactional advice --> <aop:aspect id="profilingAspect" ref="profiler"> <aop:pointcut id="serviceMethodWithReturnValue" expression="execution(!void x.w3.f.xsd http://www.org/schema/tx/spring-tx-3.org/schema/tx" xsi:schemaLocation=" http://www.org/schema/aop" xmlns:tx="http://www..*Service.springframework.))"/> <aop:around method="profile" pointcut-ref="serviceMethodWithReturnValue"/> </aop:aspect> </aop:config> <bean id="dataSource" class="org.y.DefaultFooService"/> <!-.y.xsd http://www.y.springframework.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.Spring Framework <!-.execute before the transactional advice (hence the lower order number) --> <property name="order" value="1"/> </bean> <tx:annotation-driven transaction-manager="txManager" order="200"/> <aop:config> <!-.*(.the profiling advice --> <bean id="profiler" class="x.springframework. the order attribute) --> <aop:advisor advice-ref="txAdvice" pointcut-ref="entryPointMethod" order="2"/> <!-.jdbc.y.springframework.org/schema/aop http://www.*Service..springframework.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@rj-t42:1521:elvis"/> <property name="username" value="scott"/> <property name="password" value="tiger"/> </bean> <bean id="txManager" class="org.driver.. You configure any number of additional aspects in similar fashion.org/schema/beans" xmlns:xsi="http://www.org/2001/XMLSchema-instance" xmlns:aop="http://www.jdbc.will execute after the profiling advice (c.springframework.0.dbcp.commons.execute before the transactional advice (hence the lower order number) --> <property name="order" value="1"/> </bean> <aop:config> <aop:pointcut id="entryPointMethod" expression="execution(* x.apache.service.))"/> <!-.org/schema/beans/spring-beans-3.0.org/schema/aop/spring-aop-3.0" encoding="UTF-8"?> <beans xmlns="http://www.org/schema/beans http://www.. but uses the purely XML declarative approach.springframework.

and before the transactional advice on the way out.aspectOf(). Because we're focusing here on applications running outside of a Spring container.setTransactionManager(txManager). You configure additional aspects in similar fashion.*Service. // configure the AnnotationTransactionAspect to use it. and then you link (weave) your application with the org..*(. we'll show you how to do it programmatically. The simplest way to configure the transaction management aspect is to use the <tx:annotation-driven/> element and specify the mode attribute to aspectj as described in the section called “Using @Transactional”. Using @Transactional with AspectJ It is also possible to use the Spring Framework's @Transactional support outside of a Spring container by means of an AspectJ aspect. then you simply swap the value of the profiling aspect bean's order property so that it is higher than the transactional advice's order value.jar file. Aspect Oriented Programming with Spring respectively.springframework. If you want the profiling advice to execute after the transactional advice on the way in. you first annotate your classes (and optionally your classes' methods) with the @Transactional annotation. // construct an appropriate transaction manager DataSourceTransactionManager txManager = new DataSourceTransactionManager(getDataSource()).aspectj.transaction. Note Prior to continuing..1 Reference Documentation 343 . this must be done before executing any transactional me AnnotationTransactionAspect. you may want to read the section called “Using @Transactional” and Chapter 8.))"/> <aop:around method="profile" pointcut-ref="serviceMethodWithReturnValue"/> </aop:aspect> </aop:config> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-. The aspect must also be configured with a transaction manager. You can of course use the Spring Framework's IoC container to take care of dependency-injecting the aspect.y. To do so.Spring Framework <aop:pointcut id="serviceMethodWithReturnValue" expression="execution(!void x.AnnotationTransactionAspect defined in the spring-aspects.other <bean/> definitions such as a DataSource and a PlatformTransactionManager here --> </beans> The result of the above configuration will be a fooService bean that has profiling and transactional aspects applied to it in that order. 3.

Whether or not programmatic transaction management is suitable for your development needs is a decision that you will have to make yourself. regardless of visibility. to free application code from having to do the boilerplate acquisition and release of transactional resources. • Using a PlatformTransactionManager implementation directly. Any method may be annotated. The Spring team generally recommends the TransactionTemplate for programmatic transaction management. Note As you will see in the examples that follow. AspectJ follows Java's rule that annotations on interfaces are not inherited.6 Programmatic transaction management The Spring Framework provides two means of programmatic transaction management: • Using the TransactionTemplate. See the section called “Load-time weaving with AspectJ in the Spring Framework” for a discussion of load-time weaving with AspectJ. It uses a callback approach. Using the TransactionTemplate The TransactionTemplate adopts the same approach as other Spring templates such as the JdbcTemplate. not the interface (if any) that the class implements. in that the code that is written focuses solely on what the developer wants to do. The @Transactional annotation on a method within the class overrides the default transaction semantics given by the class annotation (if present). you must annotate the implementation class (and/or methods within that class). although exception handling is less cumbersome. 3. 11. The second approach is similar to using the JTA UserTransaction API. using the TransactionTemplate absolutely couples you to Spring's transaction infrastructure and APIs.Spring Framework Note When using this aspect.1 Reference Documentation 344 . The @Transactional annotation on a class specifies the default transaction semantics for the execution of any method in the class. and results in code that is intention driven. To weave your applications with the AnnotationTransactionAspect you must either build your application with AspectJ (see the AspectJ Development Guide) or use load-time weaving.

You then pass an instance of your custom TransactionCallback to the execute(.. and that will use the TransactionTemplate explicitly. } } }). You. } public Object someServiceMethod() { return transactionTemplate. write a TransactionCallback implementation (typically expressed as an anonymous inner class) that contains the code that you need to execute in the context of a transaction. this. } }).execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { updateOperation1(). updateOperation2(). } catch (SomeBusinessExeption ex) { status.) method exposed on the TransactionTemplate. } } If there is no return value.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { updateOperation1().Spring Framework Application code that must execute in a transactional context. } }). public class SimpleService implements Service { // single TransactionTemplate shared amongst all methods in this instance private final TransactionTemplate transactionTemplate. Code within the callback can roll the transaction back by calling the setRollbackOnly() method on the supplied TransactionStatus object: transactionTemplate. use the convenient TransactionCallbackWithoutResult class with an anonymous class as follows: transactionTemplate.execute(new TransactionCallback() { // the code in this method executes in a transactional context public Object doInTransaction(TransactionStatus status) { updateOperation1().notNull(transactionManager. Specifying transaction settings 3.setRollbackOnly().transactionTemplate = new TransactionTemplate(transactionManager)."). as an application developer. // use constructor-injection to supply the PlatformTransactionManager public SimpleService(PlatformTransactionManager transactionManager) { Assert. looks like the following. "The 'transactionManager' argument must not be null. updateOperation2().1 Reference Documentation 345 . return resultOfUpdateOperation2().

notNull(transactionManager. Then.TransactionTemplate"> <property name="isolationLevelName" value="ISOLATION_READ_UNCOMMITTED"/> <property name="timeout" value="30"/> </bean>" Finally. TransactionStatus status = txManager. a different isolation level). instances of the TransactionTemplate class are threadsafe. TransactionTemplate instances do however maintain configuration state. // the transaction settings can be set here explicitly if so desired this. Using the PlatformTransactionManager You can also use the org. using the TransactionDefinition and TransactionStatus objects you can initiate transactions.1 Reference Documentation 346 . so while a number of classes may share a single instance of a TransactionTemplate.PROPAGATION_REQUIRED). this. this.getTransaction(def). Simply pass the implementation of the PlatformTransactionManager you are using to your bean through a bean reference. then you need to create two distinct TransactionTemplate instances..setIsolationLevel(TransactionDefinition. using Spring XML configuration..PlatformTransactionManager directly to manage your transaction.setPropagationBehavior(TransactionDefinition. "The 'transactionManager' argument must not be null. def. the isolation level.springframework. // explicitly setting the transaction name is something that can only be done programmatically def. public SimpleService(PlatformTransactionManager transactionManager) { Assert. roll back.transaction.transactionTemplate = new TransactionTemplate(transactionManager).ISOLATION_READ_UNCOMMITTED). TransactionTemplate instances by default have the default transactional settings. The sharedTransactionTemplate can then be injected into as many services as are required.springframework. and so forth on the TransactionTemplate either programmatically or in configuration.setName("SomeTxName").").Spring Framework You can specify transaction settings such as the propagation mode. and commit. <bean id="sharedTransactionTemplate" class="org.transactionTemplate. The following example shows the programmatic customization of the transactional settings for a specific TransactionTemplate: public class SimpleService implements Service { private final TransactionTemplate transactionTemplate. if a class needs to use a TransactionTemplate with different settings (for example. try { 3.transactionTemplate. in that instances do not maintain any conversational state.transaction. the timeout.setTimeout(30). DefaultTransactionDefinition def = new DefaultTransactionDefinition().support. } } The following example defines a TransactionTemplate with some custom transactional settings. // 30 seconds // and so forth.

When using the Spring Framework. consider using the convenient <tx:jta-transaction-manager/> configuration element. the configuration cost of declarative transaction management is greatly reduced.1 Reference Documentation 347 . Geronimo. for fully supported transaction suspension and further advanced integration. However. Being able to set the transaction name explicitly is also something that can only be done using the programmatic approach to transaction management. 3.8 Application server-specific integration Spring's transaction abstraction generally is application server agnostic. See the JtaTransactionManager Javadocs for details. if your application has numerous transactional operations. using the TransactionTemplate may be a good approach.without any special configuration required. this element automatically detects the underlying server and chooses the best transaction manager available for the platform. you may not want to set up transactional proxies using Spring or any other technology.including GlassFish. and Oracle OC4J. JBoss. Spring's JtaTransactionManager is the standard choice to run on Java EE application servers. Having access to the JTA TransactionManager allows for enhanced transaction semantics. and is known to work on all common servers.Spring Framework // execute your business logic here } catch (MyException ex) { txManager.rollback(status). WebSphere and OC4J. including WebLogic Server. It keeps transaction management out of business logic. Spring's JtaTransactionManager class. with the standard JtaTransactionManager as default fallback. When configured. they are chosen automatically. autodetects the location for the latter object. For example.7 Choosing between programmatic and declarative transaction management Programmatic transaction management is usually a good idea only if you have a small number of transactional operations. Advanced functionality such as transaction suspension works on many servers as well -. On the other hand. and is not difficult to configure. For standard scenarios.commit(status). In this case. rather than EJB CMT. } txManager. 11. which can optionally perform a JNDI lookup for the JTA UserTransaction and TransactionManager objects. which varies by application server. 11. if you have a web application that require transactions only for certain update operations. in particular supporting transaction suspension. BEA WebLogic Server. throw ex. This means that you won't have to configure server-specific adapter classes (as discussed in the following sections) explicitly. and Oracle OC4J -. declarative transaction management is usually worthwhile. Spring ships special adapters for IBM WebSphere. These adapters are discussed in the following sections. Additionally. rather.

0. Used properly.2. providing similar value-adds on OC4J: transaction names and per-transaction isolation levels.0. Oracle OC4J Spring ships a special adapter class for OC4J 10.jta.transaction. Spring-driven transaction suspension (suspend/resume as initiated by PROPAGATION_REQUIRES_NEW) is officially supported by IBM! BEA WebLogic Server On WebLogic Server 9. per-transaction isolation levels.JtaTransactionManager class (or an application server-specific subclass of it) for all your transactional operations. including transaction suspension.0 or above. the recommended Spring JTA transaction manager to use is WebSphereUowTransactionManager.1 Reference Documentation 348 . The special OC4JJtaTransactionManager adapter simply provides value-adds beyond standard JTA. works fine with Spring's JtaTransactionManager on OC4J as well. Otherwise the transaction infrastructure attempts to perform local transactions on resources such as container DataSource instances.1. If you are using global transactions. and a good application server treats them as errors. 11. This special WebLogic-specific subclass of the normal JtaTransactionManager supports the full power of Spring's transaction definitions in a WebLogic-managed transaction environment. you typically would use the WebLogicJtaTransactionManager instead of the stock JtaTransactionManager class.Spring Framework IBM WebSphere On WebSphere 6. you must use the org.1. This class is analogous to the WebLogicJtaTransactionManager class discussed in the previous section.9 and later. the Spring Framework merely provides a straightforward and portable abstraction. The full JTA functionality. 11. This special adapter leverages IBM's UOWManager API. beyond standard JTA semantics: Features include transaction names. Such local transactions do not make sense.springframework.9 Solutions to common problems Use of the wrong transaction manager for a specific DataSource Use the correct PlatformTransactionManager implementation based on your choice of transactional technologies and requirements.1.0. and proper resuming of transactions in all cases.9 and above.19 and later and 6. With this adapter. which is available in WebSphere Application Server 6.3 or later called OC4JJtaTransactionManager.10 Further Resources 3.

• Java Transaction Design Strategies is a book available from InfoQ that provides a well-paced introduction to transactions in Java.Spring Framework For more information about the Spring Framework's transaction support: • Distributed transactions in Spring.1 Reference Documentation 349 . with and without XA is a JavaWorld presentation in which SpringSource's David Syer guides you through seven patterns for distributed transactions in Spring applications. three of them with XA and four without. 3. It also includes side-by-side examples of how to configure and use transactions with both the Spring Framework and EJB3.

JDBC exceptions (including database-specific dialects) are also converted to the same hierarchy. These exceptions wrap the original exception so there is never any risk that one might lose any information as to what might have gone wrong.Spring Framework 12.2 Consistent exception hierarchy Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception.) or convertJdoAccessException() methods respectively. preferably via delegating to SessionFactoryUtils' convertHibernateAccessException(. only in the appropriate layers. The exception hierarchy that Spring provides can be seen below. converting them from proprietary.) 3. meaning that one can perform some operations with JDBC within a consistent programming model. In addition to JDBC exceptions. Hibernate. This allows one to switch between the aforementioned persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.) As mentioned above. (One can still trap and handle exceptions anywhere one needs to though.1 Introduction The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC. Spring can also wrap Hibernate-specific exceptions. to a set of focused runtime exceptions (the same is true for JDO and JPA exceptions). If one uses the interceptor-based classes then the application must care about handling HibernateExceptions and JDOExceptions itself. without having annoying boilerplate catch-and-throw blocks and exception declarations in one's DAOs. The above holds true for the various template classes in Springs support for various ORM frameworks.springframework. These methods convert the exceptions to ones that are compatible with the exceptions in the org. JPA or JDO in a consistent way. (Please note that the class hierarchy detailed in the image shows only a subset of the entire DataAccessException hierarchy. This allows one to handle most persistence exceptions..1 Reference Documentation 350 . sacrificing generic DAO abstraction in terms of exceptions though. which are non-recoverable.dao exception hierarchy. they can simply get thrown too.0). As JDOExceptions are unchecked. checked exceptions (in the case of versions of Hibernate prior to Hibernate 3. DAO support 12. 12.

for example. @Resource or @PersistenceContext annotations. } Any DAO or repository implementation will need to access to a persistence resource. depending on the persistence technology used.1 Reference Documentation 351 . a JPA-based repository will need access to an EntityManager.. a JDBC-based repository will need access to a JDBC DataSource. @Repository public class SomeMovieFinder implements MovieFinder { // . } If you are using the classic Hibernate APIs than you can inject the SessionFactory: 3.. // . The easiest way to accomplish this is to have this resource dependency injected using one of the @Autowired. This annotation also allows the component scanning support to find and configure your DAOs and repositories without having to provide XML configuration entries for them. Here is an example for a JPA repository: @Repository public class JpaMovieFinder implements MovieFinder { @PersistenceContext private EntityManager entityManager.3 Annotations used for configuring DAO or Repository classes The best way to guarantee that your Data Access Objects (DAOs) or repositories provide exception translation is to use the @Repository annotation...Spring Framework 12. @Inject..

} Note Please see the specific coverage of each persistence technology for details on how to configure the application context to take advantage of these annotations... } Last example we will show here is for typical JDBC support. 3.. } // .jdbcTemplate = new JdbcTemplate(dataSource). @Autowired public void init(DataSource dataSource) { this. @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory..1 Reference Documentation 352 . You would have the DataSource injected into an initialization method where you would create a JdbcTemplate and other data access support classes like SimpleJdbcCall etc using this DataSource. @Repository public class JdbcMovieFinder implements MovieFinder { private JdbcTemplate jdbcTemplate. } // .Spring Framework @Repository public class HibernateMovieFinder implements MovieFinder { private SessionFactory sessionFactory.

the application developer.1 Reference Documentation 353 .0-compliant driver. and the RDBMS Object style takes a more object-oriented approach similar to that of JDO Query design. In addition to three flavors of the JdbcTemplate. Open the connection.Spring Framework 13.who does what? Action Define connection parameters. Declare parameters and provide parameter values Prepare and execute the statement. statement and resultset. Close the connection. Table 13.1 Introduction to Spring Framework JDBC The value-add provided by the Spring Framework JDBC abstraction is perhaps best shown by the sequence of actions outlined in the table below.0 driver. Note 3. X X X X X X X X X Spring You X The Spring Framework takes care of all the low-level details that can make JDBC such a tedious API to develop with. a new SimpleJdbcInsert and SimplejdbcCall approach optimizes database metadata. Handle transactions.1. Once you start using one of these approaches. Do the work for each iteration. The table shows what actions Spring will take care of and which actions are the responsibility of you. Choosing an approach for JDBC database access You can choose among several approaches to form the basis for your JDBC database access. you can still mix and match to include a feature from a different approach. Specify the SQL statement. and some advanced features require a JDBC 3. All approaches require a JDBC 2. Spring JDBC . Data access with JDBC 13. Set up the loop to iterate through the results (if any). Process any exception.

springframework. and support.jdbc. and Section 13.jdbc.4. Package hierarchy The Spring Framework's JDBC abstraction framework consists of four different packages. See Section 13. This approach simplifies coding so that you only need to provide the name of the table or procedure and provide a map of parameters matching the column names. you will have to provide explicit configuration of the parameters. • SimpleJdbcInsert and SimpleJdbcCall optimize database metadata to limit the amount of necessary configuration.core package contains the JdbcTemplate class and its various callback interfaces.jdbc. execute methods can be called multiple times with various parameter values passed in. “Using the JDBC core classes to control basic JDBC processing and error handling”.jdbc.simple contains the SimpleJdbcTemplate class and the related SimpleJdbcInsert and SimpleJdbcCall classes.core. “Simplifying JDBC operations with the SimpleJdbc classes” The org.jdbc. A subpackage named org. declare parameters.springframework. datasource. The org. object. “JDBC batch operations”.5. This approach provides better documentation and ease of use when you have multiple parameters for an SQL statement. • SimpleJdbcTemplate combines the most frequently used operations of JdbcTemplate and NamedParameterJdbcTemplate. This "lowest level" approach and all others use a JdbcTemplate under the covers. namely core. • NamedParameterJdbcTemplate wraps a JdbcTemplate to provide named parameters instead of the traditional JDBC "?" placeholders.springfamework.0 updates all of the following approaches with Java 5 support such as generics and varargs.datasource package contains a utility class for easy DataSource access.namedparam contains the NamedParameterJdbcTemplate class and the related support classes. plus a variety of related classes. • JdbcTemplate is the classic Spring JDBC approach and the most popular. A subpackage named org. Once you do that. This only works if the database provides adequate metadata. and all are updated with Java 5 support such as generics and varargs. This approach is modeled after JDO Query wherein you define your query string. If the database doesn't provide this metadata. Section 13.1 Reference Documentation 354 . SqlUpdate and StoredProcedure requires you to create reusable and thread-safe objects during initialization of your data access layer. Another subpackage named org.Spring Framework Spring 3.2.springframework.core.springframework. and compile the query.embedded provides support for creating in-memory 3.datasource. and various simple DataSource implementations that can be used for testing and running unmodified JDBC code outside of a Java EE container. • RDBMS Objects including MappingSqlQuery.

8. giving them a clearly defined contract.Spring Framework database instances using Java database engines such as HSQL and H2. Exceptions thrown during JDBC processing are translated to exceptions defined in the org. This higher level of JDBC abstraction depends on the lower-level abstraction in the org. updates.object package contains classes that represent RDBMS queries. See Section 13. which helps you avoid common errors such as forgetting to close the connection. providing SQL and any necessary parameters. The org. update statements and stored procedure calls. The PreparedStatementCreator callback interface creates a prepared statement given a Connection provided by this class. In the first case the bean is given to the service directly.jdbc.dao package. The RowCallbackHandler interface extracts values from each row of a ResultSet. It also catches JDBC exceptions and translates them to the generic. See Section 13.This approach is modeled by JDO. “Modeling JDBC operations as Java objects”. “Controlling database connections” and Section 13. although of course objects returned by queries are “disconnected” from the database. performs iteration over ResultSets and extraction of returned parameter values.jdbc.6. The same is true for the CallableStatementCreator interface. 13.springframework. leaving application code to provide SQL and extract results. See the section called “SQLExceptionTranslator”. The JdbcTemplate class executes SQL queries. more informative.2 Using the JDBC core classes to control basic JDBC processing and error handling JdbcTemplate The JdbcTemplate class is the central class in the JDBC core package.jdbc.springframework.support package provides SQLException translation functionality and some utility classes.springframework. and stored procedures as thread safe. reusable objects. you only need to implement callback interfaces. “Embedded database support” The org. Note The DataSource should always be configured as a bean in the Spring IoC container.core package. in the second case it is given to the 3. When you use the JdbcTemplate for your code. This means that code using the Spring JDBC abstraction layer does not need to implement JDBC or RDBMS-specific error handling. or be configured in a Spring IoC container and given to DAOs as a bean reference. All translated exceptions are unchecked.springframework.dao package. which creates callable statements.3. exception hierarchy defined in the org. The JdbcTemplate can be used within a DAO implementation through direct instantiation with a DataSource reference.springframework. It performs the basic tasks of the core JDBC workflow such as statement creation and execution. which gives you the option of catching the exceptions from which you can recover while allowing other exceptions to be propagated to the caller. It handles the creation and release of resources.1 Reference Documentation 355 .

new Object[]{1212L}. but it may be different if you are using a custom subclass of the JdbcTemplate class).getString("last_name")).jdbcTemplate. actor. see the attendant Javadocs for that. int rowNum) throws SQLException { Actor actor = new Actor().Spring Framework prepared template. actor.jdbcTemplate.jdbcTemplate. return actor. int rowNum) throws SQLException { Actor actor = new Actor(). return actor.getString("last_name")).getString("first_name")). new Object[]{1212L}.queryForObject( "select first_name.jdbcTemplate. "Joe"). new RowMapper<Actor>() { public Actor mapRow(ResultSet rs. actor. actor.jdbcTemplate. These examples are not an exhaustive list of all of the functionality exposed by the JdbcTemplate.1 Reference Documentation 356 . 3. A simple query using a bind variable: int countOfActorsNamedJoe = this.setFirstName(rs.getString("first_name")). Querying (SELECT) Here is a simple query for getting the number of rows in a relation: int rowCount = this.class).setFirstName(rs. Examples of JdbcTemplate class usage This section provides some examples of JdbcTemplate class usage.query( "select first_name.setLastName(rs.setLastName(rs. new RowMapper<Actor>() { public Actor mapRow(ResultSet rs. Querying and populating a single domain object: Actor actor = this. String. } }).queryForObject( "select last_name from t_actor where id = ?". last_name from t_actor where id = ?".queryForInt( "select count(*) from t_actor where first_name = ?". last_name from t_actor". All SQL issued by this class is logged at the DEBUG level under the category corresponding to the fully qualified class name of the template instance (typically JdbcTemplate. Querying for a String: String lastName = this. Querying and populating a number of domain objects: List<Actor> actors = this.queryForInt("select count(*) from t_actor").

and extract them out into a single class (typically a static inner class) that can then be referenced by DAO methods as needed. update and delete operations. For example.1 Reference Documentation 357 . this.update( "delete from actor where id = ?".jdbcTemplate. this. ?)".query( "select first_name.getString("last_name")). last_name from t_actor".jdbcTemplate. "Banjo". actor. and as such the method is often used for DDL statements.update( "insert into t_actor (first_name. return actor.jdbcTemplate. "Leonor". new ActorMapper()). it would make sense to remove the duplication present in the two RowMapper anonymous inner classes. Parameter values are usually provided as var args or alternatively as an object array. It is heavily overloaded with variants taking callback interfaces. actor. binding variable arrays.execute("create table mytable (id integer.) method to perform insert.update( "call SUPPORT. this.valueOf(unionId)). last_name) values (?.REFRESH_ACTORS_SUMMARY(?)".getString("first_name")). and so on.update( "update t_actor set = ? where id = ?". this.setLastName(rs.Spring Framework } }).jdbcTemplate. } } Updating (INSERT/UPDATE/DELETE) with jdbcTemplate You use the update(..) method to execute any arbitrary SQL. int rowNum) throws SQLException { Actor actor = new Actor(). "Watling"). Long. More sophisticated stored procedure support is covered later.jdbcTemplate. Long.jdbcTemplate. it may be better to write the last code snippet as follows: public List<Actor> findAllActors() { return this. The following example invokes a simple stored procedure. 3.setFirstName(rs. } private static final class ActorMapper implements RowMapper<Actor> { public Actor mapRow(ResultSet rs.. name varchar(100))").valueOf(actorId)). Other jdbcTemplate operations You can use the execute(. this. 5276L). If the last two snippets of code actually existed in the same application.

} The corresponding configuration might look like this.org/schema/beans/spring-beans-3.properties"/> </beans> An alternative to explicit configuration is to use component-scanning and annotation support for dependency injection. public void setDataSource(DataSource dataSource) { this. but this state is not conversational state. The JdbcTemplate is stateful. in that it maintains a reference to a DataSource.Spring Framework JdbcTemplate best practices Instances of the JdbcTemplate class are threadsafe once configured.springframework. In this case you annotate the class with @Repository (which makes it a candidate for component-scanning) and annotate the DataSource setter method with @Autowired.springframework..org/schema/context http://www.password}"/> </bean> <context:property-placeholder location="jdbc.driverClassName}"/> <property name="url" value="${jdbc.xsd"> <bean id="corporateEventDao" class="com.springframework.org/schema/beans" xmlns:xsi="http://www.example. } // JDBC-backed implementations of the methods on the CorporateEventDao follow.springframework.org/schema/context" xsi:schemaLocation=" http://www. This leads to DAOs that look in part like the following: public class JdbcCorporateEventDao implements CorporateEventDao { private JdbcTemplate jdbcTemplate.username}"/> <property name="password" value="${jdbc.jdbcTemplate = new JdbcTemplate(dataSource).BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.dbcp. <?xml version="1. the JdbcTemplate is created in the setter for the DataSource. This is important because it means that you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs (or repositories).org/schema/context/spring-context-3.0.0. A common practice when using the JdbcTemplate class (and the associated SimpleJdbcTemplate and NamedParameterJdbcTemplate classes) is to configure a DataSource in your Spring configuration file.springframework.JdbcCorporateEventDao"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="dataSource" class="org.xsd http://www.org/2001/XMLSchema-instance" xmlns:context="http://www.w3..apache.0" encoding="UTF-8"?> <beans xmlns="http://www.url}"/> <property name="username" value="${jdbc.1 Reference Documentation 358 .commons. @Repository 3.org/schema/beans http://www.springframework. and then dependency-inject that shared DataSource bean into your DAO classes.

which requires multiple DataSources.apache.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc. and subsequently multiple differently configured JdbcTemplates.properties"/> </beans> If you are using Spring's JdbcDaoSupport class.commons.xsd"> <!-..org/schema/beans/spring-beans-3.springframework. You may want multiple JdbcTemplate instances if your application accesses multiple databases. } // JDBC-backed implementations of the methods on the CorporateEventDao follow.test" /> <bean id="dataSource" class="org.springframework.. The JdbcDaoSupport class is provided as a convenience only.. The NamedParameterJdbcTemplate class wraps a JdbcTemplate.springframework. Regardless of which of the above template initialization styles you choose to use (or not).) method from the JdbcDaoSupport class.jdbcTemplate = new JdbcTemplate(dataSource).w3.org/schema/beans" xmlns:xsi="http://www.org/schema/context" xsi:schemaLocation=" http://www.Spring Framework public class JdbcCorporateEventDao implements CorporateEventDao { private JdbcTemplate jdbcTemplate.springframework.1 Reference Documentation 359 .driverClassName}"/> <property name="url" value="${jdbc. it is seldom necessary to create a new instance of a JdbcTemplate class each time you want to execute SQL.xsd http://www.org/schema/context/spring-context-3.org/schema/context http://www. and delegates to 3.org/2001/XMLSchema-instance" xmlns:context="http://www.url}"/> <property name="username" value="${jdbc. then your sub-class inherits a setDataSource(.Scans within the base package of the application for @Components to configure as beans --> <context:component-scan base-package="org. NamedParameterJdbcTemplate The NamedParameterJdbcTemplate class adds support for programming JDBC statements using named parameters. Once configured. You can choose whether to inherit from this class.springframework.0. a JdbcTemplate instance is threadsafe.org/schema/beans http://www.docs.0" encoding="UTF-8"?> <beans xmlns="http://www. @Autowired public void setDataSource(DataSource dataSource) { this.springframework.password}"/> </bean> <context:property-placeholder location="jdbc. and your various JDBC-backed DAO classes extend from it.username}"/> <property name="password" value="${jdbc. } The corresponding XML configuration file would look like the following: <?xml version="1.0.springframework.dbcp. as opposed to programming JDBC statements using only classic placeholder ('?') arguments.

. } One nice feature related to the NamedParameterJdbcTemplate (and existing in the same Java package) is the SqlParameterSource interface. Alternatively. // some JDBC-backed DAO class. return namedParameterJdbcTemplate. This section describes only those areas of the NamedParameterJdbcTemplate class that differ from the JdbcTemplate itself. The following example shows the use of the Map-based style. The MapSqlParameterSource class is a very simple implementation that is simply an adapter around a java.The remaining methods exposed by the NamedParameterJdbcOperations and implemented by the NamedParameterJdbcTemplate class follow a similar pattern and are not covered here. Map namedParameters = Collections. namely. programming JDBC statements using named parameters. namedParameters). public void setDataSource(DataSource dataSource) { this. // some JDBC-backed DAO class. } public int countOfActorsByFirstName(String firstName) { String sql = "select count(*) from T_ACTOR where first_name = :first_name". SqlParameterSource namedParameters = new MapSqlParameterSource("first_name". private NamedParameterJdbcTemplate namedParameterJdbcTemplate. firstName). You have already seen an example of an implementation of this interface in one of the previous code snippet (the MapSqlParameterSource class).queryForInt(sql.namedParameterJdbcTemplate.singletonMap("first_name". public void setDataSource(DataSource dataSource) { this. An SqlParameterSource is a source of named parameter values to a NamedParameterJdbcTemplate...Map. private NamedParameterJdbcTemplate namedParameterJdbcTemplate. Another SqlParameterSource implementation is the BeanPropertySqlParameterSource 3.1 Reference Documentation 360 . } public int countOfActorsByFirstName(String firstName) { String sql = "select count(*) from T_ACTOR where first_name = :first_name". namedParameters).queryForInt(sql.Spring Framework the wrapped JdbcTemplate to do much of its work.. return this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource). } Notice the use of the named parameter notation in the value assigned to the sql variable.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource). you can pass along named parameters and their corresponding values to a NamedParameterJdbcTemplate instance by using the Map-based style.util. firstName). where the keys are the parameter names and the values are the parameter values. and the corresponding value that is plugged into the namedParameters variable (of type MapSqlParameterSource).

an instance of a class that adheres to the JavaBean conventions). namedParameters).. } Remember that the NamedParameterJdbcTemplate class wraps a classic JdbcTemplate template. } // setters omitted. and uses the properties of the wrapped JavaBean as the source of named parameter values.firstName. } public Long getId() { return this..Spring Framework class. if you need access to the wrapped JdbcTemplate instance to access functionality only present in the JdbcTemplate class.. public String getFirstName() { return this.queryForInt(sql. } public String getLastName() { return this. public class Actor { private Long id. See also the section called “JdbcTemplate best practices” for guidelines on using the NamedParameterJdbcTemplate class in the context of an application. This class wraps an arbitrary JavaBean (that is. } public int countOfActors(Actor exampleActor) { // notice how the named parameters match the properties of the above 'Actor' class String sql = "select count(*) from T_ACTOR where first_name = :firstName and last_name = :lastName".1 Reference Documentation 361 . SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(exampleActor). private String lastName. private NamedParameterJdbcTemplate namedParameterJdbcTemplate..namedParameterJdbcTemplate. you can use the getJdbcOperations() method to access the wrapped JdbcTemplate through the JdbcOperations interface.lastName. } // some JDBC-backed DAO class. return this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource). private String firstName.id. Note 3. SimpleJdbcTemplate The SimpleJdbcTemplate class wraps the classic JdbcTemplate and leverages Java 5 language features such as varargs and autoboxing. public void setDataSource(DataSource dataSource) { this.

private SimpleJdbcTemplate simpleJdbcTemplate.getLong("id")). private JdbcTemplate jdbcTemplate. int rowNum) throws SQLException { Actor actor = new Actor(). first_name. However. because the SimpleJdbcTemplate was designed for Java 5. actor. mapper). The value-add of the SimpleJdbcTemplate class in the area of syntactic-sugar is best illustrated with a before-and-after example. RowMapper<Actor> mapper = new RowMapper<Actor>() { public Actor mapRow(ResultSet rs. new Object[] {specialty.setFirstName(rs. actor. last_name from T_ACTOR" + " where specialty = ? and age = ?". Also.getLong("id")). int age) { String sql = "select id.setLastName(rs. followed by a code snippet that does the same job with the SimpleJdbcTemplate.setId(rs.1 Reference Documentation 362 . } Here is the same method. // SimpleJdbcTemplate-style.0. public void setDataSource(DataSource dataSource) { this. the SimpleJdbcTemplate provides a simpler API that works best when you do not need access to all the methods that the JdbcTemplate offers.setFirstName(rs. } public Actor findActor(String specialty.getString("first_name")). int age) { String sql = "select id. // classic JdbcTemplate-style. RowMapper<Actor> mapper = new RowMapper<Actor>() { public Actor mapRow(ResultSet rs..jdbcTemplate = new JdbcTemplate(dataSource). actor. int rowNum) throws SQLException { Actor actor = new Actor().. actor.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource).. it has more methods that take advantage of varargs due to different ordering of the parameters.setId(rs. first_name.getString("first_name")). the original JdbcTemplate also supports Java 5-enhanced syntax with generics and varargs. // notice the wrapping up of the argumenta in an array return (Actor) jdbcTemplate. return actor. actor. actor.setLastName(rs. The next code snippet shows data access code that uses the classic JdbcTemplate.getString("last_name")).. age}.Spring Framework In Spring 3. } }. } }. public void setDataSource(DataSource dataSource) { this. with the SimpleJdbcTemplate. 3.queryForObject(sql.getString("last_name")). } public Actor findActor(String specialty. last_name from T_ACTOR" + " where specialty = ? and age = ?". return actor.

It is more precise than the SQLState implementation.simpleJdbcTemplate.xml. using SQLState codes for JDBC) or proprietary (for example.DataAccessException.springframework. SQLErrorCodeSQLExceptionTranslator is the implementation of SQLExceptionTranslator that is used by default. Normally the provided concrete SQLErrorCodeSQLExceptionTranslator is used so this rule does not apply. Implementations can be generic (for example.dao. This implementation uses specific vendor codes. This class is created and populated by an SQLErrorCodesFactory which as the name suggests is a factory for creating SQLErrorCodes based on the contents of a configuration file named sql-error-codes.Spring Framework // notice the use of varargs since the parameter values now come // after the RowMapper parameter return this. you can always access the underlying JdbcTemplate by calling the getJdbcOperations() method on the SimpleJdbcTemplate. The error code translations are based on codes held in a JavaBean type class called SQLErrorCodes. specialty. Note The SimpleJdbcTemplate class only offers a subset of the methods exposed on the JdbcTemplate class. If you need to use a method from the JdbcTemplate that is not defined on the SimpleJdbcTemplate. It only applies if 3. which then allows you to invoke the method that you want. The only downside is that the methods on the JdbcOperations interface are not generic. } See the section called “JdbcTemplate best practices” for guidelines on how to use the SimpleJdbcTemplate class in the context of an application. using Oracle error codes) for greater precision. Any custom translation implemented by a subclass. so you are back to casting and so on. This file is populated with vendor codes and based on the DatabaseProductName taken from the DatabaseMetaData. The codes for the acual database you are using are used.xml from the classpath and the matching SQLErrorCodes instance is located based on the database name from the database metadata of the database in use. which is agnostic in regard to data access strategy.queryForObject(sql.1 Reference Documentation 363 . They are looked up in a file named sql-error-codes. The SQLErrorCodeSQLExceptionTranslator applies matching rules in the following sequence: Note The SQLErrorCodesFactory is used by default to define Error codes and custom exception translations. 1. age). SQLExceptionTranslator SQLExceptionTranslator is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own org. mapper.

update( "update orders" + " set shipping_charge = shipping_charge * ? / 100" + " where id = ?" pct.jdbcTemplate = new JdbcTemplate().setExceptionTranslator(tr).setDataSource(dataSource). 5. tr. String sql. the specific error code -12345 is translated and other errors are left to be translated by the default translator implementation. it is necessary to pass it to the JdbcTemplate through the method setExceptionTranslator and to use this JdbcTemplate for all of the data access processing where this translator is needed.jdbcTemplate. public void setDataSource(DataSource dataSource) { // create a JdbcTemplate and set data source this. // create a custom translator and set the DataSource for the default translation lookup CustomSQLErrorCodesTranslator tr = new CustomSQLErrorCodesTranslator(). this. Any custom implementation of the SQLExceptionTranslator interface that is provided as the customSqlExceptionTranslator property of the SQLErrorCodes class. long pct) { // use the prepared JdbcTemplate for this update this.1 Reference Documentation 364 . The list of instances of the CustomSQLErrorCodesTranslation class. Use the fallback translator. Executing statements 3.getErrorCode() == -12345) { return new DeadlockLoserDataAccessException(task. SQLException sqlex) { if (sqlex. provided for the customTranslations property of the SQLErrorCodes class. orderId).setDataSource(dataSource).jdbcTemplate. } The custom translator is passed a data source in order to look up the error codes in sql-error-codes. 3. You can extend SQLErrorCodeSQLExceptionTranslator: public class CustomSQLErrorCodesTranslator extends SQLErrorCodeSQLExceptionTranslator { protected DataAccessException customTranslate(String task. Here is an example of how this custom translator can be used: private JdbcTemplate jdbcTemoplate. } public void updateShippingCharge(long orderId. 2. } } In this example. } return null. If this translation is not available then the next fallback translator is the SQLStateSQLExceptionTranslator. sqlex). 4. To use this custom translator.xml.jdbcTemplate. this. SQLExceptionSubclassTranslator is the default fallback translator.Spring Framework you have actually provided a subclass implementation. are searched for a match. Error code matching is applied.

The most generic method is queryForList(.DataSource.execute("create table mytable (id integer.jdbcTemplate = new JdbcTemplate(dataSource). The following example shows what you need to include for a minimal but fully functional class that creates a new table: import javax.). Here is an example that contains two query methods.jdbcTemplate. import org. queryForLong(.core.springframework.queryForInt("select count(*) from mytable"). } public String getName() { return (String) this.) which returns a List where each entry is a Map with each entry in the map representing the column value for that row. public void setDataSource(DataSource dataSource) { this..).) or queryForObject(.jdbcTemplate. several methods return a list with an entry for each row that the query returned. one for an int and one that queries for a String.class). use queryForInt(.springframework..JdbcTemplate. then an InvalidDataAccessApiUsageException is thrown. If you add a 3. including the convenience methods that are provided with the JdbcTemplate. } public void setDataSource(DataSource dataSource) { this.jdbc. String..Spring Framework Executing an SQL statement requires very little code. public class RunAQuery { private JdbcTemplate jdbcTemplate.jdbcTemplate = new JdbcTemplate(dataSource). public void setDataSource(DataSource dataSource) { this.core. To retrieve a count or a specific value from one row. } public void doExecute() { this.jdbcTemplate. The latter converts the returned JDBC Type to the Java class that is passed in as an argument. } public int getCount() { return this. } } Running queries Some query methods return a single value.DataSource.JdbcTemplate. name varchar(100))"). public class ExecuteAStatement { private JdbcTemplate jdbcTemplate. If the type conversion is invalid.sql. } } In addition to the single result query methods. import javax.1 Reference Documentation 365 ..jdbc.sql. You need a DataSource and a JdbcTemplate.dataSource = dataSource.queryForObject("select name from mytable". import org.

queryForList("select * from mytable").springframework. } } Retrieving auto-generated keys An update() convenience method supports the retrieval of primary keys generated by the database. The method takes a PreparedStatementCreator as its first argument. } public void setName(int id.6 of the specification for details. import org.jdbc. name.jdbcTemplate.jdbcTemplate = new JdbcTemplate(dataSource). public void setDataSource(DataSource dataSource) { this. id=2}] Updating the database The following example shows a column updated for a certain primary key. The other argument is a KeyHolder. 3.0 standard. and this is the way the required insert statement is specified.JdbcTemplate.DataSource. id). import javax. public class ExecuteAnUpdate { private JdbcTemplate jdbcTemplate. id=1}. see Chapter 13. {name=Mary. Thus primitives should be wrapped in the primitive wrapper classes explicitly or using auto-boxing. There is not a standard single way to create an appropriate PreparedStatement (which explains why the method signature is the way it is). Object>> getList() { return this.Spring Framework method to the above example to retrieve a list of all the rows. } public List<Map<String. String name) { this. In this example. This support is part of the JDBC 3. The following example works on Oracle but may not work on other platforms: final String INSERT_SQL = "insert into my_test (name) values(?)".jdbcTemplate = new JdbcTemplate(dataSource).1 Reference Documentation 366 . which contains the generated key on successful return from the update. } The list returned would look something like this: [{name=Bob. public void setDataSource(DataSource dataSource) { this.core.update( "update mytable set name = ? where id = ?".jdbcTemplate. The parameter values can be passed in as varargs or alternatively as an array of objects.sql. it would look like this: private JdbcTemplate jdbcTemplate. an SQL statement has placeholders for row parameters.

return ps. provide a URL that varies between JDBC drivers. you obtain a data source from JNDI or you configure your own with a connection pool implementation provided by a third party. but you do not necessarily have to know how the production data source is configured. It allows a container or a framework to hide connection pooling and transaction management issues from the application code. Popular implementations are Apache Jakarta Commons DBCP and C3P0.) Then provide a username and a password to connect to the database.jdbcDriver").getKey() now contains the generated key 13.hsqldb. jdbcTemplate. keyHolder). name). Note Only use the DriverManagerDataSource class should only be used for testing purposes since it does not provide pooling and will perform poorly when multiple requests for a connection are made.setDriverClassName("org. This section uses Spring's DriverManagerDataSource implementation. // keyHolder. you need not know details about how to connect to the database. You most likely fill both roles as you develop and test code. and several additional implementations are covered later. 3.update( new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection. When using Spring's JDBC layer. Next. A DataSource is part of the JDBC specification and is a generalized connection factory. (Consult the documentation for your driver for the correct value.Spring Framework final String name = "Rob". KeyHolder keyHolder = new GeneratedKeyHolder(). } }. Implementations in the Spring distribution are meant only for testing purposes and do not provide pooling.setString(1. new String[] {"id"}).3 Controlling database connections DataSource Spring obtains a connection to the database through a DataSource. Here is an example of how to configure a DriverManagerDataSource in Java code: DriverManagerDataSource dataSource = new DriverManagerDataSource(). You obtain a connection with DriverManagerDataSource as you typically obtain a JDBC connection.prepareStatement(INSERT_SQL. As a developer. dataSource. ps. that is the responsibility of the administrator that sets up the datasource.1 Reference Documentation 367 . Specify the fully qualified classname of the JDBC driver so that the DriverManager can load the driver class.

url}"/> <property name="username" value="${jdbc. DataSourceTransactionManager. dataSource.jdbc. To learn about more options that help control the pooling features.mchange.driverClassName}"/> <property name="jdbcUrl" value="${jdbc.dbcp.driverClassName}"/> <property name="url" value="${jdbc.setPassword("").username}"/> <property name="password" value="${jdbc.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.springframework.c3p0.Spring Framework dataSource.setUrl("jdbc:hsqldb:hsql://localhost:").commons.url}"/> <property name="user" value="${jdbc.properties"/> The following examples show the basic connectivity and configuration for DBCP and C3P0.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.properties"/> DataSourceUtils The DataSourceUtils class is a convenient and powerful helper class that provides static methods to obtain connections from JNDI and close connections if necessary. dataSource. SmartDataSource The SmartDataSource interface should be implemented by classes that can provide a connection to a relational database.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <context:property-placeholder location="jdbc.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc. It supports thread-bound connections with.properties"/> C3P0 configuration: <bean id="dataSource" class="com.driverClassName}"/> <property name="url" value="${jdbc.setUsername("sa").password}"/> </bean> <context:property-placeholder location="jdbc. Here is the corresponding XML configuration: <bean id="dataSource" class="org. see the product documentation for the respective connection pooling implementations.username}"/> <property name="password" value="${jdbc.apache.1 Reference Documentation 368 . for example.datasource.url}"/> <property name="username" value="${jdbc.password}"/> </bean> <context:property-placeholder location="jdbc.v2. DBCP configuration: <bean id="dataSource" class="org. It extends the DataSource interface to allow classes using it to query whether the 3.

Pool-assuming Connection. it is similar to a transactional JNDI DataSource as provided by a Java EE server. However. in conjunction with a simple JNDI environment. either as a DataSource bean in a Spring IoC container. In this respect. that it is almost always preferable to use such a connection pool over DriverManagerDataSource. You extend the AbstractDataSource class if you are writing your own DataSource implementation. this is not multi-threading capable. 3. Obviously. set the suppressClose property to true. or in conjunction with a simple JNDI environment. For example. Be aware that you will not be able to cast this to a native Oracle Connection or the like anymore. as when using persistence tools. If any client code calls close in the assumption of a pooled connection. In contrast to DriverManagerDataSource. DriverManagerDataSource The DriverManagerDataSource class is an implementation of the standard DataSource interface that configures a plain JDBC driver through bean properties. AbstractDataSource AbstractDataSource is an abstract base class for Spring's DataSource implementations that implements code that is common to all DataSource implementations. This is primarily a test class. it reuses the same connection all the time. This implementation is useful for test and stand-alone environments outside of a Java EE container. avoiding excessive creation of physical connections. so any DataSource-aware persistence code should work. which wraps that target DataSource to add awareness of Spring-managed transactions. it enables easy testing of code outside an application server. even in a test environment. SingleConnectionDataSource The SingleConnectionDataSource class is an implementation of the SmartDataSource interface that wraps a single Connection that is not closed after each use.Spring Framework connection should be closed after a given operation. using JavaBean-style connection pools such as commons-dbcp is so easy. TransactionAwareDataSourceProxy TransactionAwareDataSourceProxy is a proxy for a target DataSource.close() calls will simply close the connection.1 Reference Documentation 369 . and returns a new Connection every time. This setting returns a close-suppressing proxy wrapping the physical connection. This usage is efficient when you know that you will reuse a connection.

) method for each created statement. All framework classes like JdbcTemplate use this strategy implicitly. To gain access to the native objects you can configure your JdbcTemplate or OracleLobHandler with a NativeJdbcExtractor.Spring Framework Note It is rarely desirable to use this class.dao exceptions instead of checked SQLExceptions. and timeouts that get applied as appropriate JDBC statement query timeouts. application code must either use JdbcTemplate or call the DataSourceUtils. if you stick to the required connection lookup pattern.it can thus be used in any case. Statement and ResultSet objects with its own wrapper objects. If not used with this transaction manager. it's possible to still have this code be usable. The NativeJdbcExtractor comes in a variety of flavors to match your execution environment: • SimpleNativeJdbcExtractor 3. (See the TransactionAwareDataSourceProxy Javadocs for more details.) DataSourceTransactionManager The DataSourceTransactionManager class is a PlatformTransactionManager implementation for single JDBC datasources. Switching between both is just a matter of configuration. It binds a JDBC connection from the specified data source to the currently executing thread. JTA does not support custom isolation levels! NativeJdbcExtractor Sometimes you need to access vendor specific JDBC methods that differ from the standard JDBC API. This implementation can be used instead of JtaTransactionManager in the single resource case.applyTransactionTimeout(. such as JdbcTemplate or DataSourceUtils. as it does not require the container to support JTA.getConnection(DataSource) instead of Java EE's standard DataSource. To support the latter.1 Reference Documentation 370 .. It is generally preferable to write your own new code using the higher level abstractions for resource management. and at the same time have this code participating in Spring managed transactions. Application code is required to retrieve the JDBC connection through DataSourceUtils. potentially allowing for one thread connection per data source. In this case. The DataSourceTransactionManager class supports custom isolation levels. except when already existing code that must be called and passed a standard JDBC DataSource interface implementation. This can be problematic if you are running in an application server or with a DataSource that wraps the Connection. It throws unchecked org. the lookup strategy behaves exactly like the common one .getConnection.springframework.

ps.get(i).setString(1. actors. public void setDataSource(DataSource dataSource) { this.getLastName()).1 Reference Documentation 371 . int i) throws SQLException { ps.get(i). ps. BatchPreparedStatementSetter. By grouping updates into batches you limit the number of round trips to the database. The entire list is used as the batch in this example: public class JdbcActorDao implements ActorDao { private JdbcTemplate jdbcTemplate. This section covers batch processing using both the JdbcTemplate and the SimpleJdbcTemplate. and passing that in as the second parameter in your batchUpdate method call. The following example updates the actor table based on entries in a list.jdbcTemplate = new JdbcTemplate(dataSource). Use the getBatchSize method to provide the size of the current batch. } public int[] batchUpdate(final List<Actor> actors) { int[] updateCounts = jdbcTemplate. Basic batch operations with the JdbcTemplate You accomplish JdbcTemplate batch processing by implementing two methods of a special interface. See the Javadocs for more details. } public int getBatchSize() { return actors. 13.longValue()). actors. last_name = ? where id = ?".getFirstName()).getId(). } } ).Spring Framework • C3P0NativeJdbcExtractor • CommonsDbcpNativeJdbcExtractor • JBossNativeJdbcExtractor • WebLogicNativeJdbcExtractor • WebSphereNativeJdbcExtractor • XAPoolNativeJdbcExtractor Usually the SimpleNativeJdbcExtractor is sufficient for unwrapping a Connection object in most environments. actors.4 JDBC batch operations Most JDBC drivers provide improved performance if you batch multiple calls to the same prepared statement.setString(2. 3. This method will be called the number of times that you specified in the getBatchSize call.setLong(3. new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps.batchUpdate( "update t_actor set first_name = ?. Use the setValues method to set the values for the parameters of the prepared statement.size().get(i).

} // } .. The same example using classic JDBC "?" placeholders: public class JdbcActorDao implements ActorDao { private JdbcTemplate jdbcTemplate. you provide all parameter values in the call as a list. which allows you to interrupt a batch once the input source is exhausted. Batch operations with a List of objects Both the JdbcTemplate and the NamedParameterJdbcTemplate provides an alternate way of providing the batch update. The framework loops over these values and uses an internal prepared statement setter. batch).toArray()). additional methods If you are processing a stream of updates or reading from a file. but the last batch might not have that number of entries. In this case you can use the InterruptibleBatchPreparedStatementSetter interface. one entry for each member of the batch.createBatch(actors.jdbcTemplate = new JdbcTemplate(dataSource)... int[] updateCounts = namedParameterJdbcTemplate. The API varies depending on whether you use named parameters.. } 3. then you might have a preferred batch size. } public int[] batchUpdate(final List<Actor> actors) { SqlParameterSource[] batch = SqlParameterSourceUtils.Spring Framework return updateCounts. For the named parameters you provide an array of SqlParameterSource. and they must be in the same order as they are defined in the SQL statement.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource). The isBatchExhausted method allows you to signal the end of the batch. public void setDataSource(DataSource dataSource) { this. return updateCounts. you pass in a list containing an object array with the update values. last_name = :lastName where id = :id". public void setDataSource(DataSource dataSource) { this. This example shows a batch update using named parameters: public class JdbcActorDao implements ActorDao { private NamedParameterTemplate namedParameterJdbcTemplate. You can use the SqlParameterSource.batchUpdate( "update t_actor set first_name = :firstName. passing in either an array of JavaBeans or an array of Maps containing the parameter values.createBatch method to create this array.1 Reference Documentation 372 . Instead of implementing a special batch interface. } // } . additional methods For an SQL statement using the classic "?" placeholders. This object array must have one entry for each placeholder in the SQL statement.

If the count is not available. This count is reported by the JDBC driver. the JDBC driver returns a -2 value. the number of updates to make for each batch and a ParameterizedPreparedStatementSetter to set the values for the parameters of the prepared statement.. batch. } // } .batchUpdate( "update t_actor set first_name = ?. This method takes.. } int[] updateCounts = jdbcTemplate. actor. actor. new ParameterizedPreparedStatementSetter<Actor>() { public void setValues(PreparedStatement ps. a Collection of objects containing the parameters. 3. but there is now a more convenient method. for (Actor actor : actors) { Object[] values = new Object[] { actor. actor.batchUpdate( "update t_actor set first_name = ?.getFirstName()).1 Reference Documentation 373 . You can of course do this with the methods mentioned above by making multiple calls to the batchUpdate method. in addition to the SQL statement. 100.getFirstName().getLastName().getId()}. batch). Actor argument) throws SQLException { ps.add(values).jdbcTemplate = new JdbcTemplate(dataSource). Batch operations with multiple batches The last example of a batch update deals with batches that are so large that you want to break them up into several smaller batches. batch.setString(1.Spring Framework public int[] batchUpdate(final List<Actor> actors) { List<Object[]> batch = new ArrayList<Object[]>().getLastName().getId()}. actors. return updateCounts. } public int[][] batchUpdate(final Collection<Actor> actors) { Collection<Object[]> batch = new ArrayList<Object[]>(). public void setDataSource(DataSource dataSource) { this. last_name = ? where id = ?".getFirstName(). The framework loops over the provided values and breaks the update calls into batches of the size specified. actor. last_name = ? where id = ?". argument. This example shows a batch update using a batch size of 100: public class JdbcActorDao implements ActorDao { private JdbcTemplate jdbcTemplate.add(values). } int[][] updateCounts = jdbcTemplate. for (Actor actor : actors) { Object[] values = new Object[] { actor. additional methods All of the above batch update methods return an int array containing the number of affected rows for each batch entry.

For this example.getId().setString(2. simply create a new instance and set the table name using the withTableName method.insertActor = new SimpleJdbcInsert(dataSource).1 Reference Documentation 374 . 13.setLong(3. the initializing method is the setDataSource method.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource). actor. } // } . Object>(3).5 Simplifying JDBC operations with the SimpleJdbc classes The SimpleJdbcInsert and SimpleJdbcCall classes provide a simplified configuration by taking advantage of database metadata that can be retrieved through the JDBC driver. Configuration methods for this class follow the "fluid" style that returns the instance of the SimpleJdbcInsert. parameters. depending on the total number of updat objects provided. public class JdbcActorDao implements ActorDao { private SimpleJdbcTemplate simpleJdbcTemplate. this.getFirstName()).longValue()).put("id". This means there is less to configure up front. You should instantiate the SimpleJdbcInsert in the data access layer's initialization method. which allows you to chain all configuration methods. ps. Object> parameters = new HashMap<String.put("first_name".getLastName()). This example uses only one configuration method. public void setDataSource(DataSource dataSource) { this. actor. argument.withTableName("t_actor").Spring Framework ps. additional methods The batch update methods for this call returns an array of int arrays containing an array entry for each batch with an array of the number of affected rows for each update. You do not need to subclass the SimpleJdbcInsert class. } public void add(Actor actor) { Map<String. although you can override or turn off the metadata processing if you prefer to provide all the details in your code. 3. argument. you will see examples of multiple ones later. private SimpleJdbcInsert insertActor. The top level array's length indicates the number of batches executed and the second level array's length indicates the number of updates in that batch. the JDBC driver returns a -2 value. The update count for each update stament is the one reported by the JDBC driver. Inserting data using SimpleJdbcInsert Let's start by looking at the SimpleJdbcInsert class with the minimal amount of configuration options. return updateCounts. If the count is not available.getId()).. parameters. The number of updates in each batch should be the the batch size provided for all batches except for the last one that might be less. } } )..

parameters.utils.Number is the base class that you can rely on.getLastName()). public void setDataSource(DataSource dataSource) { this. this.longValue()).put("last_name". you specify the name of the generated key column with the usingGeneratedKeyColumns method. This is because we read the metadata in order to construct the actual insert statement. actor.lang. } // } .. java.put("last_name". The important thing to note here is that the keys used for the Map must match the column names of the table as defined in the database. insertActor.. but instead of passing in the id it retrieves the auto-generated key and sets it on the new Actor object.executeAndReturnKey(parameters).put("first_name".. When you create the SimpleJdbcInsert. Retrieving auto-generated keys using SimpleJdbcInsert This example uses the same insert as the preceding. Number newId = insertActor.You cannot rely on all databases to return a specific Java class here. Object> parameters = new HashMap<String. private SimpleJdbcInsert insertActor. then you can use a KeyHolder that is returned from the executeReturningKeyHolder method. If you have multiple auto-generated columns. } public void add(Actor actor) { Map<String. actor. Object>(2).. Specifying columns for a SimpleJdbcInsert You can limit the columns for an insert by specifying a list of column names with the usingColumns method: 3. This returns a java. or the generated values are non-numeric. actor.execute(parameters). actor.insertActor = new SimpleJdbcInsert(dataSource) .withTableName("t_actor") .getFirstName()). public class JdbcActorDao implements ActorDao { private SimpleJdbcTemplate simpleJdbcTemplate.setId(newId.Number object with which you can create an instance of the numerical type that is used in our domain class.Map as its only parameter.lang.usingGeneratedKeyColumns("id").simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource). additional methods The main difference when executing the insert by this second approach is that you do not add the id to the Map and you call the executeReturningKey method.1 Reference Documentation 375 . parameters.getLastName()). in addition to specifying the table name. additional methods The execute method used here takes a plain java. } // } .Spring Framework parameters.

It will use the corresponding getter method to extract the parameter values. Object> parameters = new HashMap<String. Spring provides a couple of implementations of the SqlParameterSource interface that can be used instead. } public void add(Actor actor) { SqlParameterSource parameters = new BeanPropertySqlParameterSource(actor). 3. actor.withTableName("t_actor") .simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource). Number newId = insertActor. Number newId = insertActor. } // } .Spring Framework public class JdbcActorDao implements ActorDao { private SimpleJdbcTemplate simpleJdbcTemplate. Here is an example: public class JdbcActorDao implements ActorDao { private SimpleJdbcTemplate simpleJdbcTemplate.executeAndReturnKey(parameters).insertActor = new SimpleJdbcInsert(dataSource) . actor. additional methods The execution of the insert is the same as if you had relied on the metadata to determine which columns to use.. parameters.withTableName("t_actor") .getFirstName()).1 Reference Documentation 376 . private SimpleJdbcInsert insertActor. additional methods Another option is the MapSqlParameterSource that resembles a Map but provides a more convenient addValue method that can be chained. public void setDataSource(DataSource dataSource) { this. Object>(2). which is a very convenient class if you have a JavaBean-compliant class that contains your values.longValue()). this.usingGeneratedKeyColumns("id").setId(newId.insertActor = new SimpleJdbcInsert(dataSource) .usingColumns("first_name".longValue()).usingGeneratedKeyColumns("id"). } public void add(Actor actor) { Map<String. private SimpleJdbcInsert insertActor.The first one is BeanPropertySqlParameterSource. but it's not the most convenient class to use.getLastName()). parameters. actor.setId(newId. "last_name") . } // } . this... public void setDataSource(DataSource dataSource) { this.executeAndReturnKey(parameters).put("first_name". Using SqlParameterSource to provide parameter values Using a Map to provide parameter values works fine.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource).put("last_name".. actor.

longValue()). you don't have to create a subclass and you don't have to declare parameters that can be looked up in the database metadata. so that you do not have to declare them explicitly. actor. public void setDataSource(DataSource dataSource) { this.withTableName("t_actor") .insertActor = new SimpleJdbcInsert(dataSource) .1 Reference Documentation 377 .usingGeneratedKeyColumns("id"). in addition to the DataSource..setId(newId. Number newId = insertActor. You should instantiate and configure the class in the initialization method of your data access layer. Compared to the StoredProcedure class. and birth_date columns in the form of out parameters. The out parameters return the data read from the table.Spring Framework public class JdbcActorDao implements ActorDao { private SimpleJdbcTemplate simpleJdbcTemplate. The in_id parameter contains the id of the actor you are looking up.executeAndReturnKey(parameters).. out_last_name. additional methods As you can see.getFirstName()) . The only configuration option.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource).getLastName()). You can declare parameters if you prefer to do that. } // } . last_name. The SimpleJdbcCall is declared in a similar manner to the SimpleJdbcInsert. actor. The example procedure reads a specified actor entry and returns first_name. this. } public void add(Actor actor) { SqlParameterSource parameters = new MapSqlParameterSource() . The first example shows a simple procedure that returns only scalar values in VARCHAR and DATE format from a MySQL database. OUT out_first_name VARCHAR(100).addValue("last_name". only the executing code has to change to use these alternative input classes. is the 3. birth_date INTO out_first_name. last_name. OUT out_last_name VARCHAR(100). or if you have parameters such as ARRAY or STRUCT that do not have an automatic mapping to a Java class. OUT out_birth_date DATE) BEGIN SELECT first_name. out_birth_date FROM t_actor where id = in_id. private SimpleJdbcInsert insertActor. Calling a stored procedure with SimpleJdbcCall The SimpleJdbcCall class leverages metadata in the database to look up names of in and out parameters. CREATE PROCEDURE read_actor ( IN in_id INTEGER. the configuration is the same. Following is an example of a SimpleJdbcCall configuration using the above stored procedure.addValue("first_name". END. actor.

jar in your classpath for this to work.setFirstName((String) out. which could vary between databases.get("out_birth_date")). actor.setBirthDate((Date) out. actor. Then you pass this customized JdbcTemplate instance into the constructor of your SimpleJdbcCall.addValue("in_id"..1 Reference Documentation 378 . } public Actor readActor(Long id) { SqlParameterSource in = new MapSqlParameterSource() . Again. The execute method takes the IN parameters and returns a Map containing any out parameters keyed by the name as specified in the stored procedure. } // } . actor.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource).get("out_first_name")). id). public void setDataSource(DataSource dataSource) { this. To do the latter. To make your code more portable you should do a case-insensitive lookup or instruct Spring to use a CaseInsensitiveMap from the Jakarta Commons project. out_last_name and out_birth_date.. public void setDataSource(DataSource dataSource) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource). Here is an example of this configuration: public class JdbcActorDao implements ActorDao { private SimpleJdbcCall procReadActor. Actor actor = new Actor(). public class JdbcActorDao implements ActorDao { private SimpleJdbcTemplate simpleJdbcTemplate. The last part of the execute method creates an Actor instance to use to return the data retrieved. it is important to use the names of the out parameters as they are declared in the stored procedure.execute(in). In this case they are out_first_name.procReadActor = new SimpleJdbcCall(dataSource) . private SimpleJdbcCall procReadActor.setLastName((String) out. The case does not have to match because you use metadata to determine how database objects should be referred to in a stored procedure. 3. this.Spring Framework name of the stored procedure. return actor.setId(id). What is specified in the source for the stored procedure is not necessarily the way it is stored in the database. you create your own JdbcTemplate and set the setResultsMapCaseInsensitive property to true.withProcedureName("read_actor").get("out_last_name")). Also. additional methods The code you write for the execution of the call involves creating an SqlParameterSource containing the IN parameter. Some databases transform names to all upper case while others use lower case or use the case as specified. You must include the commons-collections. actor. It's important to match the name provided for the input value with that of the parameter name declared in the stored procedure. the case in the names of the out parameters stored in the results map matches that of the out parameter names in the database. Map out = procReadActor.

withoutProcedureColumnMetaDataAccess() . To bypass all processing of metadata lookups for potential parameters and only use the declared parameters. jdbcTemplate.withProcedureName("read_actor").VARCHAR).procReadActor = new SimpleJdbcCall(jdbcTemplate) .1 Reference Documentation 379 . Types. Types. and Sybase. Explicitly declaring parameters to use for a SimpleJdbcCall You have seen how the parameters are deduced based on metadata. this. or all the parameters explicitly.declareParameters( new SqlParameter("in_id".Spring Framework jdbcTemplate. Microsoft SQL Server. using the information from the preceding example. Suppose that you have two or more different call signatures declared for a database function. We also support metadata lookup of stored functions for: MySQL. and Oracle.. additional methods By taking this action. You can opt to declare one. } // } . See the next section for details on how to define an SqlParameter. In this case you call the useInParameterNames to specify the list of IN parameter names to include for a given signature.NUMERIC). Note Explicit declarations are necessary if the database you use is not a Spring-supported database. you call the method withoutProcedureColumnMetaDataAccess as part of the declaration. some. public class JdbcActorDao implements ActorDao { private SimpleJdbcCall procReadActor.setResultsMapCaseInsensitive(true). Currently Spring supports metadata lookup of stored procedure calls for the following databases: Apache Derby. which takes a variable number of SqlParameter objects as input. MySQL.useInParameterNames("in_id") .. DB2. you avoid conflicts in the case used for the names of your returned out parameters.procReadActor = new SimpleJdbcCall(jdbcTemplate) . 3. The parameter metadata is still used where you do not declare parameters explicitly. Microsoft SQL Server. this. You do this by creating and configuring SimpleJdbcCall with the declareParameters method. Oracle.setResultsMapCaseInsensitive(true).withProcedureName("read_actor") . but you can declare then explicitly if you wish. The following example shows a fully declared procedure call. public void setDataSource(DataSource dataSource) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource). new SqlOutParameter("out_first_name".

Another option is to specify an SqlReturnType that provides an opportunity to define customized handling of the return values. We have already seen declarations like: new SqlParameter("in_id". Types. new SqlOutParameter("out_birth_date".Spring Framework new SqlOutParameter("out_last_name". The first line with the SqlParameter declares an IN parameter. new SqlOutParameter("out_first_name". The SQL type is specified using the java. you use an SqlParameter or one of its subclasses. You use the withFunctionName method as part of the 3. Note Only parameters declared as SqlParameter and SqlInOutParameter will be used to provide input values.VARCHAR). you can provide a RowMapper to handle mapping of rows returned from a REF cursor.1 Reference Documentation 380 .sql. For IN parameters..VARCHAR). “Modeling JDBC operations as Java objects”. in addition to the name and the SQL type. covered in Section 13.NUMERIC).DATE) ). } // } . This is different from the StoredProcedure class. Types. this one specifies all details explicitly rather than relying on metadata. IN parameters can be used for both stored procedure calls and for queries using the SqlQuery and its subclasses covered in the following section.6. parameters that provide an IN value to the procedure and that also return a value. You typically specify the parameter name and SQL type in the constructor. you can specify a scale for numeric data or a type name for custom database types. Types. For out parameters. which for backwards compatibility reasons allows input values to be provided for parameters declared as SqlOutParameter. except that you provide a function name rather than a procedure name. additional methods The execution and end results of the two examples are the same. How to define SqlParameters To define a parameter for the SimpleJdbc classes and also for the RDBMS operations classes. The second line with the SqlOutParameter declares an out parameter to be used in a stored procedure call. Calling a stored function using SimpleJdbcCall You call a stored function in almost the same way as you call a stored procedure.Types constants.. Types. There is also an SqlInOutParameter for InOut parameters.

return name. END. ' '.setResultsMapCaseInsensitive(true). } public String getActorName(Long id) { SqlParameterSource in = new MapSqlParameterSource() . in).simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource). id). this..Spring Framework configuration to indicate that we want to make a call to a function. RETURN out_name. String name = funcGetActorName. jdbcTemplate.1 Reference Documentation 381 .. The following example is based on a stored function named get_actor_name that returns an actor's full name. public void setDataSource(DataSource dataSource) { this. A specialized execute call. JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource). Some databases return result sets during the JDBC results processing while others require an explicitly registered out parameter of a specific type.withFunctionName("get_actor_name").executeFunction(String. The name specified is still used 3. so the returned results will have to match the order in which you declare the RowMapper implementations. SELECT concat(first_name. A similar convenience method named executeObject is also available for stored procedures that only have one out parameter. With the SimpleJdbcCall you use the returningResultSet method and declare a RowMapper implementation to be used for a specific parameter. executeFunction.class. additional methods The execute method used returns a String containing the return value from the function call. } // } . private SimpleJdbcCall funcGetActorName. which means you do not have to retrieve the return value from the results map. Here is the MySQL source for this function: CREATE FUNCTION get_actor_name (in_id INTEGER) RETURNS VARCHAR(200) READS SQL DATA BEGIN DECLARE out_name VARCHAR(200). Both approaches need additional processing to loop over the result set and process the returned rows. To call this function we again create a SimpleJdbcCall in the initialization method. last_name) INTO out_name FROM t_actor where id = in_id. is used to execute the function and it returns the function return value as an object of a specified type.funcGetActorName = new SimpleJdbcCall(jdbcTemplate) . Returning ResultSet/REF Cursor from a SimpleJdbcCall Calling a stored procedure or function that returns a result set is a bit tricky. In the case where the result set is returned during the results processing. public class JdbcActorDao implements ActorDao { private SimpleJdbcTemplate simpleJdbcTemplate. there are no names defined.addValue("in_id". and the corresponding string for a function call is generated.

6 Modeling JDBC operations as Java objects The org. and insert statements.execute(new HashMap<String. 3.last_name. JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource). To call this procedure you declare the RowMapper.procReadAllActors = new SimpleJdbcCall(jdbcTemplate) . Often it is simpler to write a DAO method that simply calls a method on a JdbcTemplate directly (as opposed to encapsulating a query as a full-blown class).. Object>(0)). You can also execute stored procedures and run update. } // } .setResultsMapCaseInsensitive(true). END. The list of Actors is then retrieved from the results map and returned to the caller. public void setDataSource(DataSource dataSource) { this.jdbc. return (List) m. a. jdbcTemplate. 13.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource). Note Many Spring developers believe that the various RDBMS operation classes described below (with the exception of the StoredProcedure class) can often be replaced with straight JdbcTemplate calls. private SimpleJdbcCall procReadAllActors. Here is the MySQL source for this procedure: CREATE PROCEDURE read_all_actors() BEGIN SELECT a. you can execute queries and get the results back as a list containing business objects with the relational column data mapped to the properties of the business object.class)). As an example. public class JdbcActorDao implements ActorDao { private SimpleJdbcTemplate simpleJdbcTemplate. a.id. The next example uses a stored procedure that takes no IN parameters and returns all rows from the t_actor table.object package contains classes that allow you to access the database in a more object-oriented manner..springframework.returningResultSet("actors".1 Reference Documentation 382 . a. you can use a ParameterizedBeanPropertyRowMapper that is created by passing in the required class to map to in the newInstance method. this.birth_date FROM t_actor a.newInstance(Actor. Because the class you want to map to follows the JavaBean rules. ParameterizedBeanPropertyRowMapper. delete. } public List getActorsList() { Map m = procReadAllActors.first_name.get("actors"). additional methods The execute call passes in an empty Map because this call does not take any parameters.Spring Framework to store the processed list of results in the results map that is returned from the execute statement.withProcedureName("read_all_actors") .

You must declare each parameter using the declareParameter method passing in an SqlParameter. 3. you call the compile() method so the statement can be prepared and later executed. super.) method to provide a RowMapper instance that can create one object per row obtained from iterating over the ResultSet that is created during the execution of the query. public class ActorMappingQuery extends MappingSqlQuery<Actor> { public ActorMappingQuery(DataSource ds) { super(ds.Types. threadsafe class that encapsulates an SQL query. int rowNumber) throws SQLException { Actor actor = new Actor().declareParameter(new SqlParameter("id".getString("first_name")). The constructor for this customer query takes the DataSource as the only parameter.INTEGER)). if you are getting measurable value from using the RDBMS operation classes.sql. so as long as these instances are created when the DAO is initialized they can be kept as instance variables and be reused. continue using these classes. Types. last_name from t_actor where id = ?"). MappingSqlQuery MappingSqlQuery is a reusable query in which concrete subclasses must implement the abstract mapRow(. The following example shows a custom query that maps the data from the t_actor relation to an instance of the Actor class.Spring Framework However.. Subclasses must implement the newRowMapper(. } } The class extends MappingSqlQuery parameterized with the Actor type. This SQL will be used to create a PreparedStatement so it may contain place holders for any parameters to be passed in during execution.setId(rs.getLong("id")). Other implementations that extend SqlQuery are MappingSqlQueryWithParameters and UpdatableSqlQuery.setFirstName(rs. } @Override protected Actor mapRow(ResultSet rs. actor. This class is thread-safe after it is compiled.setLastName(rs. first_name. The SqlQuery class is rarely used directly because the MappingSqlQuery subclass provides a much more convenient implementation for mapping rows to Java classes.1 Reference Documentation 383 . SqlQuery SqlQuery is a reusable. actor. In this constructor you call the constructor on the superclass with the DataSource and the SQL that should be executed to retrieve the rows for this query.getString("last_name"))..) method to convert each row of the supplied ResultSet into an object of the type specified. actor. return actor. "select id. After you define all parameters. The SqlParameter takes a name and the JDBC type as defined in java. compile().

jdbc. you don't have to subclass the SqlUpdate class since it can easily be parameterized by setting SQL and declaring parameters.. an update can have parameters and is defined in SQL.core.execute(age. } SqlUpdate The SqlUpdate class encapsulates an SQL update. an update object is reusable. String namePattern) { List<Actor> actors = actorSearchMappingQuery. int rating) { return update(rating. } 3. Types. id). and like all RdbmsOperation classes..SqlParameter.Spring Framework private ActorMappingQuery actorMappingQuery. The SQLUpdate class is concrete. to add a custom update method.1 Reference Documentation 384 . as in the following snippet where it's simply called execute.Types.sql. It can be subclassed. for example.) methods of query objects. } The method in this example retrieves the customer with the id that is passed in as the only parameter. setSql("update customer set credit_rating = ? where id = ?").DataSource. Like a query. public List<Actor> searchForActors(int age. import org. Since we only want one object returned we simply call the convenience method findObject with the id as parameter. } public Customer getCustomer(Long id) { return actorMappingQuery. Types.) methods analogous to the execute(. compile().springframework. If we had instead a query that returned a list of objects and took additional parameters then we would use one of the execute methods that takes an array of parameter values passed in as varargs.springframework.SqlUpdate.jdbc. } /** * @param id for the Customer to be updated * @param rating the new value for credit rating * @return number of rows updated */ public int execute(int id. import java. declareParameter(new SqlParameter("creditRating". namePattern). declareParameter(new SqlParameter("id".object.actorMappingQuery = new ActorMappingQuery(dataSource).NUMERIC)). This class provides a number of update(. public class UpdateCreditRating extends SqlUpdate { public UpdateCreditRating(DataSource ds) { setDataSource(ds). @Autowired public void setDataSource(DataSource dataSource) { this. import javax. return actors. import org. However.sql.NUMERIC)).findObject(id).

but an output parameter is declared as a date type using the class SqlOutParameter.springframework.Types constants. import javax.sql.DataSource.factory. Another option is to specify an SqlReturnType that enables you to define customized handling of the return values.core. preventing use other than through a subclass that offers tighter typing.util.util. java..Spring Framework } StoredProcedure The StoredProcedure class is a superclass for object abstractions of RDBMS stored procedures.VARCHAR).Autowired. This class is abstract. Here is an example of a simple DAO that uses a StoredProcedure to call a function. in this case only one. Types.1 Reference Documentation 385 . IN parameters can be used for both stored procedure calls and for queries using the SqlQuery and its subclasses covered in the following section. Types. import import import import java.NUMERIC). You must specify the parameter name and SQL type in the constructor like in the following code snippet. sysdate().beans. you can specify a scale for numeric data or a type name for custom database types. new SqlParameter("in_id". import org.SqlOutParameter.sql. and its various execute(. import org.) methods have protected access. The execute() method executes the procedure and extracts the returned date from the results Map. In this example.sql.Map. java. The inherited sql property will be the name of the stored procedure in the RDBMS. new SqlOutParameter("out_first_name". This example has no input parameters. For in parameters. The results Map has an entry for each declared output parameter. There is also an SqlInOutParameter for InOut parameters. The SQL type is specified using the java. 3.jdbc. the StoredProcedure class is an inner class. To use the stored procedure functionality you have to create a class that extends StoredProcedure.Date.StoredProcedure.HashMap. For out parameters you can provide a RowMapper to handle mapping of rows returned from a REF cursor. To define a parameter for the StoredProcedure class.annotation.object.which comes with any Oracle database. The first line with the SqlParameter declares an IN parameter.util.Types.springframework.jdbc. using the parameter name as the key. import org. parameters that provide an in value to the procedure and that also return a value. in addition to the name and the SQL type. you use an SqlParameter or one of its subclasses. java. The second line with the SqlOutParameter declares an out parameter to be used in the stored procedure call. but if you need to reuse the StoredProcedure you declare it as a top-level class.springframework.

SPROC_NAME).StoredProcedure.CURSOR. new GenreMapper())). import oracle. Object>()).HashMap.DataSource.sql. Date sysdate = (Date) results. declareParameter(new SqlOutParameter("titles".core. this sproc has no input parameters. } public Date getSysdate() { return getSysdate. } private class GetSysdateProcedure extends StoredProcedure { private static final String SQL = "sysdate". Object>()).getSysdate = new GetSysdateProcedure(dataSource).object. compile().util. setFunction(true).get("date").jdbc. } } 3. compile(). import javax.. OracleTypes..execute().execute(new HashMap<String. public GetSysdateProcedure(DataSource dataSource) { setDataSource(dataSource). import java.1 Reference Documentation 386 . declareParameter(new SqlOutParameter("genres". } } } The following example of a StoredProcedure has two output parameters (in this case.util. Types. Oracle REF cursors).DATE)). so an empty Map is supplied return super.jdbc. return sysdate. @Autowired public void init(DataSource dataSource) { this.OracleTypes.springframework. setSql(SQL). so an empty Map is supplied.jdbc.Spring Framework public class StoredProcedureDao { private GetSysdateProcedure getSysdate. import org. import java.CURSOR. public class TitlesAndGenresStoredProcedure extends StoredProcedure { private static final String SPROC_NAME = "AllTitlesAndGenres". Object> results = execute(new HashMap<String. OracleTypes. declareParameter(new SqlOutParameter("date". public TitlesAndGenresStoredProcedure(DataSource dataSource) { super(dataSource. new TitleMapper())).Map. } public Map<String. Object> execute() { // again.springframework. Map<String. } public Date execute() { // the 'sysdate' sproc has no input parameters. import org.SqlOutParameter.

java.core.jdbc.domain. import java.foo.Genre. import java.Title.Date.springframework.sql. return title. import java.util.sql.sql.getLong("id")).foo. java.OracleTypes.util. import com.SQLException. public final class TitleMapper implements RowMapper<Title> { public Title mapRow(ResultSet rs.setId(rs. you can code a strongly typed execute(.sql.jdbc.SQLException.core.jdbc.jdbc. title.object.) method that would delegate to the superclass' untyped execute(Map parameters) method (which has protected access).jdbc.RowMapper..RowMapper.jdbc. import org. import javax. public final class GenreMapper implements RowMapper<Genre> { public Genre mapRow(ResultSet rs. org. The TitleMapper class maps a ResultSet to a Title domain object for each row in the supplied ResultSet: import org. public class TitlesAfterDateStoredProcedure extends StoredProcedure { 3.springframework.SqlParameter.springframework.HashMap.1 Reference Documentation 387 . import java.DataSource. } } To pass parameters to a stored procedure that has one or more input parameters in its definition in the RDBMS.sql. int rowNum) throws SQLException { return new Genre(rs.setName(rs. The code for the two RowMapper implementations is provided below. org. import import import import java.ResultSet.Spring Framework Notice how the overloaded variants of the declareParameter(. java.util.StoredProcedure.core. import com..) method that have been used in the TitlesAndGenresStoredProcedure constructor are passed RowMapper implementation instances.springframework.getString("name")).Types. title.ResultSet.Map.domain. } } The GenreMapper class maps a ResultSet to a Genre domain object for each row in the supplied ResultSet.springframework. org.getString("name")).SqlOutParameter. int rowNum) throws SQLException { Title title = new Title(). this is a very convenient and powerful way to reuse existing functionality.sql.core. for example: import import import import oracle.

return super. OracleTypes. inputs. You can provide SQL type information in several ways: • Many update and query methods of the JdbcTemplate take an additional parameter in the form of an int array. declareParameter(new SqlParameter(CUTOFF_DATE_PARAM. cutoffDate). Handling BLOB and CLOB objects You can store images. compile(). new TitleMapper())).sql.1 Reference Documentation 388 . You can also provide an optional scale parameter for numeric values. In Spring you can handle these large objects by using the 3.DATE). private static final String CUTOFF_DATE_PARAM = "cutoffDate". public TitlesAfterDateStoredProcedure(DataSource dataSource) { super(dataSource. Object>(). Types. } public Map<String.CURSOR. Object> execute(Date cutoffDate) { Map<String.put(CUTOFF_DATE_PARAM. Providing SQL type information for parameters Usually Spring determines the SQL type of the parameters based on the type of parameter passed in.7 Common problems with parameter and data value handling Common problems with parameters and data values exist in the different approaches provided by the Spring Framework JDBC. and large chunks of text. use the SqlParameterSource classes BeanPropertySqlParameterSource or MapSqlParameterSource. other binary objects. } } 13. • For methods working with named parameters.Types class. They both have methods for registering the SQL type for any of the named parameter values. declareParameter(new SqlOutParameter("titles". These large object are called BLOB for binary data and CLOB for character data.execute(inputs). Create a new instance for each value and pass in the SQL type and parameter value in the constructor. This is sometimes necessary to correctly set NULL values. It is possible to explicitly provide the SQL type to be used when setting parameter values. Object> inputs = new HashMap<String. • You can use the SqlParameterValue class to wrap the parameter value that needs this additional information. Provide one entry for each parameter. SPROC_NAME). This array is used to indicate the SQL type of the coresponding parameter using constant values from the java.Spring Framework private static final String SPROC_NAME = "TitlesAfterDate".

length()). blobIs. Later you will see how to read it back from the database. through the getLobCreator method. blobIs. For this example we assume that there is a variable. lobCreator.execute( "INSERT INTO lob_table (id.setClobAsCharacterStream(ps. new AbstractLobCreatingPreparedStatementCallback(lobHandler) { protected void setValues(PreparedStatement ps. final File clobIn = new File("large.close(). a_clob. This example uses a JdbcTemplate and an implementation of the AbstractLobCreatingPreparedStatementCallback.Spring Framework JdbcTemplate directly and also when using the higher abstractions provided by RDBMS Objects and the SimpleJdbc classes.length()). } } ). used for creating new LOB objects to be inserted.txt").close(). ?. a_blob) VALUES (?.setLong(1. (int)clobIn. LobCreator lobCreator) throws SQLException { ps. clobReader. lobHandler. final InputStream clobIs = new FileInputStream(clobIn). jdbcTemplate. clobReader. It implements one method. The LobCreator/LobHandler provides the following support for LOB input and output: • BLOB • byte[] – getBlobAsBytes and setBlobAsBytes • InputStream – getBlobAsBinaryStream and setBlobAsBinaryStream • CLOB • String – getClobAsString and setClobAsString • InputStream – getClobAsAsciiStream and setClobAsAsciiStream • Reader – getClobAsCharacterStream and setClobAsCharacterStream The next example shows how to create and insert a BLOB. that already is set to an instance of a DefaultLobHandler.1 Pass in the lobHandler that in this example is a plain DefaultLobHandler Reference Documentation 389 . final File blobIn = new File("spring2004. (int)blobIn. ?)". 2. setValues. You typically set this value through dependency injection.jpg"). lobCreator. All of these approaches use an implementation of the LobHandler interface for the actual management of the LOB data.setBlobAsBinaryStream(ps. 1L). final InputStreamReader clobReader = new InputStreamReader(clobIs). This method provides a LobCreator that you use to set the values for the LOB columns in your SQL insert statement. final InputStream blobIs = new FileInputStream(blobIn). 3. ‚ ƒ „ ‚ 3. The LobHandler provides access to a LobCreator class.

Object>>() { public Map<String. return results. (2. } }).getClobAsString(rs. Using the method getBlobAsBytes. This variable list is not directly supported for prepared statements by the JDBC standard. byte[] blobBytes = lobHandler. String clobText = lobHandler. int i) throws SQLException { Map<String. or you need to generate the SQL string dynamically once you know how many placeholders are required. ƒ results. new RowMapper<Map<String. In addition to the primitive values in the value list. pass in the contents of the BLOB. This list would support multiple expressions defined for the in clause such as select * from T_ACTOR where (id. The named parameter support provided in the NamedParameterJdbcTemplate and SimpleJdbcTemplate takes the latter approach. clobText). a_blob from lob_table". "a_blob"). blobBytes). 'Johnson'). "a_clob"). List<Map<String. Object>(). you cannot declare a variable number of placeholders. ƒ „ Using the method getClobAsString.Spring Framework ƒ „ Using the method setClobAsCharacterStream. retrieve the contents of the CLOB. a_clob. Object>> l = jdbcTemplate. ‚ results. Again. 2. Note Be careful when passing in many values.util. This list will be used to insert the required placeholders and pass in the values during the statement execution. Now it's time to read the LOB data from the database. Object> results = new HashMap<String.query("select id. A typical example would be select * from T_ACTOR where id in (1. You need a number of variations with the desired number of placeholders prepared.1 Reference Documentation 390 . 3). 'Harrop')). Oracle's limit is 1000.getBlobAsBytes(rs. last_name) in ((1.util. Various databases exceed this number. you use a JdbcTemplate with the same instance variable lobHandler and a reference to a DefaultLobHandler. The JDBC standard does not guarantee that you can use more than 100 values for an in expression list.List of primitive objects. Passing in lists of values for IN clause The SQL standard allows for selecting rows based on an expression that includes a variable list of values. Handling complex types for stored procedure calls When you call stored procedures you can sometimes use complex types specific to the database. This of course requires that your database supports this syntax. pass in the contents of the CLOB. To 3. Pass in the values as a java. Object> mapRow(ResultSet rs.List of object arrays. Using the method setBlobAsBinaryStream.put("CLOB". retrieve the contents of the BLOB. but they usually have a hard limit for how many values are allowed.put("BLOB". you can create a java.

parse("2010-12-31"). testItem.Date(testItem. Spring provides a SqlReturnType for handling them when they are returned from the stored procedure call and SqlTypeValue when they are passed in as a parameter to the stored procedure.longValue()).). item. new java. SqlTypeValue value = new AbstractSqlTypeValue() { protected Object createTypeValue(Connection conn. The active connection is passed in. int colIndx. This SqlTypeValue can now be added to the Map containing the input parameters for the execute call of the stored procedure. final Long[] ids = new Long[] {1L. Here is an example of returning the value of an Oracle STRUCT object of the user declared type ITEM_TYPE. conn. String typeName) throws SQLException { StructDescriptor itemDescriptor = new StructDescriptor(typeName.setDescription((String)attr[1]). Oracle has its own internal ARRAY class that must be used in this case. return item.STRUCT.util. new SimpleDateFormat("yyyy-M-d"). or ArrayDescriptors. item. You use the SqlTypeValue to pass in the value of a Java object like TestItem into a stored procedure.getExpirationDate().parse("2010-12-31"). "ITEM_TYPE". Another use for the SqlTypeValue is passing in an array of values to an Oracle stored procedure. } })). "A test item". conn). The SqlReturnType interface has a single method named getTypeValue that must be implemented. new SimpleDateFormat("yyyy-M-d").1 Reference Documentation 391 . Struct item = new STRUCT(itemDescriptor. and you can use it to create database-specific objects such as StructDescriptors. String typeName) throws SQLException { STRUCT struct = (STRUCT)cs. TestItem item = new TestItem().getObject(colIndx).sql.setId(((Number) attr[0]). OracleTypes.new TestItem(123L.getId(). int sqlType. declareParameter(new SqlOutParameter("item".getTime()) }). This interface is used as part of the declaration of an SqlOutParameter. The SqlTypeValue interface has a single method named createTypeValue that you must implement.Date)attr[2]). Object[] attr = struct. return item.new TestItem(123L. new SqlReturnType() { public Object getTypeValue(CallableStatement cs. final TestItem .getDescription().). int sqlType. item.setExpirationDate((java. } }. new Object[] { testItem. SqlTypeValue value = new AbstractSqlTypeValue() { 3. and you can use the SqlTypeValue to create an instance of the Oracle ARRAY and populate it with values from the Java ARRAY. final TestItem . "A test item". as shown in the following example.Spring Framework accommodate these types.getAttributes(). 2L}.

Creating an embedded database instance using Spring XML If you want to expose an embedded database instance as a bean in a Spring ApplicationContext.Spring Framework protected Object createTypeValue(Connection conn. conn).build().embedded package provides support for embedded Java database engines.datasource.addScript("my-test-data. Use this when you need to create an embedded database instance in a standalone environment. return idArray. and Derby is provided natively.sql"). use the embedded-database tag in the spring-jdbc namespace: <jdbc:embedded-database id="dataSource"> <jdbc:script location="classpath:schema.sql and testdata. EmbeddedDatabase db = builder. The database instance is made available to the Spring container as a bean of type javax. H2.addScript("my-schema. Creating an embedded database instance programmatically The EmbeddedDatabaseBuilder class provides a fluent API for constructing an embedded database programmatically. int sqlType. ids).sql"/> <jdbc:script location="classpath:test-data. This bean can then be injected into data access objects as needed.DataSource) db.1 Reference Documentation 392 . quick startup time. // do stuff against the db (EmbeddedDatabase extends javax.sql"). } }.8 Embedded database support The org.setType(H2). ARRAY idArray = new ARRAY(arrayDescriptor.sql"/> </jdbc:embedded-database> The preceding configuration creates an embedded HSQL database populated with SQL from schema.sql resources in the classpath.shutdown() Extending the embedded database support 3. and the ability to rapidly evolve SQL during development. You can also use an extensible API to plug in new embedded database types and DataSource implementations.DataSource.springframework. String typeName) throws SQLException { ArrayDescriptor arrayDescriptor = new ArrayDescriptor(typeName.sql. testability. Why use an embedded database? An embedded database is useful during the development phase of a project because of its lightweight nature. such as a data access object unit test: EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().jdbc. conn. 13.sql. Support for HSQL. Benefits include ease of configuration.

template. If you are using the builder API.sql and classpath:test-d db = new EmbeddedDatabaseBuilder(). Using Derby Spring also supports Apache Derby 10. to manage embedded database connections. To enable H2. If using the builder API.5 and above.Derby. call the setType(EmbeddedDatabaseType) method with EmbeddedDatabaseType.. call the setType(EmbeddedDatabaseType) method with EmbeddedDatabaseType. HSQL is the default embedded database if no type is specified explicitly. Implement DataSourceFactory to support a new DataSource implementation. such as a connection pool. such as Apache Derby. set the type attribute of the embedded-database tag to H2.HSQL. If you are using the builder API.8. Using HSQL Spring supports HSQL 1.H2.).addDefaultScripts(). The following is a data access unit test template that uses an embedded database: public class DataAccessUnitTestTemplate { private EmbeddedDatabase db.0 and above.1 Reference Documentation 393 . } @Test public void testDataAccess() { JdbcTemplate template = new JdbcTemplate(db).build(). 2.query(.Spring Framework Spring JDBC embedded database support can be extended in two ways: 1. To enable Derby. You are encouraged to contribute back extensions to the Spring community at jira. set the type attribute of the embedded-database tag to Derby. set the type attribute of the embedded-database tag to HSQL. 3. @Before public void setUp() { // creates a HSQL in-memory db populated from default scripts classpath:schema.springframework.org. call the setType(EmbeddedDatabaseType) method with EmbeddedDatabaseType. Using H2 Spring supports the H2 database as well. Implement EmbeddedDatabaseConfigurer to support a new embedded database type. Testing data access logic with an embedded database Embedded databases provide a lightweight way to test data access code.. To specify HSQL explicitly.

This can be set according to the environment (e.1 Reference Documentation 394 .springframework.INITIALIZE_DATABASE}"> <jdbc:script location=".sql"/> <jdbc:script location="classpath:com/foo/sql/db-test-data. for instance if running against an existing database that already has test data in it.. to get more control over the creation and deletion of existing data. but sometimes you need to initialize an instance running on a server somewhere.sql). The first is flag to switch the initialization on and off. The likelihood of accidentally deleting data is reduced by the commonest pattern (as shown above) that creates the tables first and then inserts the data . to pull a boolean value from system properties or an environment bean).sql"/> </jdbc:initialize-database> The example above runs the two scripts specified against the database: the first script is a schema creation.. use the initialize-database tag in the spring-jdbc namespace: <jdbc:initialize-database data-source="dataSource"> <jdbc:script location="classpath:com/foo/sql/db-schema.Spring Framework } @After public void tearDown() { db.shutdown(). If a pattern is used the scripts are executed in lexical order of their URL or filename.datasource.the first step will fail if the tables already exist.jdbc. and the second is a test data set insert.g. classpath*:/com/foo/**/sql/*-data. This will not always be what you want. The script locations can also be patterns with wildcards in the usual ant style used for resources in Spring (e. However. } } 13. <jdbc:initialize-database data-source="dataSource" enabled="#{systemProperties."/> </jdbc:initialize-database> The second option to control what happens with existing data is to be more tolerant of failures.9 Initializing a DataSource The org. the XML namespace provides a couple more options. To this 3.g. The embedded database support provides one option for creating and initializing a DataSource for an application. Initializing a database instance using Spring XML If you want to initialize a database and you can provide a reference to a DataSource bean.g. e.init package provides support for initializing an existing DataSource. The default behaviour of the database initializer is to unconditionally execute the scripts provided.

The database initializer depends on a data source instance and runs the scripts provided in its initialization callback (c.f. e.. and not otherwise.. <jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS"> <jdbc:script location=". followed by a set of CREATE statements. If other beans depend on the same data source and also use the data source in an initialization callback then there might be a problem because the data has not yet been initialized.1 Reference Documentation 395 . In that case the first script is usually a set of drops. init-method in an XML bean definition or Init