diff --git a/src/asciidoc/index.adoc b/src/asciidoc/index.adoc index 8d2acfb36b..b6f7321ceb 100644 --- a/src/asciidoc/index.adoc +++ b/src/asciidoc/index.adoc @@ -14,6 +14,15 @@ __Copies of this document may be made for your own use and for distribution to o 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-introduction]] = Overview of Spring Framework The Spring Framework is a lightweight solution and a potential one-stop-shop for @@ -36,6 +45,10 @@ This document is a reference guide to Spring Framework features. If you have any requests, comments, or questions on this document, please post them on the user mailing list or on the support forums at http://forum.spring.io/[]. + + + + [[overview]] == Introduction to Spring Framework Spring Framework is a Java platform that provides comprehensive infrastructure support @@ -54,6 +67,9 @@ Examples of how you, as an application developer, can use the Spring platform ad * Make a local Java method a management operation without having to deal with JMX APIs. * Make a local Java method a message handler without having to deal with JMS APIs. + + + [[overview-dependency-injection]] === Dependency Injection and Inversion of Control @@ -92,6 +108,9 @@ first-class objects that you can integrate into your own application(s). Numerou organizations and institutions use the Spring Framework in this manner to engineer robust, __maintainable__ applications. + + + [[overview-modules]] === Modules The Spring Framework consists of features organized into about 20 modules. These modules @@ -101,6 +120,8 @@ Programming), Instrumentation, and Test, as shown in the following diagram. .Overview of the Spring Framework image::images/spring-overview.png[] + + [[overview-core-container]] ==== Core Container The <> consists of the Core, Beans, Context, and @@ -130,6 +151,8 @@ arithmetic operators, named variables, and retrieval of objects by name from Spr IoC container. It also supports list projection and selection as well as common list aggregations. + + [[overview-data-access]] ==== Data Access/Integration The __Data Access/Integration__ layer consists of the JDBC, ORM, OXM, JMS and @@ -155,6 +178,8 @@ The <> module supports programmatic and declarative tra management for classes that implement special interfaces and for __all your POJOs (plain old Java objects)__. + + [[overview-web]] ==== Web The __Web__ layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules. @@ -177,6 +202,8 @@ or to a Spring MVC solution. The __Web-Portlet__ module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module. + + [[overview-aop-instrumentation]] ==== AOP and Instrumentation Spring's <> module provides an __AOP Alliance__-compliant @@ -191,12 +218,17 @@ The separate __Aspects__ module provides integration with AspectJ. The __Instrumentation__ module provides class instrumentation support and classloader implementations to be used in certain application servers. + + [[overview-testing]] ==== Test The __Test__ module supports the testing of Spring components with JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of those contexts. It also provides mock objects that you can use to test your code in isolation. + + + [[overview-usagescenarios]] === Usage scenarios The building blocks described previously make Spring a logical choice in many scenarios, @@ -244,6 +276,8 @@ Enterprise JavaBeans, enabling you to reuse your existing POJOs and wrap them in stateless session beans for use in scalable, fail-safe web applications that might need declarative security. + + [[dependency-management]] ==== Dependency Management and Naming Conventions Dependency management and dependency injection are different things. To get those nice @@ -363,6 +397,7 @@ necessarily use a different naming convention than Maven Central artifacts. | Extensive integration through STS with Maven, Roo, CloudFoundry |=== + [[overview-spring-dependencies]] ===== Spring Dependencies and Depending on Spring Although Spring provides integration and support for a huge range of enterprise and @@ -378,6 +413,7 @@ to the documentation of your dependency management system, or look at some sampl Spring itself uses Ivy to manage dependencies when it is building, and our samples mostly use Maven. + [[overview-maven-dependency-management]] ===== Maven Dependency Management If you are using Maven for dependency management you don't even need to supply the @@ -483,6 +519,7 @@ http://ebr.springsource.com/repository/app/[http://ebr.springsource.com/reposito that can be used to search for and download dependencies. It also has handy snippets of Maven and Ivy configuration that you can copy and paste if you are using those tools. + [[overview-ivy-dependency-management]] ===== Ivy Dependency Management If you prefer to use http://ant.apache.org/ivy[Ivy] to manage dependencies then there @@ -532,6 +569,8 @@ Ivy snippet ready for you to include in your dependencies section. For example ( name="org.springframework.core" rev="{spring-version}" conf="compile->runtime"/> ---- + + [[overview-logging]] ==== Logging Logging is a very important dependency for Spring because a) it is the only mandatory @@ -561,6 +600,7 @@ you get pretty nice looking logs just from the JDK (java.util.logging or JUL for You should find that your Spring application works and logs happily to the console out of the box in most situations, and that's important. + [[overview-not-using-commons-logging]] ===== Not Using Commons Logging Unfortunately, the runtime discovery algorithm in `commons-logging`, while convenient @@ -596,6 +636,7 @@ Now this application is probably broken because there is no implementation of th API on the classpath, so to fix it a new one has to be provided. In the next section we show you how to provide an alternative implementation of JCL using SLF4J as an example. + [[overview-logging-slf4j]] ===== Using SLF4J SLF4J is a cleaner dependency and more efficient at runtime than `commons-logging` @@ -673,6 +714,7 @@ on two libraries not four ( `jcl-over-slf4j` and `logback`). If you do that you also need to exclude the slf4j-api dependency from other external dependencies (not Spring), because you only want one version of that API on the classpath. + [[overview-logging-log4j]] ===== Using Log4J Many people use http://logging.apache.org/log4j[Log4j] as a logging framework for @@ -740,9 +782,18 @@ the container. That option isn't always open, but there are plenty of other sugg in the public domain for alternative approaches, and your mileage may vary depending on the exact version and feature set of the container. + + + + + [[spring-whats-new]] = What's New in Spring 3 + + + + [[new-in-3.0]] == New Features and Enhancements in Spring Framework 3.0 If you have been using the Spring Framework for some time, you will be aware that Spring @@ -758,6 +809,9 @@ Furthermore, Spring is compatible with J2EE 1.4 and Java EE 5, while at the same introducing some early support for Java EE 6. **** + + + [[new-in-3.0-intro]] === Java 5 The entire framework code has been revised to take advantage of Java 5 features like @@ -776,6 +830,9 @@ has been aligned with JSR-236 (Concurrency Utilities for Java EE 6) as far as po Furthermore, we provide support for asynchronous method invocations through the use of the new @Async annotation (or EJB 3.1's @Asynchronous annotation). + + + [[new-in-3.0-improved-docs]] === Improved documentation The Spring reference documentation has also substantially been updated to reflect all of @@ -785,6 +842,9 @@ have crept in. If you do spot any typos or even more serious errors, and you can few cycles during lunch, please do bring the error to the attention of the Spring team by http://jira.springframework.org/[raising an issue]. + + + [[new-in-3.0-new-tutorial]] === New articles and tutorials There are many excellent articles and tutorials that show how to get started with Spring @@ -808,6 +868,9 @@ For more information on Subversion (or in short SVN), see the project homepage a `http://subversion.apache.org/` ==== + + + [[new-in-3.0-modules-build]] === New module organization and build system The framework modules have been revised and are now managed separately with one @@ -841,6 +904,9 @@ us: * consistent dependency management * consistent generation of OSGi manifests + + + [[new-in-3.0-features-overview]] === Overview of new features This is a list of new features for Spring Framework 3.0. We will cover these features in @@ -856,6 +922,8 @@ more detail later in this section. * Early support for Java EE 6 * Embedded database support + + [[new-feature-java5]] ==== Core APIs updated for Java 5 BeanFactory interface returns typed bean instances as far as possible: @@ -875,6 +943,8 @@ New Java 5 based converter API and SPI: Typed ApplicationListener + + [[new-feature-el]] ==== Spring Expression Language Spring introduces an expression language which is similar to Unified EL in its syntax @@ -922,9 +992,12 @@ public class RewardsTestDatabase { } ---- + + [[new-feature-java-config]] ==== The Inversion of Control (IoC) container + [[new-java-configuration]] ===== Java based bean metadata Some core features from the JavaConfig project have been added to the Spring Framework @@ -1006,12 +1079,15 @@ public static void main(String[] args) { See <> for full information on `AnnotationConfigApplicationContext`. + [[new-bean-metadata-in-components]] ===== Defining bean metadata within components `@Bean` annotated methods are also supported inside Spring components. They contribute a factory bean definition to the container. See <> for more information + + [[new-feature-convert-and-format]] ==== General purpose type conversion system and field formatting system A general purpose <> has been introduced. The @@ -1022,6 +1098,8 @@ In addition, a <> SPI has been introduced for formatting field This SPI provides a simpler and more robust alternative to JavaBean PropertyEditors for use in client environments such as Spring MVC. + + [[new-feature-oxm]] ==== The Data Tier Object to XML mapping functionality (OXM) from the Spring Web Services project has been @@ -1029,12 +1107,15 @@ moved to the core Spring Framework now. The functionality is found in the `org.springframework.oxm` package. More information on the use of the `OXM` module can be found in the <> chapter. + + [[new-feature-rest]] ==== The Web Tier The most exciting new feature for the Web Tier is the support for building RESTful web services and web applications. There are also some new annotations that can be used in any web application. + [[new-feature-rest-support]] ===== Comprehensive REST support Server-side support for building RESTful applications has been provided as an extension @@ -1050,6 +1131,7 @@ mentioned earlier. Refer to the sections on <> and <> for more information. + [[new-feature-at-mvc]] ===== @MVC additions A `mvc` namespace has been introduced that greatly simplifies Spring MVC configuration. @@ -1059,11 +1141,15 @@ Additional annotations such as `@CookieValue` and `@RequestHeaders` have been ad <> for more information. + + [[new-feature-validation]] ==== Declarative model validation Several <>, including JSR 303 support that uses Hibernate Validator as the default provider. + + [[new-feature-jee-6]] ==== Early support for Java EE 6 We provide support for asynchronous method invocations through the use of the new @Async @@ -1071,23 +1157,35 @@ annotation (or EJB 3.1's @Asynchronous annotation). JSR 303, JSF 2.0, JPA 2.0, etc + + [[new-feature-embedded-databases]] ==== Support for embedded databases Convenient support for <>, including HSQL, H2, and Derby, is now provided. + + + + [[new-in-3.1]] == New Features and Enhancements in Spring Framework 3.1 This is a list of new features for Spring Framework 3.1. A number of features do not have dedicated reference documentation but do have complete Javadoc. In such cases, fully-qualified class names are given. See also <> + + + [[new-in-3.1-cache-abstraction]] === Cache Abstraction * <> * http://spring.io/blog/2011/02/23/spring-3-1-m1-cache-abstraction/[Cache Abstraction] (SpringSource team blog) + + + [[new-in-3.1-bean-definition-profiles]] === Bean Definition Profiles * http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/[XML @@ -1097,12 +1195,18 @@ fully-qualified class names are given. See also <> * See org.springframework.context.annotation.Configuration Javadoc * See org.springframework.context.annotation.Profile Javadoc + + + [[new-in-3.1-environment-abstraction]] === Environment Abstraction * http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/[Environment Abstraction] (SpringSource Team Blog) * See org.springframework.core.env.Environment Javadoc + + + [[new-in-3.1-property-source-abstraction]] === PropertySource Abstraction * http://blog.springsource.com/2011/02/15/spring-3-1-m1-unified-property-management/[Unified @@ -1111,6 +1215,9 @@ fully-qualified class names are given. See also <> * See org.springframework.core.env.PropertySource Javadoc * See org.springframework.context.annotation.PropertySource Javadoc + + + [[new-in-3.1-code-equivalent-xml-namespaces]] === Code equivalents for Spring's XML namespaces Code-based equivalents to popular Spring XML namespace elements @@ -1130,10 +1237,16 @@ Framework 3.0. * See org.springframework.context.annotation.EnableLoadTimeWeaving Javadoc * See org.springframework.beans.factory.aspectj.EnableSpringConfigured Javadoc + + + [[new-in-3.1-hibernate-4-support]] === Support for Hibernate 4.x * See Javadoc for classes within the new org.springframework.orm.hibernate4 package + + + [[new-in-3.1-test-context-profiles]] === TestContext framework support for @Configuration classes and bean definition profiles The `@ContextConfiguration` annotation now supports supplying `@Configuration` classes @@ -1151,10 +1264,16 @@ definition profiles in `ApplicationContext` integration tests. * See `org.springframework.test.context.support.DelegatingSmartContextLoader` Javadoc * See `org.springframework.test.context.support.AnnotationConfigContextLoader` Javadoc + + + [[new-in-3.1-c-namespace]] === c: namespace for more concise constructor injection * <> + + + [[new-in-3.1-injection-non-javabeans-setters]] === Support for injection against non-standard JavaBeans setters Prior to Spring Framework 3.1, in order to inject against a property method it had to @@ -1163,6 +1282,9 @@ must be void-returning. It is now possible in Spring XML to specify setter metho return any object type. This is useful when considering designing APIs for method-chaining, where setter methods return a reference to 'this'. + + + [[new-in-3.1-servlet-3-code-config]] === Support for Servlet 3 code-based configuration of Servlet Container The new `WebApplicationInitializer` builds atop Servlet 3.0's @@ -1173,10 +1295,16 @@ traditional web.xml. * http://bit.ly/lrDHja[Diff from Spring's Greenhouse reference application] demonstrating migration from web.xml to `WebApplicationInitializer` + + + [[new-in-3.1-servlet-3-multipart-resolver]] === Support for Servlet 3 MultipartResolver * See org.springframework.web.multipart.support.StandardServletMultipartResolver Javadoc + + + [[new-in-3.1-jpa-without-xml]] === JPA EntityManagerFactory bootstrapping without persistence.xml In standard JPA, persistence units get defined through `META-INF/persistence.xml` files @@ -1193,6 +1321,9 @@ entity scanning: a particularly fine match for Spring applications which rely on component scanning for Spring beans as well, possibly even bootstrapped using a code-based Servlet 3.0 initializer. + + + [[new-in-3.1-handler-method-controller-processing]] === New HandlerMethod-based Support Classes For Annotated Controller Processing Spring Framework 3.1 introduces a new set of support classes for processing requests @@ -1230,12 +1361,18 @@ but use of the new classes is recommended going forward. See <> for additional details and a list of features not available with the new support classes. + + + [[new-in-3.1-request-mapping-consumes-produces]] === "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 <> and <> + + + [[new-in-3.1-flash-redirect-attributes]] === Flash Attributes and RedirectAttributes Flash attributes can now be stored in a `FlashMap` and saved in the HTTP session to @@ -1247,6 +1384,9 @@ declaring a method argument of type `RedirectAttributes`. This method argument c also be used to get precise control over the attributes used in a redirect scenario. See <> for more details. + + + [[new-in-3.1-uri-template-var-enhancements]] === URI Template Variable Enhancements URI template variables from the current request are used in more places: @@ -1263,6 +1403,9 @@ URI template variables from the current request are used in more places: provided there is a registered Converter or PropertyEditor to convert from a String to the target object type. + + + [[new-in-3.1-mvc-valid-requestbody]] === @Valid On @RequestBody Controller Method Arguments An `@RequestBody` method argument can be annotated with `@Valid` to invoke automatic @@ -1270,11 +1413,17 @@ validation similar to the support for `@ModelAttribute` method arguments. A resu `MethodArgumentNotValidException` is handled in the `DefaultHandlerExceptionResolver` and results in a `400` response code. + + + [[new-in-3.1-mvc-requestpart]] === @RequestPart Annotation On Controller Method Arguments This new annotation provides access to the content of a "multipart/form-data" request part. See <> and <>. + + + [[new-in-3.1-mvc-uricomponentsbuilder]] === UriComponentsBuilder and UriComponents A new `UriComponents` class has been added, which is an immutable container of URI @@ -1289,10 +1438,17 @@ In most cases the new classes can be used as a more flexible alternative to the A `ServletUriComponentsBuilder` sub-class provides static factory methods to copy information from a Servlet request. See <>. + + + + [[new-in-3.2]] == New Features and Enhancements in Spring Framework 3.2 This section covers what's new in Spring Framework 3.2. See also <> + + + [[new-in-3.2-webmvc-async]] === Support for Servlet 3 based asynchronous request processing The Spring MVC programming model now provides explicit Servlet 3 async support. @@ -1308,12 +1464,18 @@ The Spring MVC programming model now provides explicit Servlet 3 async support. See <>. + + + [[new-in-3.2-spring-mvc-test]] === Spring MVC Test framework First-class support for testing Spring MVC applications with a fluent API and without a Servlet container. Server-side tests involve use of the `DispatcherServlet` while client-side REST tests rely on the `RestTemplate`. See <>. + + + [[new-in-3.2-webmvc-content-negotiation]] === Content negotiation improvements A `ContentNegotiationStrategy` is now available for resolving the requested media types @@ -1329,6 +1491,9 @@ The introduction of `ContentNegotiationManger` also enables selective suffix pat matching for incoming requests. For more details, see the Javadoc of http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.html#setUseRegisteredSuffixPatternMatch(boolean)[RequestMappingHandlerMapping.setUseRegisteredSuffixPatternMatch]. + + + [[new-in-3.2-webmvc-controller-advice]] === @ControllerAdvice annotation Classes annotated with `@ControllerAdvice` can contain `@ExceptionHandler`, @@ -1337,11 +1502,17 @@ methods across controller hierarchies as opposed to the controller hierarchy wit which they are declared. `@ControllerAdvice` is a component annotation allowing implementation classes to be auto-detected through classpath scanning. + + + [[new-in-3.2-matrix-variables]] === Matrix variables A new `@MatrixVariable` annotation adds support for extracting matrix variables from the request URI. For more details see <>. + + + [[new-in-3.2-dispatcher-servlet-initializer]] === Abstract base class for code-based Servlet 3+ container initialization An abstract base class implementation of the `WebApplicationInitializer` interface is @@ -1350,6 +1521,9 @@ to it. The new class is named `AbstractDispatcherServletInitializer` and its sub `AbstractAnnotationConfigDispatcherServletInitializer` can be used with Java-based Spring configuration. For more details see <>. + + + [[new-in-3.2-webmvc-exception-handler-support]] === ResponseEntityExceptionHandler class A convenient base class with an `@ExceptionHandler` method that handles standard Spring @@ -1361,6 +1535,9 @@ instead. See the revised <> including information on customizing the default Servlet container error page. + + + [[new-in-3.2-webmvc-generic-types-rest-template]] === Support for generic types in the RestTemplate and in @RequestBody arguments The `RestTemplate` can now read an HTTP response to a generic type (e.g. @@ -1375,6 +1552,9 @@ parameterized type. The new interface is implemented by the `Jaxb2CollectionHttpMessageConverter` that can read read a generic `Collection` where the generic type is a JAXB type annotated with `@XmlRootElement` or `@XmlType`. + + + [[new-in-3.2-webmvc-jackson-json]] === Jackson JSON 2 and related improvements The Jackson JSON 2 library is now supported. Due to packaging changes in the Jackson @@ -1384,6 +1564,9 @@ configuration improvements include support for pretty printing as well as a `JacksonObjectMapperFactoryBean` for convenient customization of an `ObjectMapper` in XML configuration. + + + [[new-in-3.2-webmvc-tiles3]] === Tiles 3 Tiles 3 is now supported in addition to Tiles 2.x. Configuring it should be very similar @@ -1395,6 +1578,9 @@ Also note that besides the version number change, the tiles dependencies have al changed. You will need to have a subset or all of `tiles-request-api`, `tiles-api`, `tiles-core`, `tiles-servlet`, `tiles-jsp`, `tiles-el`. + + + [[new-in-3.2-webmvc-request-body-arg-with-binding-result]] === @RequestBody improvements An `@RequestBody` or an `@RequestPart` argument can now be followed by an `Errors` @@ -1402,17 +1588,26 @@ argument making it possible to handle validation errors (as a result of an `@Val annotation) locally within the `@RequestMapping` method. `@RequestBody` now also supports a required flag. + + + [[new-in-3.2-webmvc-http-patch]] === HTTP PATCH method The HTTP request method `PATCH` may now be used in `@RequestMapping` methods as well as in the `RestTemplate` in conjunction with Apache HttpComponents HttpClient version 4.2 or later. The JDK `HttpURLConnection` does not support the `PATCH` method. + + + [[new-in-3.2-webmvc-mapped-interceptor-exclude-patterns]] === Excluded patterns in mapped interceptors Mapped interceptors now support URL patterns to be excluded. The MVC namespace and the MVC JavaConfig both expose these options. + + + [[new-in-3.2-meta-annotations]] === Using meta-annotations for injection points and for bean definition methods As of 3.2, Spring allows for `@Autowired` and `@Value` to be used as meta-annotations, @@ -1420,11 +1615,17 @@ e.g. to build custom injection annotations in combination with specific qualifie Analogously, you may build custom `@Bean` definition annotations for `@Configuration` classes, e.g. in combination with specific qualifiers, @Lazy, @Primary, etc. + + + [[new-in-3.2-jcache]] === Initial support for JCache 0.5 Spring provides a CacheManager adapter for JCache, building against the JCache 0.5 preview release. Full JCache support is coming next year, along with Java EE 7 final. + + + [[new-in-3.2-date-time-format-without-joda]] === Support for @DateTimeFormat without Joda Time The `@DateTimeFormat` annotation can now be used without needing a dependency on the @@ -1432,12 +1633,18 @@ Joda Time library. If Joda Time is not present the JDK `SimpleDateFormat` will b to parse and print date patterns. When Joda Time is present it will continue to be used in preference to `SimpleDateFormat`. + + + [[new-in-3.2-global-date-time-format]] === Global date & time formatting It is now possible to define global formats that will be used when parsing and printing date and time types. See <> for details. + + + [[new-in-3.2-testing]] === New Testing Features In addition to the aforementioned inclusion of the <> + + + [[new-in-3.2-concurrency]] === Concurrency refinements across the framework Spring Framework 3.2 includes fine-tuning of concurrent data structures in many parts of the framework, minimizing locks and generally improving the arrangements for highly concurrent creation of scoped/prototype beans. + + + [[new-in-3.2-build]] === New Gradle-based build and move to GitHub Building and contributing to the framework has never been simpler with our move to a @@ -1470,6 +1683,9 @@ source] section of the README and the https://github.com/SpringSource/spring-framework/blob/master/CONTRIBUTING.md[contributor guidelines] for complete details. + + + [[new-in-3.2-java7]] === Refined Java SE 7 / OpenJDK 7 support Last but not least, Spring Framework 3.2 comes with refined Java 7 support within the @@ -1477,6 +1693,11 @@ framework as well as through upgraded third-party dependencies: specifically, CG ASM 4.0 (both of which come as inlined dependencies with Spring now) and AspectJ 1.7 support (next to the existing AspectJ 1.6 support). + + + + + [[spring-core]] = Core Technologies This part of the reference documentation covers all of those technologies that are @@ -1510,9 +1731,16 @@ testing will hopefully convince you of this as well. * <> * <> + + + + [[beans]] == The IoC container + + + [[beans-introduction]] === Introduction to the Spring IoC container and beans This chapter covers the Spring Framework implementation of the Inversion of Control @@ -1550,6 +1778,9 @@ instantiated, assembled, and otherwise managed by a Spring IoC container. Otherw bean is simply one of many objects in your application. Beans, and the __dependencies__ among them, are reflected in the __configuration metadata__ used by a container. + + + [[beans-basics]] === Container overview The interface `org.springframework.context.ApplicationContext` represents the Spring IoC @@ -1586,6 +1817,8 @@ application. .The Spring IoC container image::images/container-magic.png[] + + [[beans-factory-metadata]] ==== Configuration metadata As the preceding diagram shows, the Spring IoC container consumes a form of @@ -1658,6 +1891,8 @@ classname. The value of the id attribute refers to collaborating objects. The XM referring to collaborating objects is not shown in this example; see <> for more information. + + [[beans-factory-instantiation]] ==== Instantiating a container Instantiating a Spring IoC container is straightforward. The location path or paths @@ -1739,6 +1974,7 @@ element refers to the name of another bean definition. This linkage between id a elements expresses the dependency between collaborating objects. For details of configuring an object's dependencies, see <>. + [[beans-factory-xml-import]] ===== Composing XML-based configuration metadata It can be useful to have bean definitions span multiple XML files. Often each individual @@ -1791,6 +2027,8 @@ locations, for example, through "${...}" placeholders that are resolved against system properties at runtime. ==== + + [[beans-factory-client]] ==== Using the container The `ApplicationContext` is the interface for an advanced factory capable of maintaining @@ -1820,6 +2058,9 @@ code should never use them. Indeed, your application code should have no calls t Spring's integration with web frameworks provides for dependency injection for various web framework classes such as controllers and JSF-managed beans. + + + [[beans-definition]] === Bean overview A Spring IoC container manages one or more __beans__. These beans are created with the @@ -1883,6 +2124,8 @@ supports this registration through the methods `registerSingleton(..)` and `registerBeanDefinition(..)`. However, typical applications work solely with beans defined through metadata bean definitions. + + [[beans-beanname]] ==== Naming beansBean naming conventions Every bean has one or more identifiers. These identifiers must be unique within the @@ -1917,6 +2160,7 @@ you are using Spring AOP it helps a lot when applying advice to a set of beans r by name. **** + [[beans-beanname-alias]] ===== Aliasing a bean outside the bean definition In a bean definition itself, you can supply more than one name for the bean, by using a @@ -1959,6 +2203,8 @@ Now each component and the main application can refer to the dataSource through that is unique and guaranteed not to clash with any other definition (effectively creating a namespace), yet they refer to the same bean. + + [[beans-factory-class]] ==== Instantiating beansInner class names A bean definition essentially is a recipe for creating one or more objects. The @@ -1995,6 +2241,7 @@ Notice the use of the `$` character in the name to separate the inner class name the outer class name. **** + [[beans-factory-class-ctor]] ===== Instantiation with a constructor When you create a bean by the constructor approach, all normal classes are usable by and @@ -2025,6 +2272,7 @@ For details about the mechanism for supplying arguments to the constructor (if r and setting object instance properties after the object is constructed, see <>. + [[beans-factory-class-static-factory-method]] ===== Instantiation with a static factory method When defining a bean that you create with a static factory method, you use the `class` @@ -2064,6 +2312,7 @@ For details about the mechanism for supplying (optional) arguments to the factor and setting object instance properties after the object is returned from the factory, see <>. + [[beans-factory-class-instance-factory-method]] ===== Instantiation using an instance factory method Similar to instantiation through a <>. ==== + + + [[beans-dependencies]] === Dependencies A typical enterprise application does not consist of a single object (or bean in the @@ -2159,6 +2411,8 @@ present what the end-user sees as a coherent application. This next section expl you go from defining a number of bean definitions that stand alone to a fully realized application where objects collaborate to achieve a goal. + + [[beans-factory-collaborators]] ==== Dependency injection __Dependency injection__ (DI) is a process whereby objects define their dependencies, @@ -2179,6 +2433,7 @@ which allow for stub or mock implementations to be used in unit tests. DI exists in two major variants, <> and <>. + [[beans-constructor-injection]] ===== Constructor-based dependency injection __Constructor-based__ DI is accomplished by the container invoking a constructor with a @@ -2345,6 +2600,7 @@ public class ExampleBean { ---- -- + [[beans-setter-injection]] ===== Setter-based dependency injectionConstructor-based or setter-based DI? __Setter-based__ DI is accomplished by the container calling setter methods on your @@ -2403,6 +2659,7 @@ you. A legacy class may not expose any setter methods, and so constructor inject the only available DI. **** + [[beans-dependency-resolution]] ===== Dependency resolution processCircular dependencies The container performs bean dependency resolution as follows: @@ -2473,6 +2730,7 @@ methods (such as a <>) are invoked. + [[beans-some-examples]] ===== Examples of dependency injection The following example uses XML-based configuration metadata for setter-based DI. A small @@ -2610,6 +2868,8 @@ contains the `static` factory method, although in this example it is. An instanc from the use of the `factory-bean` attribute instead of the `class` attribute), so details will not be discussed here. + + [[beans-factory-properties-detailed]] ==== Dependencies and configuration in detail As mentioned in the previous section, you can define bean properties and constructor @@ -2617,6 +2877,7 @@ arguments as references to other managed beans (collaborators), or as values def inline. Spring's XML-based configuration metadata supports sub-element types within its `` and `` elements for this purpose. + [[beans-value-element]] ===== Straight values (primitives, Strings, and so on) @@ -2747,6 +3008,7 @@ brings value is in the configuration of <> in a `ProxyFactoryBean` bean definition. Using elements when you specify the interceptor names prevents you from misspelling an interceptor id. + [[beans-ref-element]] ===== References to other beans (collaborators) The `ref` element is the final element inside a `` or `` @@ -2813,6 +3075,7 @@ container with a proxy that will have the same name as the parent bean. ---- + [[beans-inner-beans]] ===== Inner beans A `` element inside the `` or `` elements defines a @@ -2837,6 +3100,7 @@ these values. It also ignores the `scope` flag. Inner beans are __always__ anony they are __always__ created with the outer bean. It is __not__ possible to inject inner beans into collaborating beans other than into the enclosing bean. + [[beans-collection-elements]] ===== Collections In the ``, ``, ``, and `` elements, you set the properties @@ -3006,6 +3270,7 @@ available by reflection. Thus Spring's type conversion infrastructure recognizes various value elements as being of type `Float`, and the string values `9.99, 2.75`, and `3.99` are converted into an actual `Float` type. + [[beans-null-element]] ===== Null and empty string values Spring treats empty arguments for properties and the like as empty `Strings`. The @@ -3034,6 +3299,7 @@ The preceding example is equivalent to the following Java code: The above configuration is equivalent to the following Java code: `exampleBean.setEmail(null)`. + [[beans-p-namespace]] ===== XML shortcut with the p-namespace The p-namespace enables you to use the `bean` element's attributes, instead of nested @@ -3115,6 +3381,7 @@ communicate this to your team members, to avoid producing XML documents that use three approaches at the same time. ==== + [[beans-c-namespace]] ===== XML shortcut with the c-namespace Similar to the <>, the __c-namespace__, newly introduced in Spring @@ -3175,6 +3442,7 @@ In practice, the constructor resolution arguments so unless one really needs to, we recommend using the name notation through-out your configuration. + [[beans-compound-property-names]] ===== Compound property names You can use compound or nested property names when you set bean properties, as long as @@ -3194,6 +3462,8 @@ property, and that final `sammy` property is being set to the value `123`. In or this to work, the `fred` property of `foo`, and the `bob` property of `fred` must not be `null` after the bean is constructed, or a `NullPointerException` is thrown. + + [[beans-factory-dependson]] ==== Using depends-on @@ -3237,6 +3507,8 @@ only, a corresponding destroy time dependency. Dependent beans that define a itself being destroyed. Thus `depends-on` can also control shutdown order. ==== + + [[beans-factory-lazy-init]] ==== Lazy-initialized beans By default, `ApplicationContext` implementations eagerly create and configure all @@ -3278,6 +3550,8 @@ You can also control lazy-initialization at the container level by using the ---- + + [[beans-factory-autowire]] ==== Autowiring collaborators The Spring container can __autowire__ relationships between collaborating beans. You can @@ -3340,6 +3614,7 @@ contain the corresponding bean names. You can combine autowire behavior with dependency checking, which is performed after autowiring completes. + [[beans-autowired-exceptions]] ===== Limitations and disadvantages of autowiring Autowiring works best when it is used consistently across a project. If autowiring is @@ -3374,6 +3649,7 @@ In the latter scenario, you have several options: * If you are using Java 5 or later, implement the more fine-grained control available with annotation-based configuration, as described in <>. + [[beans-factory-autowire-candidate]] ===== Excluding a bean from autowiring On a per-bean basis, you can exclude a bean from autowiring. In Spring's XML format, set @@ -3394,6 +3670,8 @@ These techniques are useful for beans that you never want to be injected into ot beans by autowiring. It does not mean that an excluded bean cannot itself be configured using autowiring. Rather, the bean itself is not a candidate for autowiring other beans. + + [[beans-factory-method-injection]] ==== Method injection In most application scenarios, most beans in the container are @@ -3456,6 +3734,7 @@ You can read more about the motivation for Method Injection in http://blog.springsource.com/2004/08/06/method-injection/[this blog entry]. **** + [[beans-factory-lookup-method-injection]] ===== Lookup method injection Lookup method injection is the ability of the container to override methods on @@ -3549,6 +3828,7 @@ interface as opposed to a Spring-specific lookup interface. Consult the JavaDocs these classes for additional information. ==== + [[beans-factory-arbitrary-method-replacement]] ===== Arbitrary method replacement A less useful form of method injection than lookup method Injection is the ability to @@ -3629,6 +3909,9 @@ Because the number of arguments is often enough to distinguish between each poss choice, this shortcut can save a lot of typing, by allowing you to type only the shortest string that will match an argument type. + + + [[beans-factory-scopes]] === Bean scopes When you create a bean definition, you create a __recipe__ for creating actual instances @@ -3684,6 +3967,8 @@ For instructions on how to register this or any other custom scope, see <>. ==== + + [[beans-factory-scopes-singleton]] ==== The singleton scope Only one __shared__ instance of a singleton bean is managed, and all requests for beans @@ -3716,6 +4001,8 @@ in Spring__. To define a bean as a singleton in XML, you would write, for exampl ---- + + [[beans-factory-scopes-prototype]] ==== The prototype scope The non-singleton, prototype scope of bean deployment results in the __creation of a new @@ -3756,6 +4043,8 @@ replacement for the Java `new` operator. All lifecycle management past that poin be handled by the client. (For details on the lifecycle of a bean in the Spring container, see <>.) + + [[beans-factory-scopes-sing-prot-interaction]] ==== Singleton beans with prototype-bean dependencies When you use singleton-scoped beans with dependencies on prototype beans, be aware that @@ -3771,6 +4060,8 @@ __once__, when the Spring container is instantiating the singleton bean and reso and injecting its dependencies. If you need a new instance of a prototype bean at runtime more than once, see <> + + [[beans-factory-scopes-other]] ==== Request, session, and global session scopes The `request`, `session`, and `global session` scopes are __only__ available if you use @@ -3779,6 +4070,7 @@ a web-aware Spring `ApplicationContext` implementation (such as such as the `ClassPathXmlApplicationContext`, you get an `IllegalStateException` complaining about an unknown bean scope. + [[beans-factory-scopes-other-web-configuration]] ===== Initial web configuration To support the scoping of beans at the `request`, `session`, and `global session` levels @@ -3841,6 +4133,7 @@ the same thing, namely bind the HTTP request object to the `Thread` that is serv that request. This makes beans that are request- and session-scoped available further down the call chain. + [[beans-factory-scopes-request]] ===== Request scope Consider the following bean definition: @@ -3859,6 +4152,7 @@ created from the same `loginAction` bean definition will not see these changes i they are particular to an individual request. When the request completes processing, the bean that is scoped to the request is discarded. + [[beans-factory-scopes-session]] ===== Session scope Consider the following bean definition: @@ -3879,6 +4173,7 @@ changes in state, because they are particular to an individual HTTP `Session`. W HTTP `Session` is eventually discarded, the bean that is scoped to that particular HTTP `Session` is also discarded. + [[beans-factory-scopes-global-session]] ===== Global session scope Consider the following bean definition: @@ -3900,6 +4195,7 @@ If you write a standard Servlet-based web application and you define one or more as having `global session` scope, the standard HTTP `Session` scope is used, and no error is raised. + [[beans-factory-scopes-other-injection]] ===== Scoped beans as dependencies The Spring IoC container manages not only the instantiation of your objects (beans), but @@ -4035,12 +4331,15 @@ interfaces. For more detailed information about choosing class-based or interface-based proxying, see <>. + + [[beans-factory-scopes-custom]] ==== Custom scopes As of Spring 2.0, the bean scoping mechanism is extensible. You can define your own scopes, or even redefine existing scopes, although the latter is considered bad practice and you __cannot__ override the built-in `singleton` and `prototype` scopes. + [[beans-factory-scopes-custom-creating]] ===== Creating a custom scope To integrate your custom scope(s) into the Spring container, you need to implement the @@ -4095,6 +4394,7 @@ identifier can be the session identifier. String getConversationId() ---- + [[beans-factory-scopes-custom-using]] ===== Using a custom scope After you write and test one or more custom `Scope` implementations, you need to make @@ -4184,9 +4484,14 @@ When you place in a `FactoryBean` implementation, it is the bean itself that is scoped, not the object returned from `getObject()`. ==== + + + [[beans-factory-nature]] === Customizing the nature of a bean + + [[beans-factory-lifecycle]] ==== Lifecycle callbacks To interact with the container's management of the bean lifecycle, you can implement the @@ -4218,6 +4523,7 @@ startup and shutdown process as driven by the container's own lifecycle. The lifecycle callback interfaces are described in this section. + [[beans-factory-lifecycle-initializingbean]] ===== Initialization callbacks The `org.springframework.beans.factory.InitializingBean` interface allows a bean to @@ -4275,6 +4581,7 @@ public class AnotherExampleBean implements InitializingBean { but does not couple the code to Spring. + [[beans-factory-lifecycle-disposablebean]] ===== Destruction callbacks Implementing the `org.springframework.beans.factory.DisposableBean` interface allows a @@ -4332,6 +4639,7 @@ public class AnotherExampleBean implements DisposableBean { ... but does not couple the code to Spring. + [[beans-factory-lifecycle-default-init-destroy-methods]] ===== Default initialization and destroy methods When you write initialization and destroy method callbacks that do not use the @@ -4409,6 +4717,7 @@ interceptors to the init method, because doing so would couple the lifecycle of target bean with its proxy/interceptors and leave strange semantics when your code interacts directly to the raw target bean. + [[beans-factory-lifecycle-combined-effects]] ===== Combining lifecycle mechanisms As of Spring 2.5, you have three options for controlling bean lifecycle behavior: the @@ -4440,6 +4749,7 @@ Destroy methods are called in the same order: * `destroy()` as defined by the `DisposableBean` callback interface * A custom configured `destroy()` method + [[beans-factory-lifecycle-processor]] ===== Startup and shutdown callbacks The `Lifecycle` interface defines the essential methods for any object that has its own @@ -4550,6 +4860,7 @@ automatically for a standard context implementation). The "phase" value as well "depends-on" relationships will determine the startup order in the same way as described above. + [[beans-factory-shutdown]] ===== Shutting down the Spring IoC container gracefully in non-web applications [NOTE] @@ -4590,6 +4901,8 @@ public final class Boot { } ---- + + [[beans-factory-aware]] ==== ApplicationContextAware and `BeanNameAware` @@ -4645,6 +4958,8 @@ The callback is invoked after population of normal bean properties but before an initialization callback such as `InitializingBean` s __afterPropertiesSet__ or a custom init-method. + + [[aware-list]] ==== Other Aware interfaces @@ -4726,6 +5041,9 @@ Note again that usage of these interfaces ties your code to the Spring API and d follow the Inversion of Control style. As such, they are recommended for infrastructure beans that require programmatic access to the container. + + + [[beans-child-bean-definitions]] === Bean definition inheritance A bean definition can contain a lot of configuration information, including constructor @@ -4810,6 +5128,9 @@ must make sure to set the __abstract__ attribute to __true__, otherwise the appl context will actually (attempt to) pre-instantiate the `abstract` bean. ==== + + + [[beans-factory-extension]] === Container Extension Points Typically, an application developer does not need to subclass `ApplicationContext` @@ -4817,6 +5138,8 @@ implementation classes. Instead, the Spring IoC container can be extended by plu implementations of special integration interfaces. The next few sections describe these integration interfaces. + + [[beans-factory-extension-bpp]] ==== Customizing beans using a BeanPostProcessor @@ -4916,6 +5239,7 @@ Spring will access other beans for matching them by type. The following examples show how to write, register, and use `BeanPostProcessors` in an `ApplicationContext`. + [[beans-factory-extension-bpp-examples-hw]] ===== Example: Hello World, BeanPostProcessor-style @@ -5009,6 +5333,7 @@ Bean 'messenger' created : org.springframework.scripting.groovy.GroovyMessenger@ org.springframework.scripting.groovy.GroovyMessenger@272961 ---- + [[beans-factory-extension-bpp-examples-rabpp]] ===== Example: The RequiredAnnotationBeanPostProcessor @@ -5019,6 +5344,8 @@ container. An example is Spring's `RequiredAnnotationBeanPostProcessor` - a that JavaBean properties on beans that are marked with an (arbitrary) annotation are actually (configured to be) dependency-injected with a value. + + [[beans-factory-extension-factory-postprocessors]] ==== Customizing configuration metadata with a BeanFactoryPostProcessor @@ -5078,6 +5405,7 @@ Thus, marking it for lazy initialization will be ignored, and the `default-lazy-init` attribute to `true` on the declaration of your `` element. ==== + [[beans-factory-placeholderconfigurer]] ===== Example: the Class name substitution PropertyPlaceholderConfigurer @@ -5178,6 +5506,7 @@ fails when it is about to be created, which is during the `preInstantiateSinglet phase of an `ApplicationContext` for a non-lazy-init bean. ==== + [[beans-factory-overrideconfigurer]] ===== Example: the PropertyOverrideConfigurer @@ -5241,6 +5570,8 @@ property overriding with a dedicated configuration element: ---- + + [[beans-factory-extension-factorybean]] ==== Customizing instantiation logic with a FactoryBean @@ -5274,6 +5605,9 @@ with an id of `myBean`, invoking `getBean("myBean")` on the container returns th product of the `FactoryBean`; whereas, invoking `getBean("&myBean")` returns the `FactoryBean` instance itself. + + + [[beans-annotation-config]] === Annotation-based container configurationAre annotations better than XML for configuring Spring? **** @@ -5354,6 +5688,8 @@ it only checks for `@Autowired` beans in your controllers, and not your services <> for more information. ==== + + [[beans-required-annotation]] ==== @Required @@ -5384,6 +5720,8 @@ or the like later on. It is still recommended that you put assertions into the b class itself, for example, into an init method. Doing so enforces those required references and values even when you use the class outside of a container. + + [[beans-autowired-annotation]] ==== @Autowired @@ -5572,6 +5910,8 @@ annotations within your own `BeanPostProcessor` or `BeanFactoryPostProcessor` ty any). These types must be 'wired up' explicitly via XML or using a Spring `@Bean` method. ==== + + [[beans-autowired-annotation-qualifiers]] ==== Fine-tuning annotation-based autowiring with qualifiers Because autowiring by type may lead to multiple candidates, it is often necessary to @@ -5918,6 +6258,8 @@ the following example. ---- + + [[beans-custom-autowire-configurer]] ==== CustomAutowireConfigurer @@ -5951,6 +6293,8 @@ Regardless of the Java version, when multiple beans qualify as autowire candidat determination of a "primary" candidate is the same: if exactly one bean definition among the candidates has a `primary` attribute set to `true`, it will be selected. + + [[beans-resource-annotation]] ==== @Resource @@ -6035,6 +6379,8 @@ public class MovieRecommender { } ---- + + [[beans-postconstruct-and-predestroy-annotations]] ==== @PostConstruct and `@PreDestroy` @@ -6072,6 +6418,9 @@ For details about the effects of combining various lifecycle mechanisms, see <>. ==== + + + [[beans-classpath-scanning]] === Classpath scanning and managed components Most examples in this chapter use XML to specify the configuration metadata that @@ -6095,6 +6444,8 @@ than using the traditional XML files. Take a look at the `@Configuration`, `@Bea `@Import`, and `@DependsOn` annotations for examples of how to use these new features. ==== + + [[beans-stereotype-annotations]] ==== @Component and further stereotype annotations @@ -6117,6 +6468,8 @@ choosing between using `@Component` or `@Service` for your service layer, `@Serv clearly the better choice. Similarly, as stated above, `@Repository` is already supported as a marker for automatic exception translation in your persistence layer. + + [[beans-scanning-autodetection]] ==== Automatically detecting classes and registering bean definitions Spring can automatically detect stereotyped classes and register corresponding @@ -6196,6 +6549,8 @@ You can disable the registration of `AutowiredAnnotationBeanPostProcessor` and with a value of false. ==== + + [[beans-scanning-filters]] ==== Using filters to customize scanning By default, classes annotated with `@Component`, `@Repository`, `@Service`, @@ -6256,6 +6611,8 @@ detection of classes annotated with `@Component`, `@Repository`, `@Service`, or `@Controller`. ==== + + [[beans-factorybeans-annotations]] ==== Defining bean metadata within components Spring components can also contribute bean definition metadata to the container. You do @@ -6339,6 +6696,8 @@ classes `@Bean` methods create bean metadata references to collaborating objects Methods are__not__ invoked with normal Java semantics. In contrast, calling a method or field within a `@Component` classes `@Bean` method __has__ standard Java semantics. + + [[beans-scanning-name-generator]] ==== Naming autodetected components When a component is autodetected as part of the scanning process, its bean name is @@ -6394,6 +6753,8 @@ As a general rule, consider specifying the name with the annotation whenever oth components may be making explicit references to it. On the other hand, the auto-generated names are adequate whenever the container is responsible for wiring. + + [[beans-scanning-scope-resolver]] ==== Providing a scope for autodetected components As with Spring-managed components in general, the default and most common scope for @@ -6448,6 +6809,8 @@ the following configuration will result in standard JDK dynamic proxies: ---- + + [[beans-scanning-qualifiers]] ==== Providing qualifier metadata with annotations The `@Qualifier` annotation is discussed in <>. @@ -6498,6 +6861,9 @@ __of the same type__ to provide variations in their qualifier metadata, because metadata is provided per-instance rather than per-class. ==== + + + [[beans-standard-annotations]] === Using JSR 330 Standard Annotations Starting with Spring 3.0, Spring offers support for JSR-330 standard annotations @@ -6522,6 +6888,8 @@ You can add the following dependency to your file pom.xml: ---- ==== + + [[beans-inject-named]] ==== Dependency Injection with @Inject and `@Named` @@ -6567,6 +6935,8 @@ public class SimpleMovieLister { } ---- + + [[beans-named]] ==== @Named: a standard equivalent to the `@Component` annotation @@ -6625,6 +6995,8 @@ component-scanning in the exact same way as when using Spring annotations: ---- + + [[beans-standard-annotations-limitations]] ==== Limitations of the standard approach When working with standard annotations, it is important to know that some significant @@ -6671,9 +7043,14 @@ Nevertheless, this one is only intended to be used for creating your own annotat | no equivalent |=== + + + [[beans-java]] === Java-based container configuration + + [[beans-java-basic-concepts]] ==== Basic concepts: Full @Configuration vs 'lite' @Beans mode? @Bean and `@Configuration` @@ -6733,6 +7110,8 @@ The `@Bean` and `@Configuration` annotations will be discussed in depth in the s below. First, however, we'll cover the various ways of creating a spring container using Java-based configuration. + + [[beans-java-instantiating-container]] ==== Instantiating the Spring container using AnnotationConfigApplicationContext The sections below document Spring's `AnnotationConfigApplicationContext`, new in Spring @@ -6748,6 +7127,7 @@ When `@Component` and JSR-330 classes are provided, they are registered as bean definitions, and it is assumed that DI metadata such as `@Autowired` or `@Inject` are used within those classes where necessary. + [[beans-java-instantiating-container-contstructor]] ===== Simple construction In much the same way that Spring XML files are used as input when instantiating a @@ -6783,6 +7163,7 @@ public static void main(String[] args) { The above assumes that `MyServiceImpl`, `Dependency1` and `Dependency2` use Spring dependency injection annotations such as `@Autowired`. + [[beans-java-instantiating-container-register]] ===== Building the container programmatically using register(Class...) @@ -6803,6 +7184,7 @@ public static void main(String[] args) { } ---- + [[beans-java-instantiating-container-scan]] ===== Enabling component scanning with scan(String...) @@ -6842,6 +7224,7 @@ during the call to `scan()`, and upon `refresh()` all its `@Bean` methods will b processed and registered as bean definitions within the container. ==== + [[beans-java-instantiating-container-web]] ===== Support for web applications with AnnotationConfigWebApplicationContext @@ -6906,6 +7289,8 @@ init-param: ---- + + [[beans-java-bean-annotation]] ==== Using the @Bean annotation @@ -6918,6 +7303,7 @@ The annotation supports some of the attributes offered by ``, such as: You can use the `@Bean` annotation in a `@Configuration`-annotated or in a `@Component`-annotated class. + [[beans-java-declaring-a-bean]] ===== Declaring a bean To declare a bean, simply annotate a method with the `@Bean` annotation. You use this @@ -6958,6 +7344,7 @@ Both declarations make a bean named `transferService` available in the transferService -> com.acme.TransferServiceImpl ---- + [[beans-java-lifecycle-callbacks]] ===== Receiving lifecycle callbacks Any classes defined with the `@Bean` annotation support the regular lifecycle callbacks @@ -7032,6 +7419,7 @@ When you work directly in Java, you can do anything you like with your objects a not always need to rely on the container lifecycle! ==== + [[beans-java-specifying-bean-scope]] ===== Specifying bean scope @@ -7089,6 +7477,7 @@ public Service userService() { } ---- + [[beans-java-customizing-bean-naming]] ===== Customizing bean naming By default, configuration classes use a `@Bean` method's name as the name of the @@ -7108,6 +7497,7 @@ public class AppConfig { } ---- + [[beans-java-bean-aliasing]] ===== Bean aliasing As discussed in <>, it is sometimes desirable to give a single bean @@ -7128,6 +7518,8 @@ public class AppConfig { } ---- + + [[beans-java-configuration-annotation]] ==== Using the @Configuration annotation @@ -7136,6 +7528,7 @@ bean definitions. `@Configuration` classes declare beans via public `@Bean` anno methods. Calls to `@Bean` methods on `@Configuration` classes can also be used to define inter-bean dependencies. See <> for a general introduction. + [[beans-java-injecting-dependencies]] ===== Injecting inter-bean dependencies When `@Bean` s have dependencies on one another, expressing that dependency is as simple @@ -7170,6 +7563,7 @@ declared within a `@Configuration` class. You cannot declare inter-bean dependen using plain `@Component` classes. ==== + [[beans-java-method-injection]] ===== Lookup method injection As noted earlier, <> is an @@ -7222,6 +7616,7 @@ public CommandManager commandManager() { } ---- + [[beans-java-further-information-java-config]] ===== Further information about how Java-based configuration works internally The following example shows a `@Bean` annotated method being called twice: @@ -7278,9 +7673,12 @@ startup-time: * They should have a constructor with no arguments ==== + + [[beans-java-composing-configuration-classes]] ==== Composing Java-based configurations + [[beans-java-using-import]] ===== Using the @Import annotation @@ -7455,6 +7853,7 @@ way, navigating `@Configuration` classes and their dependencies becomes no diffe than the usual process of navigating interface-based code. -- + [[beans-java-combining]] ===== Combining Java and XML configuration Spring's `@Configuration` class support does not aim to be a 100% complete replacement @@ -7628,6 +8027,9 @@ public static void main(String[] args) { } ---- + + + [[context-load-time-weaver]] === Registering a LoadTimeWeaver @@ -7664,6 +8066,9 @@ support>> where load-time weaving may be necessary for JPA class transformation. the `LocalContainerEntityManagerFactoryBean` Javadoc for more detail. For more on AspectJ load-time weaving, see <>. + + + [[context-introduction]] === Additional Capabilities of the ApplicationContext @@ -7689,6 +8094,8 @@ package also provides the following functionality: particular layer, such as the web layer of an application, through the `HierarchicalBeanFactory` interface. + + [[context-functionality-messagesource]] ==== Internationalization using MessageSource @@ -7893,6 +8300,8 @@ reloading of bundle property files (while efficiently caching them in between). out the `ReloadableResourceBundleMessageSource` javadoc for details. ==== + + [[context-functionality-events]] ==== Standard and Custom Events Event handling in the `ApplicationContext` is provided through the `ApplicationEvent` @@ -8071,6 +8480,8 @@ http://www.enterpriseintegrationpatterns.com[pattern-oriented], event-driven architectures that build upon the well-known Spring programming model. ==== + + [[context-functionality-resources]] ==== Convenient access to low-level resources For optimal usage and understanding of application contexts, users should generally @@ -8102,6 +8513,8 @@ classpath location. You can also use location paths (resource strings) with spec prefixes to force loading of definitions from the classpath or a URL, regardless of the actual context type. + + [[context-create]] ==== Convenient ApplicationContext instantiation for web applications @@ -8149,6 +8562,8 @@ in any subdirectory of "WEB-INF". You can use `ContextLoaderServlet` instead of `ContextLoaderListener`. The Servlet uses the `contextConfigLocation` parameter just as the listener does. + + [[context-deploy-rar]] ==== 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 @@ -8190,6 +8605,9 @@ access from the outside, it could for example export RMI endpoints, which of cou be used by other application modules on the same machine. ==== + + + [[beans-beanfactory]] === The BeanFactory The `BeanFactory` provides the underlying basis for Spring's IoC functionality but it is @@ -8205,6 +8623,8 @@ 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. + + [[context-introduction-ctx-vs-beanfactory]] ==== BeanFactory or `ApplicationContext`? @@ -8287,6 +8707,8 @@ implementations in the vast majority of Spring-backed applications, especially w using `BeanFactoryPostProcessors` and `BeanPostProcessors`. These mechanisms implement important functionality such as property placeholder replacement and AOP. + + [[beans-servicelocator]] ==== Glue code and the evil singleton It is best to write most application code in a dependency-injection (DI) style, where @@ -8318,9 +8740,16 @@ locator that is described in this http://blog.springsource.com/2007/06/11/using-a-shared-parent-application-context-in-a-multi-war-spring-application/[SpringSource team blog entry]. + + + + [[resources]] == Resources + + + [[resources-introduction]] === Introduction Java's standard `java.net.URL` class and standard handlers for various URL prefixes @@ -8332,6 +8761,9 @@ prefixes (similar to existing handlers for prefixes such as `http:`), this is ge 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. + + + [[resources-resource]] === The Resource interface @@ -8405,12 +8837,17 @@ It is important to note that the `Resource` abstraction does not replace functio it wraps it where possible. For example, a `UrlResource` wraps a URL, and uses the wrapped `URL` to do its work. + + + [[resources-implementations]] === Built-in Resource implementations There are a number of `Resource` implementations that come supplied straight out of the box in Spring: + + [[resources-implementations-urlresource]] ==== UrlResource @@ -8430,6 +8867,8 @@ create an appropriate specialized `Resource` for that prefix. However, if it doe recognize the prefix, it will assume the this is just a standard URL string, and will create a `UrlResource`. + + [[resources-implementations-classpathresource]] ==== ClassPathResource @@ -8449,12 +8888,16 @@ takes a `String` argument which is meant to represent a path. For the latter cas JavaBeans `PropertyEditor` will recognize the special prefix `classpath:` on the string path, and create a `ClassPathResource` in that case. + + [[resources-implementations-filesystemresource]] ==== FileSystemResource This is a `Resource` implementation for `java.io.File` handles. It obviously supports resolution as a `File`, and as a `URL`. + + [[resources-implementations-servletcontextresource]] ==== ServletContextResource @@ -8467,6 +8910,8 @@ filesystem. Whether or not it's expanded and on the filesystem like this, or acc directly from the JAR or somewhere else like a DB (it's conceivable) is actually dependent on the Servlet container. + + [[resources-implementations-inputstreamresource]] ==== InputStreamResource @@ -8479,6 +8924,8 @@ opened resource - therefore returning `true` from `isOpen()`. Do not use it if y to keep the resource descriptor somewhere, or if you need to read a stream multiple times. + + [[resources-implementations-bytearrayresource]] ==== ByteArrayResource @@ -8488,6 +8935,9 @@ This is a `Resource` implementation for a given byte array. It creates a It's useful for loading content from any given byte array, without having to resort to a single-use `InputStreamResource`. + + + [[resources-resourceloader]] === The ResourceLoader @@ -8573,6 +9023,9 @@ The following table summarizes the strategy for converting `String` s to `Resour | Depends on the underlying `ApplicationContext`. |=== + + + [[resources-resourceloaderaware]] === The ResourceLoaderAware interface @@ -8612,6 +9065,9 @@ constructor argument, or method parameter that is expecting the `ResourceLoader` long as the field, constructor, or method in question carries the `@Autowired` annotation. For more information, see <>. + + + [[resources-as-dependencies]] === Resources as dependencies @@ -8657,9 +9113,14 @@ used. The following two examples show how to force a `ClassPathResource` and a ---- + + + [[resources-app-ctx]] === Application contexts and Resource paths + + [[resources-app-ctx-construction]] ==== Constructing application contexts An application context constructor (for a specific application context type) generally @@ -8705,6 +9166,7 @@ ApplicationContext ctx = `FileSystemXmlApplicationContext`. If it is subsequently used as a `ResourceLoader`, any unprefixed paths will still be treated as filesystem paths. + [[resources-app-ctx-classpathxml]] ===== Constructing ClassPathXmlApplicationContext instances - shortcuts @@ -8740,6 +9202,8 @@ ApplicationContext ctx = new ClassPathXmlApplicationContext( Please do consult the Javadocs for the `ClassPathXmlApplicationContext` class for details of the various constructors. + + [[resources-app-ctx-wildcards-in-resource-paths]] ==== Wildcards in application context constructor resource paths The resource paths in application context constructor values may be a simple path (as @@ -8759,6 +9223,7 @@ resolved at construction time. It has nothing to do with the `Resource` type its It's not possible to use the `classpath*:` prefix to construct an actual `Resource`, as a resource points to just one resource at a time. + [[resources-app-ctx-ant-patterns-in-paths]] ===== Ant-style Patterns When the path location contains an Ant-style pattern, for example: @@ -8803,6 +9268,7 @@ environments, but will fail in others, and it is strongly recommended that the w resolution of resources coming from jars be thoroughly tested in your specific environment before you rely on it. + [[resources-classpath-wildcards]] ===== The Classpath*: portability classpath*: prefix @@ -8841,6 +9307,7 @@ used on the last non-wildcard path segment to get all the matching resources in class loader hierarchy, and then off each resource the same PathMatcher resolution strategy described above is used for the wildcard subpath. + [[resources-wildcards-in-path-other-stuff]] ===== Other notes relating to wildcards Please note that " `classpath*:`" when combined with Ant-style patterns will only work @@ -8875,6 +9342,8 @@ classloader locations, the actual end resource may not be underneath. Therefore, preferably, use " `classpath*:`" with the same Ant-style pattern in such a case, which will search all class path locations that contain the root package. + + [[resources-filesystemresource-caveats]] ==== FileSystemResource caveats @@ -8940,9 +9409,16 @@ ApplicationContext ctx = new FileSystemXmlApplicationContext("file:/conf/context.xml"); ---- + + + + [[validation]] == Validation, Data Binding, and Type Conversion + + + [[validation-introduction]] === IntroductionJSR-303/JSR-349 Bean Validation @@ -8985,6 +9461,9 @@ higher-level "format" package for formatting UI field values. These new packages used as simpler alternatives to PropertyEditors, and will also be discussed in this chapter. + + + [[validator]] === Validation using Spring's Validator interface @@ -9101,6 +9580,9 @@ of Spring Web MVC you can use `` tag to inspect the error messages course you can also inspect the errors object yourself. More information about the methods it offers can be found from the Javadoc. + + + [[validation-conversion]] === Resolving codes to error messages We've talked about databinding and validation. Outputting messages corresponding to @@ -9127,6 +9609,9 @@ and http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/DefaultMessageCodesResolver.html[DefaultMessageCodesResolver] respectively. + + + [[beans-beans]] === Bean manipulation and the BeanWrapper @@ -9152,6 +9637,8 @@ the `DataBinder` and the `BeanFactory`. The way the `BeanWrapper` works is partly indicated by its name: __it wraps a bean__ to perform actions on that bean, like setting and retrieving properties. + + [[beans-beans-conventions]] ==== Setting and getting basic and nested properties Setting and getting properties is done using the `setPropertyValue(s)` and @@ -9258,6 +9745,8 @@ company.setPropertyValue("managingDirector", jim.getWrappedInstance()); Float salary = (Float) company.getPropertyValue("managingDirector.salary"); ---- + + [[beans-beans-conversion]] ==== Built-in PropertyEditor implementations @@ -9416,6 +9905,7 @@ public class FooBeanInfo extends SimpleBeanInfo { } ---- + [[beans-beans-conversion-customeditor-registration]] ===== Registering additional custom PropertyEditors @@ -9610,6 +10100,9 @@ of `initBinder(..)` is just one line long!), and allows common `PropertyEditor` registration code to be encapsulated in a class and then shared amongst as many `Controllers` as needed. + + + [[core-convert]] === Spring 3 Type Conversion Spring 3 introduces a `core.convert` package that provides a general type conversion @@ -9619,6 +10112,8 @@ used as an alternative to PropertyEditors to convert externalized bean property strings to required property types. The public API may also be used anywhere in your application where type conversion is needed. + + [[core-convert-Converter-API]] ==== Converter SPI The SPI to implement type conversion logic is simple and strongly typed: @@ -9660,6 +10155,8 @@ final class StringToInteger implements Converter { } ---- + + [[core-convert-ConverterFactory-SPI]] ==== ConverterFactory When you need to centralize the conversion logic for an entire class hierarchy, for @@ -9710,6 +10207,8 @@ final class StringToEnumConverterFactory implements ConverterFactory> for details on using `FormattingConversionServiceFactoryBean`. + + [[core-convert-programmatic-usage]] ==== Using a ConversionService programmatically To work with a ConversionService instance programmatically, simply inject a reference to @@ -9880,6 +10386,9 @@ public class MyService { } ---- + + + [[format]] === Spring 3 Field Formatting As discussed in the previous section, <> is a @@ -9905,6 +10414,8 @@ java.lang.Long. Use the Formatter SPI when you're working in a client environmen as a web application, and need to parse and print localized field values. The ConversionService provides a unified type conversion API for both SPIs. + + [[format-Formatter-SPI]] ==== Formatter SPI The Formatter SPI to implement field formatting logic is simple and strongly typed: @@ -9994,6 +10505,8 @@ public final class DateFormatter implements Formatter { The Spring team welcomes community-driven Formatter contributions; see http://jira.springframework.org[http://jira.springframework.org] to contribute. + + [[format-CustomFormatAnnotations]] ==== Annotation-driven Formatting As you will see, field formatting can be configured by field type or annotation. To bind @@ -10076,6 +10589,7 @@ public class MyModel { } ---- + [[format-annotations-api]] ===== Format Annotation API A portable format annotation API exists in the `org.springframework.format.annotation` @@ -10096,6 +10610,8 @@ public class MyModel { } ---- + + [[format-FormatterRegistry-SPI]] ==== FormatterRegistry SPI The FormatterRegistry is an SPI for registering formatters and converters. @@ -10133,6 +10649,8 @@ enforce that all Date fields are formatted a certain way, or fields with a speci annotation are formatted in a certain way. With a shared FormatterRegistry, you define these rules once and they are applied whenever formatting is needed. + + [[format-FormatterRegistrar-SPI]] ==== FormatterRegistrar SPI The FormatterRegistrar is an SPI for registering formatters and converters through the @@ -10157,6 +10675,8 @@ needs to be indexed under a specific field type different from its own or wh registering a Printer/Parser pair. The next section provides more information on converter and formatter registration. + + [[format-configuring-formatting-mvc]] ==== Configuring Formatting in Spring MVC In a Spring MVC application, you may configure a custom ConversionService instance @@ -10239,6 +10759,9 @@ See <> and the `FormattingConversionServiceFactor for more information on when to use FormatterRegistrars. ==== + + + [[format-configuring-formatting-globaldatetimeformat]] === Configuring a global date & time format By default, date and time fields that are not annotated with `@DateTimeFormat` are @@ -10329,6 +10852,9 @@ is used. For Java based `@Configuration` this means extending the For XML you should use the `'conversion-service'` attribute of the `mvc:annotation-driven` element. See <> for details. + + + [[validation-beanvalidation]] === Spring 3 Validation Spring 3 introduces several enhancements to its validation support. First, the JSR-303 @@ -10336,6 +10862,8 @@ Bean Validation API is now fully supported. Second, when used programmatically, DataBinder can now validate objects as well as bind to them. Third, Spring MVC now has support for declaratively validating @Controller inputs. + + [[validation-beanvalidation-overview]] ==== Overview of the JSR-303 Bean Validation API JSR-303 standardizes validation constraint declaration and metadata for the Java @@ -10380,6 +10908,8 @@ reference implementation, see the https://www.hibernate.org/412.html[Hibernate Validator] documentation. To learn how to setup a Bean Validation provider as a Spring bean, keep reading. + + [[validation-beanvalidation-spring]] ==== Configuring a Bean Validation Provider Spring provides full support for the Bean Validation API. This includes convenient @@ -10400,6 +10930,7 @@ The basic configuration above will trigger Bean Validation to initialize using i default bootstrap mechanism. A JSR-303/JSR-349 provider, such as Hibernate Validator, is expected to be present in the classpath and will be detected automatically. + [[validation-beanvalidation-spring-inject]] ===== Injecting a Validator `LocalValidatorFactoryBean` implements both `javax.validation.ValidatorFactory` and @@ -10439,6 +10970,7 @@ public class MyService { } ---- + [[validation-beanvalidation-spring-constraints]] ===== Configuring Custom Constraints Each Bean Validation constraint consists of two parts. First, a @Constraint annotation @@ -10484,6 +11016,7 @@ public class MyConstraintValidator implements ConstraintValidator { As you can see, a ConstraintValidator implementation may have its dependencies @Autowired like any other Spring bean. + [[validation-beanvalidation-spring-other]] ===== Additional Configuration Options The default `LocalValidatorFactoryBean` configuration should prove sufficient for most @@ -10491,6 +11024,8 @@ cases. There are a number of configuration options for various Bean Validation constructs, from message interpolation to traversal resolution. See the JavaDocs of `LocalValidatorFactoryBean` for more information on these options. + + [[validation-binder]] ==== Configuring a DataBinder Since Spring 3, a DataBinder instance can be configured with a Validator. Once @@ -10522,12 +11057,15 @@ A DataBinder can also be configured with multiple `Validator` instances via combining globally configured Bean Validation with a Spring `Validator` configured locally on a DataBinder instance. See <>. + + [[validation-mvc]] ==== Spring MVC 3 Validation Beginning with Spring 3, Spring MVC has the ability to automatically validate @Controller inputs. In previous versions it was up to the developer to manually invoke validation logic. + [[validation-mvc-triggering]] ===== Triggering @Controller Input Validation To trigger validation of a @Controller input, simply annotate the input argument as @@ -10552,6 +11090,7 @@ The @Valid annotation is part of the standard JSR-303 Bean Validation API, and i Spring-specific construct. ==== + [[validation-mvc-configuring]] ===== Configuring a Validator for use by Spring MVC The Validator instance invoked when a @Valid method argument is encountered may be @@ -10615,6 +11154,7 @@ public class MyController { } ---- + [[validation-mvc-jsr303]] ===== Configuring a JSR-303/JSR-349 Validator for use by Spring MVC With Bean Validation, a single `javax.validation.Validator` instance typically validates @@ -10649,9 +11189,16 @@ will be validated by the Bean Validation provider. That provider, in turn, will any constraints declared against the input. Any ConstraintViolations will automatically be exposed as errors in the BindingResult renderable by standard Spring MVC form tags. + + + + [[expressions]] == Spring Expression Language (SpEL) + + + [[expressions-intro]] === Introduction The Spring Expression Language (SpEL for short) is a powerful expression language that @@ -10683,6 +11230,9 @@ syntax. In several places an Inventor and Inventor's Society class are used as t target objects for expression evaluation. These class declarations and the data used to populate them are listed at the end of the chapter. + + + [[expressions-features]] === Feature Overview The expression language supports the following functionality @@ -10706,6 +11256,9 @@ The expression language supports the following functionality * Collection selection * Templated expressions + + + [[expressions-evaluation]] === Expression Evaluation using Spring's Expression Interface This section introduces the simple use of SpEL interfaces and its expression language. @@ -10871,6 +11424,8 @@ Expression exp = parser.parseExpression("name == 'Nikola Tesla'"); boolean result = exp.getValue(context, Boolean.class); // evaluates to true ---- + + [[expressions-evaluation-context]] ==== The EvaluationContext interface The interface `EvaluationContext` is used when evaluating an expression to resolve @@ -10889,6 +11444,7 @@ variables and functions are described in the language reference sections `ConstructorResolver` s, `MethodResolver` s, and `PropertyAccessor` s to extend how SpEL evaluates expressions. Please refer to the JavaDoc of these classes for more details. + [[expressions-type-conversion]] ===== Type Conversion By default SpEL uses the conversion service available in Spring core ( @@ -10925,12 +11481,17 @@ parser.parseExpression("booleanList[0]").setValue(simpleContext, "false"); Boolean b = simple.booleanList.get(0); ---- + + + [[expressions-beandef]] === Expression support for defining bean definitions SpEL expressions can be used with XML or annotation based configuration metadata for defining BeanDefinitions. In both cases the syntax to define the expression is of the form `#{ }`. + + [[expressions-beandef-xml-based]] ==== XML based configuration A property or constructor-arg value can be set using expressions as shown below @@ -10977,6 +11538,8 @@ You can also refer to other bean properties by name, for example. ---- + + [[expressions-beandef-annotation-based]] ==== Annotation-based configuration The `@Value` annotation can be placed on fields, methods and method/constructor @@ -11069,9 +11632,14 @@ public class MovieRecommender { } ---- + + + [[expressions-language-ref]] === Language Reference + + [[expressions-ref-literal]] ==== Literal expressions The types of literal expressions supported are strings, dates, numeric values (int, @@ -11102,6 +11670,8 @@ Object nullValue = parser.parseExpression("null").getValue(); Numbers support the use of the negative sign, exponential notation, and decimal points. By default real numbers are parsed using Double.parseDouble(). + + [[expressions-properties-arrays]] ==== Properties, Arrays, Lists, Maps, Indexers Navigating with property references is easy, just use a period to indicate a nested @@ -11168,6 +11738,8 @@ parser.parseExpression("Officers['advisors'][0].PlaceOfBirth.Country").setValue( "Croatia"); ---- + + [[expressions-inline-lists]] ==== Inline lists Lists can be expressed directly in an expression using {} notation. @@ -11185,6 +11757,8 @@ List listOfLists = (List) parser.parseExpression("{{'a','b'},{'x','y'}}").getVal entirely composed of fixed literals then a constant list is created to represent the expression, rather than building a new list on each evaluation. + + [[expressions-array-construction]] ==== Array construction Arrays can be built using the familiar Java syntax, optionally supplying an initializer @@ -11205,6 +11779,8 @@ int[][] numbers3 = (int[][]) parser.parseExpression("new int[4][5]").getValue(co It is not currently allowed to supply an initializer when constructing a multi-dimensional array. + + [[expressions-methods]] ==== Methods Methods are invoked using typical Java programming syntax. You may also invoke methods @@ -11221,9 +11797,12 @@ boolean isMember = parser.parseExpression("isMember('Mihajlo Pupin')").getValue( Boolean.class); ---- + + [[expressions-operators]] ==== Operators + [[expressions-operators-relational]] ===== Relational operators The relational operators; equal, not equal, less than, less than or equal, greater than, @@ -11266,6 +11845,7 @@ which the expression is embedded (eg. an XML document). The textual equivalents shown here: lt ('<'), gt ('>'), le ('<='), ge ('>='), eq ('=='), ne ('!='), div ('/'), mod ('%'), not ('!'). These are case insensitive. + [[expressions-operators-logical]] ===== Logical operators The logical operators that are supported are and, or, and not. Their use is demonstrated @@ -11302,6 +11882,7 @@ String expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')"; boolean falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class); ---- + [[expressions-operators-mathematical]] ===== Mathematical operators The addition operator can be used on numbers, strings and dates. Subtraction can be used @@ -11342,6 +11923,8 @@ int one = parser.parseExpression("8 / 5 % 2").getValue(Integer.class); // 1 int minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(Integer.class); // -21 ---- + + [[expressions-assignment]] ==== Assignment Setting of a property is done by using the assignment operator. This would typically be @@ -11361,6 +11944,8 @@ String aleks = parser.parseExpression("Name = 'Alexandar Seovic'").getValue(inve String.class); ---- + + [[expressions-types]] ==== Types The special 'T' operator can be used to specify an instance of java.lang.Class (the @@ -11382,6 +11967,8 @@ boolean trueValue = .getValue(Boolean.class); ---- + + [[expressions-constructors]] ==== Constructors Constructors can be invoked using the new operator. The fully qualified class name @@ -11402,6 +11989,8 @@ p.parseExpression("Members.add(new org.spring.samples.spel.inventor.Inventor('Al .getValue(societyContext); ---- + + [[expressions-ref-variables]] ==== Variables Variables can be referenced in the expression using the syntax #variableName. Variables @@ -11419,6 +12008,7 @@ parser.parseExpression("Name = #newName").getValue(context); System.out.println(tesla.getName()) // "Mike Tesla" ---- + [[expressions-this-root]] ===== The #this and #root variables The variable #this is always defined and refers to the current evaluation object @@ -11444,6 +12034,8 @@ List primesGreaterThanTen = (List) parser.parseExpression("#primes.?[#this>10]").getValue(context); ---- + + [[expressions-ref-functions]] ==== Functions You can extend SpEL by registering user defined functions that can be called within the @@ -11491,6 +12083,8 @@ String helloWorldReversed = parser.parseExpression("#reverseString('hello')").getValue(context, String.class); ---- + + [[expressions-bean-references]] ==== Bean references If the evaluation context has been configured with a bean resolver it is possible to @@ -11507,6 +12101,8 @@ context.setBeanResolver(new MyBeanResolver()); Object bean = parser.parseExpression("@foo").getValue(context); ---- + + [[expressions-operator-ternary]] ==== Ternary Operator (If-Then-Else) You can use the ternary operator for performing if-then-else conditional logic inside @@ -11539,6 +12135,8 @@ String queryResultString = Also see the next section on the Elvis operator for an even shorter syntax for the ternary operator. + + [[expressions-operator-elvis]] ==== The Elvis Operator The Elvis operator is a shortening of the ternary operator syntax and is used in the @@ -11586,6 +12184,8 @@ name = parser.parseExpression("Name?:'Elvis Presley'").getValue(context, String. System.out.println(name); // Elvis Presley ---- + + [[expressions-operator-safe-navigation]] ==== Safe Navigation operator The Safe Navigation operator is used to avoid a `NullPointerException` and comes from @@ -11628,6 +12228,8 @@ The Elvis operator can be used to apply default values in expressions, e.g. in a This will inject a system property `pop3.port` if it is defined or 25 if not. ==== + + [[expressions-collection-selection]] ==== Collection Selection Selection is a powerful expression language feature that allows you to transform some @@ -11663,6 +12265,8 @@ In addition to returning all the selected elements, it is possible to retrieve j first or the last value. To obtain the first entry matching the selection the syntax is `^[...]` whilst to obtain the last matching selection the syntax is `$[...]`. + + [[expressions-collection-projection]] ==== Collection Projection Projection allows a collection to drive the evaluation of a sub-expression and the @@ -11683,6 +12287,8 @@ evaluated against each entry in the map (represented as a Java `Map.Entry`). The of a projection across a map is a list consisting of the evaluation of the projection expression against each map entry. + + [[expressions-templating]] ==== Expression templating Expression templates allow a mixing of literal text with one or more evaluation blocks. @@ -11725,6 +12331,9 @@ public class TemplateParserContext implements ParserContext { } ---- + + + [[expressions-example-classes]] === Classes used in the examples Inventor.java @@ -11882,9 +12491,16 @@ public class Society { } ---- + + + + [[aop]] == Aspect Oriented Programming with Spring + + + [[aop-introduction]] === IntroductionSpring 2.0 AOP __Aspect-Oriented Programming__ (AOP) complements Object-Oriented Programming (OOP) by @@ -11924,6 +12540,8 @@ declarative middleware services such as pooling, you do not need to work directl Spring AOP, and can skip most of this chapter. ==== + + [[aop-introduction-defn]] ==== AOP concepts Let us begin by defining some central AOP concepts and terminology. These terms are not @@ -11999,6 +12617,8 @@ targeted independently of the Object-Oriented hierarchy. For example, an around providing declarative transaction management can be applied to a set of methods spanning multiple objects (such as all business operations in the service layer). + + [[aop-introduction-spring-defn]] ==== Spring AOP capabilities and goals Spring AOP is implemented in pure Java. There is no need for a special compilation @@ -12056,6 +12676,8 @@ See <> for a more complete discussion of the whys and wherefores o style. ==== + + [[aop-introduction-proxies]] ==== AOP Proxies Spring AOP defaults to using standard J2SE __dynamic proxies__ for AOP proxies. This @@ -12073,6 +12695,9 @@ It is important to grasp the fact that Spring AOP is __proxy-based__. See <> for a thorough examination of exactly what this implementation detail actually means. + + + [[aop-ataspectj]] === @AspectJ support @AspectJ refers to a style of declaring aspects as regular Java classes annotated with @@ -12088,6 +12713,8 @@ Using the AspectJ compiler and weaver enables use of the full AspectJ language, discussed in <>. ==== + + [[aop-aspectj-support]] ==== Enabling @AspectJ Support To use @AspectJ aspects in a Spring configuration you need to enable Spring support for @@ -12102,6 +12729,7 @@ case you will also need to ensure that AspectJ's `aspectjweaver.jar` library is classpath of your application (version 1.6.8 or later). This library is available in the `'lib'` directory of an AspectJ distribution or via the Maven Central repository. + [[aop-enable-aspectj-java]] ===== Enabling @AspectJ Support with Java configuration To enable @AspectJ support with Java `@Configuration` add the `@EnableAspectJAutoProxy` @@ -12117,6 +12745,7 @@ public class AppConfig { } ---- + [[aop-enable-aspectj-xml]] ===== Enabling @AspectJ Support with XML configuration To enable @AspectJ support with XML based configuration use the `aop:aspectj-autoproxy` @@ -12140,6 +12769,8 @@ following definition to your application context: ---- + + [[aop-at-aspectj]] ==== Declaring an aspect @@ -12197,6 +12828,8 @@ from other aspects. The__@Aspect__ annotation on a class marks it as an aspect, hence excludes it from auto-proxying. ==== + + [[aop-pointcuts]] ==== Declaring a pointcut Recall that pointcuts determine join points of interest, and thus enable us to control @@ -12228,6 +12861,7 @@ http://www.eclipse.org/aspectj/doc/released/adk15notebook/index.html[AspectJ 5 Developers Notebook]) or one of the books on AspectJ such as "Eclipse AspectJ" by Colyer et. al. or "AspectJ in Action" by Ramnivas Laddad. + [[aop-pointcuts-designators]] ===== Supported Pointcut DesignatorsOther pointcut types Spring AOP supports the following AspectJ pointcut designators (PCD) for use in pointcut @@ -12319,6 +12953,7 @@ proxy-based AOP framework and its close integration with the Spring bean factory it is natural and straightforward to identify specific beans by name. ==== + [[aop-pointcuts-combining]] ===== Combining pointcut expressions Pointcut expressions can be combined using '&&', '||' and '!'. It is also possible to @@ -12347,6 +12982,7 @@ rules apply (you can see private pointcuts in the same type, protected pointcuts hierarchy, public pointcuts anywhere and so on). Visibility does not affect pointcut __matching__. + [[aop-common-pointcuts]] ===== Sharing common pointcut definitions When working with enterprise applications, you often want to refer to modules of the @@ -12440,6 +13076,7 @@ write: The `` and `` elements are discussed in <>. The transaction elements are discussed in <>. + [[aop-pointcuts-examples]] ===== Examples Spring AOP users are likely to use the `execution` pointcut designator the most often. @@ -12653,6 +13290,7 @@ bean(tradeService) bean(*Service) ---- + [[writing-good-pointcuts]] ===== Writing good pointcuts During compilation, AspectJ processes pointcuts in order to try and optimize matching @@ -12688,12 +13326,15 @@ designators are very fast to match and their usage means AspectJ can very quickl dismiss groups of join points that should not be further processed - that is why a good pointcut should always include one if possible. + + [[aop-advice]] ==== Declaring advice Advice is associated with a pointcut expression, and runs before, after, or around method executions matched by the pointcut. The pointcut expression may be either a simple reference to a named pointcut, or a pointcut expression declared in place. + [[aop-advice-before]] ===== Before advice Before advice is declared in an aspect using the `@Before` annotation: @@ -12734,6 +13375,7 @@ public class BeforeExample { } ---- + [[aop-advice-after-returning]] ===== After returning advice After returning advice runs when a matched method execution returns normally. It is @@ -12794,6 +13436,7 @@ type ( `Object` in this case, which will match any return value). Please note that it is __not__ possible to return a totally different reference when using after-returning advice. + [[aop-advice-after-throwing]] ===== After throwing advice After throwing advice runs when a matched method execution exits by throwing an @@ -12846,6 +13489,7 @@ will be passed to the advice method as the corresponding argument value. A `thro clause also restricts matching to only those method executions that throw an exception of the specified type ( `DataAccessException` in this case). + [[aop-advice-after-finally]] ===== After (finally) advice After (finally) advice runs however a matched method execution exits. It is declared @@ -12869,6 +13513,7 @@ public class AfterFinallyExample { } ---- + [[aop-ataspectj-around-advice]] ===== Around advice The final kind of advice is around advice. Around advice runs "around" a matched method @@ -12929,6 +13574,7 @@ has one, and invoke proceed() if it does not. Note that proceed may be invoke many times, or not at all within the body of the around advice, all of these are quite legal. + [[aop-ataspectj-advice-params]] ===== Advice parameters Spring 2.0 offers fully typed advice - meaning that you declare the parameters you need @@ -13175,6 +13821,7 @@ throws Throwable { In many cases you will be doing this binding anyway (as in the example above). + [[aop-ataspectj-advice-ordering]] ===== Advice ordering What happens when multiple pieces of advice all want to run at the same join point? @@ -13198,6 +13845,8 @@ order via reflection for javac-compiled classes). Consider collapsing such advic methods into one advice method per join point in each aspect class, or refactor the pieces of advice into separate aspect classes - which can be ordered at the aspect level. + + [[aop-introductions]] ==== Introductions Introductions (known as inter-type declarations in AspectJ) enable an aspect to declare @@ -13242,6 +13891,8 @@ you would write the following: UsageTracked usageTracked = (UsageTracked) context.getBean("myService"); ---- + + [[aop-instantiation-models]] ==== Aspect instantiation models [NOTE] @@ -13288,6 +13939,8 @@ programming guide for more information on per-clauses. The `'pertarget'` instantiation model works in exactly the same way as perthis, but creates one aspect instance for each unique target object at matched join points. + + [[aop-ataspectj-example]] ==== Example Now that you have seen how all the constituent parts work, let's put them together to do @@ -13396,6 +14049,9 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable { } ---- + + + [[aop-schema]] === Schema-based AOP support If you are unable to use Java 5, or simply prefer an XML-based format, then Spring 2.0 @@ -13424,6 +14080,8 @@ being woven) if you are already using explicit auto-proxying via the use of just the `` style, or just the `AutoProxyCreator` style. ==== + + [[aop-schema-declaring-an-aspect]] ==== Declaring an aspect Using the schema support, an aspect is simply a regular Java object defined as a bean in @@ -13450,6 +14108,8 @@ using the `ref` attribute: The bean backing the aspect (" `aBean`" in this case) can of course be configured and dependency injected just like any other Spring bean. + + [[aop-schema-pointcuts]] ==== Declaring a pointcut A named pointcut can be declared inside an element, enabling the pointcut @@ -13564,11 +14224,14 @@ used as named pointcuts to form composite pointcuts. The named pointcut support schema based definition style is thus more limited than that offered by the @AspectJ style. + + [[aop-schema-advice]] ==== Declaring advice The same five advice kinds are supported as for the @AspectJ style, and they have exactly the same semantics. + [[aop-schema-advice-before]] ===== Before advice Before advice runs before a matched method execution. It is declared inside an @@ -13615,6 +14278,7 @@ containing the advice. Before a data access operation is executed (a method exec join point matched by the pointcut expression), the "doAccessCheck" method on the aspect bean will be invoked. + [[aop-schema-advice-after-returning]] ===== After returning advice After returning advice runs when a matched method execution completes normally. It is @@ -13663,6 +14327,7 @@ example, the method signature may be declared as: public void doAccessCheck(Object retVal) {... ---- + [[aop-schema-advice-after-throwing]] ===== After throwing advice After throwing advice executes when a matched method execution exits by throwing an @@ -13711,6 +14376,7 @@ example, the method signature may be declared as: public void doRecoveryActions(DataAccessException dataAccessEx) {... ---- + [[aop-schema-advice-after-finally]] ===== After (finally) advice After (finally) advice runs however a matched method execution exits. It is declared @@ -13730,6 +14396,7 @@ using the `after` element: ---- + [[aop-schema-advice-around]] ===== Around advice The final kind of advice is around advice. Around advice runs "around" a matched method @@ -13775,6 +14442,7 @@ public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { } ---- + [[aop-schema-params]] ===== Advice parameters The schema based declaration style supports fully typed advice in the same way as @@ -13912,6 +14580,7 @@ ms % Task name 00000 ? execution(getFoo) ---- + [[aop-ordering]] ===== Advice ordering When multiple advice needs to execute at the same join point (executing method) the @@ -13919,6 +14588,8 @@ ordering rules are as described in <>. The preced 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. + + [[aop-schema-introductions]] ==== Introductions Introductions (known as inter-type declarations in AspectJ) enable an aspect to declare @@ -13973,11 +14644,15 @@ following: UsageTracked usageTracked = (UsageTracked) context.getBean("myService"); ---- + + [[aop-schema-instatiation-models]] ==== Aspect instantiation models The only supported instantiation model for schema-defined aspects is the singleton model. Other instantiation models may be supported in future releases. + + [[aop-schema-advisors]] ==== Advisors The concept of "advisors" is brought forward from the AOP support defined in Spring 1.2 @@ -14018,6 +14693,8 @@ As well as the `pointcut-ref` attribute used in the above example, you can also To define the precedence of an advisor so that the advice can participate in ordering, use the `order` attribute to define the `Ordered` value of the advisor. + + [[aop-schema-example]] ==== Example Let's see how the concurrent locking failure retry example from @@ -14142,6 +14819,9 @@ pointcut expression so that only `@Idempotent` operations match: @annotation(com.xyz.myapp.service.Idempotent)"/> ---- + + + [[aop-choosing]] === Choosing which AOP declaration style to use Once you have decided that an aspect is the best approach for implementing a given @@ -14150,6 +14830,8 @@ Aspect language (code) style, @AspectJ annotation style, or the Spring XML style decisions are influenced by a number of factors including application requirements, development tools, and team familiarity with AOP. + + [[aop-spring-or-aspectj]] ==== Spring AOP or full AspectJ? Use the simplest thing that can work. Spring AOP is simpler than using full AspectJ as @@ -14171,6 +14853,8 @@ that do not play a major role in your application, then you may want to consider the @AspectJ style and sticking with a regular Java compilation in your IDE, and adding an aspect weaving phase to your build script. + + [[aop-ataspectj-or-xml]] ==== @AspectJ or XML for Spring AOP? If you have chosen to use Spring AOP, then you have a choice of @AspectJ or XML style. @@ -14233,6 +14917,9 @@ implement additional requirements then it is very easy to migrate to an AspectJ- approach. On balance the Spring team prefer the @AspectJ style whenever you have aspects that do more than simple "configuration" of enterprise services. + + + [[aop-mixing-styles]] === Mixing aspect types It is perfectly possible to mix @AspectJ style aspects using the autoproxying support, @@ -14241,6 +14928,9 @@ proxies and interceptors defined using the Spring 1.2 style in the same configur All of these are implemented using the same underlying support mechanism and will co-exist without any difficulty. + + + [[aop-proxying]] === Proxying mechanisms Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given @@ -14301,6 +14991,8 @@ To be clear: using ' `proxy-target-class="true"`' on ``, proxies __for all three of them__. ==== + + [[aop-understanding-aop-proxies]] ==== Understanding AOP proxies Spring AOP is __proxy-based__. It is vitally important that you grasp the semantics of @@ -14433,6 +15125,9 @@ public class Main { Finally, it must be noted that AspectJ does not have this self-invocation issue because it is not a proxy-based AOP framework. + + + [[aop-aspectj-programmatic]] === Programmatic creation of @AspectJ Proxies In addition to declaring aspects in your configuration using either `` or @@ -14463,6 +15158,9 @@ factory.addAspect(usageTracker); MyInterfaceType proxy = factory.getProxy(); ---- + + + [[aop-using-aspectj]] === Using AspectJ with Spring applications Everything we've covered so far in this chapter is pure Spring AOP. In this section, @@ -14478,6 +15176,8 @@ dependency inject AspectJ aspects that are woven using the AspectJ compiler. Fin <> provides an introduction to load-time weaving for Spring applications using AspectJ. + + [[aop-atconfigurable]] ==== Using AspectJ to dependency inject domain objects with Spring The Spring container instantiates and configures beans defined in your application @@ -14654,6 +15354,7 @@ with the container: You would get double initialization otherwise, once through container and once through the aspect. ==== + [[aop-configurable-testing]] ===== Unit testing @Configurable objects @@ -14666,6 +15367,7 @@ AspectJ then you can still unit test outside of the container as normal, but you see a warning message each time that you construct an `@Configurable` object indicating that it has not been configured by Spring. + [[aop-configurable-container]] ===== Working with multiple application contexts The `AnnotationBeanConfigurerAspect` used to implement the `@Configurable` support is an @@ -14693,6 +15395,8 @@ only added to the container wide classpath (and hence loaded by the shared paren classloader), all web applications will share the same aspect instance which is probably not what you want. + + [[aop-ajlib-other]] ==== Other Spring aspects for AspectJ In addition to the `@Configurable` aspect, `spring-aspects.jar` contains an AspectJ @@ -14742,6 +15446,8 @@ public aspect DomainObjectConfiguration extends AbstractBeanConfigurerAspect { } ---- + + [[aop-aj-configure]] ==== Configuring AspectJ aspects using Spring IoC When using AspectJ aspects with Spring applications, it is natural to both want and @@ -14797,6 +15503,8 @@ result in the creation of __Spring AOP proxies__. The @AspectJ style of aspect declaration is just being used here, but the AspectJ runtime is __not__ involved. ==== + + [[aop-aj-ltw]] ==== Load-time weaving with AspectJ in the Spring Framework Load-time weaving (LTW) refers to the process of weaving AspectJ aspects into an @@ -14831,6 +15539,7 @@ LTW using Spring, followed by detailed specifics about elements introduced in th following example. For a complete example, please see the Petclinic <> application. + [[aop-aj-ltw-first-example]] ===== A first example Let us assume that you are an application developer who has been tasked with diagnosing @@ -15043,6 +15752,7 @@ course), and then quite easily exclude from builds of the application being depl into UAT or production. ==== + [[aop-aj-ltw-the-aspects]] ===== Aspects The aspects that you use in LTW have to be AspectJ aspects. They can be written in @@ -15051,6 +15761,7 @@ The latter option is of course only an option if you are using Java 5+, but it d that your aspects are then both valid AspectJ __and__ Spring AOP aspects. Furthermore, the compiled aspect classes need to be available on the classpath. + [[aop-aj-ltw-aop_dot_xml]] ===== ' META-INF/aop.xml' @@ -15066,6 +15777,7 @@ and so there is no extra value that I can contribute either as a result), so rat rehash the quite satisfactory section that the AspectJ developers wrote, I am just directing you there.) + [[aop-aj-ltw-libraries]] ===== Required libraries (JARS) At a minimum you will need the following libraries to use the Spring Framework's support @@ -15079,6 +15791,7 @@ instrumentation>>, you will also need: * `spring-instrument.jar` + [[aop-aj-ltw-spring]] ===== Spring configuration The key component in Spring's LTW support is the `LoadTimeWeaver` interface (in the @@ -15251,6 +15964,7 @@ attribute is not present being ' `autodetect`' then AspectJ weaving is on, else it is off. This is the default value. |=== + [[aop-aj-ltw-environments]] ===== Environment-specific configuration This last section contains any additional settings and configuration that you will need @@ -15396,6 +16110,9 @@ For performance reasons, it is recommended to use this configuration only if you environment (such as http://www.eclipse.org/jetty/[Jetty]) does not have (or does not support) a dedicated LTW. + + + [[aop-resources]] === Further Resources More information on AspectJ can be found on the http://www.eclipse.org/aspectj[AspectJ @@ -15408,9 +16125,16 @@ The book __AspectJ in Action__ by Ramnivas Laddad (Manning, 2003) comes highly recommended; the focus of the book is on AspectJ, but a lot of general AOP themes are explored (in some depth). + + + + [[aop-api]] == Spring AOP APIs + + + [[aop-api-introduction]] === Introduction The previous chapter described the Spring 2.0 and later version's support for AOP using @@ -15422,10 +16146,15 @@ and articles, you may come across Spring 1.2 style examples. Spring 3.0 is backw compatible with Spring 1.2 and everything described in this chapter is fully supported in Spring 3.0. + + + [[aop-api-pointcuts]] === Pointcut API in Spring Let's look at how Spring handles the crucial pointcut concept. + + [[aop-api-concepts]] ==== Concepts Spring's pointcut model enables pointcut reuse independent of advice types. It's @@ -15497,6 +16226,8 @@ If possible, try to make pointcuts static, allowing the AOP framework to cache t results of pointcut evaluation when an AOP proxy is created. ==== + + [[aop-api-pointcut-ops]] ==== Operations on pointcuts Spring supports operations on pointcuts: notably, __union__ and __intersection__. @@ -15509,6 +16240,8 @@ Spring supports operations on pointcuts: notably, __union__ and __intersection__ __ComposablePointcut__ class in the same package. However, using AspectJ pointcut expressions is usually a simpler approach. + + [[aop-api-pointcuts-aspectj]] ==== AspectJ expression pointcuts Since 2.0, the most important type of pointcut used by Spring is @@ -15517,11 +16250,14 @@ uses an AspectJ supplied library to parse an AspectJ pointcut expression string. See the previous chapter for a discussion of supported AspectJ pointcut primitives. + + [[aop-api-pointcuts-impls]] ==== Convenience pointcut implementations Spring provides several convenient pointcut implementations. Some can be used out of the box; others are intended to be subclassed in application-specific pointcuts. + [[aop-api-pointcuts-static]] ===== Static pointcuts Static pointcuts are based on method and target class, and cannot take into account the @@ -15589,6 +16325,7 @@ __RegexpMethodPointcutAdvisor__ can be used with any Advice type. An important type of static pointcut is a __metadata-driven__ pointcut. This uses the values of metadata attributes: typically, source-level metadata. + [[aop-api-pointcuts-dynamic]] ===== Dynamic pointcuts Dynamic pointcuts are costlier to evaluate than static pointcuts. They take into account @@ -15613,6 +16350,8 @@ other dynamic pointcuts. In Java 1.4, the cost is about 5 times that of other dy pointcuts. ==== + + [[aop-api-pointcuts-superclasses]] ==== Pointcut superclasses Spring provides useful pointcut superclasses to help you to implement your own pointcuts. @@ -15636,6 +16375,8 @@ There are also superclasses for dynamic pointcuts. You can use custom pointcuts with any advice type in Spring 1.0 RC2 and above. + + [[aop-api-pointcuts-custom]] ==== Custom pointcuts Because pointcuts in Spring AOP are Java classes, rather than language features (as in @@ -15649,10 +16390,15 @@ Later versions of Spring may offer support for "semantic pointcuts" as offered b for example, "all methods that change instance variables in the target object." ==== + + + [[aop-api-advice]] === Advice API in Spring Let's now look at how Spring AOP handles advice. + + [[aop-api-advice-lifecycle]] ==== Advice lifecycles Each advice is a Spring bean. An advice instance can be shared across all advised @@ -15668,11 +16414,14 @@ the advice adds state to the proxied object. It's possible to use a mix of shared and per-instance advice in the same AOP proxy. + + [[aop-api-advice-types]] ==== Advice types in Spring Spring provides several advice types out of the box, and is extensible to support arbitrary advice types. Let us look at the basic concepts and standard advice types. + [[aop-api-advice-around]] ===== Interception around advice The most fundamental advice type in Spring is __interception around advice__. @@ -15728,6 +16477,7 @@ are not currently interoperable between frameworks, and the AOP Alliance does no currently define pointcut interfaces. ==== + [[aop-api-advice-before]] ===== Before advice A simpler advice type is a __before advice__. This does not need a `MethodInvocation` @@ -15782,6 +16532,7 @@ public class CountingBeforeAdvice implements MethodBeforeAdvice { Before advice can be used with any pointcut. ==== + [[aop-api-advice-throws]] ===== Throws advice __Throws advice__ is invoked after the return of the join point if the join point threw @@ -15861,6 +16612,7 @@ exception that is incompatible with the target method's signature!__ Throws advice can be used with any pointcut. ==== + [[aop-api-advice-after-returning]] ===== After Returning advice An after returning advice in Spring must implement the @@ -15909,6 +16661,7 @@ thrown up the interceptor chain instead of the return value. After returning advice can be used with any pointcut. ==== + [[aop-api-advice-introduction]] ===== Introduction advice Spring treats introduction advice as a special kind of interception advice. @@ -16068,6 +16821,9 @@ We can apply this advisor programmatically, using the `Advised.addAdvisor()` met choices discussed below, including "auto proxy creators," correctly handle introductions and stateful mixins. + + + [[aop-api-advisor]] === Advisor API in Spring In Spring, an Advisor is an aspect that contains just a single advice object associated @@ -16083,6 +16839,9 @@ example, you could use a interception around advice, throws advice and before ad one proxy configuration: Spring will automatically create the necessary interceptor chain. + + + [[aop-pfb]] === Using the ProxyFactoryBean to create AOP proxies If you're using the Spring IoC container (an ApplicationContext or BeanFactory) for your @@ -16100,6 +16859,8 @@ __org.springframework.aop.framework.ProxyFactoryBean__. This gives complete cont the pointcuts and advice that will apply, and their ordering. However, there are simpler options that are preferable if you don't need such control. + + [[aop-pfb-1]] ==== Basics The `ProxyFactoryBean`, like other Spring `FactoryBean` implementations, introduces a @@ -16115,6 +16876,8 @@ achieve with other AOP frameworks. For example, an advice may itself reference application objects (besides the target, which should be available in any AOP framework), benefiting from all the pluggability provided by Dependency Injection. + + [[aop-pfb-2]] ==== JavaBean properties In common with most `FactoryBean` implementations provided with Spring, the @@ -16166,6 +16929,8 @@ to be applied. An example of using this feature can be found in < ---- + + + [[aop-concise-proxy]] === Concise proxy definitions Especially when defining transactional proxies, you may end up with many similar proxy @@ -16454,6 +17228,9 @@ and this definition specifies a class, you must make sure to set the__abstract__ attribute to __true__, otherwise the application context will actually try to pre-instantiate it. + + + [[aop-prog]] === Creating AOP proxies programmatically with the ProxyFactory It's easy to create AOP proxies programmatically using Spring. This enables you to use @@ -16494,6 +17271,9 @@ applications. We recommend that you externalize configuration from Java code wit as in general. ==== + + + [[aop-api-advised]] === Manipulating advised objects However you create AOP proxies, you can manipulate them using the @@ -16585,6 +17365,9 @@ prevent calling code removing a security interceptor. It may also be used in Spr to allow aggressive optimization if runtime advice modification is known not to be required. + + + [[aop-autoproxy]] === Using the "auto-proxy" facility So far we've considered explicit creation of AOP proxies using a `ProxyFactoryBean` or @@ -16604,11 +17387,14 @@ There are two ways to do this: * A special case of auto-proxy creation that deserves to be considered separately; auto-proxy creation driven by source-level metadata attributes. + + [[aop-autoproxy-choices]] ==== Autoproxy bean definitions The `org.springframework.aop.framework.autoproxy` package provides the following standard auto-proxy creators. + [[aop-api-autoproxy]] ===== BeanNameAutoProxyCreator The `BeanNameAutoProxyCreator` class is a `BeanPostProcessor` that automatically creates @@ -16642,6 +17428,7 @@ created automatically by the `BeanNameAutoProxyCreator`. The same advice will be to all matching beans. Note that if advisors are used (rather than the interceptor in the above example), the pointcuts may apply differently to different beans. + [[aop-api-autoproxy-default]] ===== DefaultAdvisorAutoProxyCreator A more general and extremely powerful auto proxy creator is @@ -16703,6 +17490,7 @@ Advisors can implement the `org.springframework.core.Ordered` interface to ensur correct ordering if this is an issue. The TransactionAttributeSourceAdvisor used in the above example has a configurable order value; the default setting is unordered. + [[aop-api-autoproxy-abstract]] ===== AbstractAdvisorAutoProxyCreator This is the superclass of DefaultAdvisorAutoProxyCreator. You can create your own @@ -16710,6 +17498,8 @@ auto-proxy creators by subclassing this class, in the unlikely event that adviso definitions offer insufficient customization to the behavior of the framework `DefaultAdvisorAutoProxyCreator`. + + [[aop-autoproxy-metadata]] ==== Using metadata-driven auto-proxying A particularly important type of auto-proxying is driven by metadata. This produces a @@ -16846,6 +17636,9 @@ definitions, the mixin will be applied. Note that both `lockMixin` and `lockable definitions are prototypes. The `myAttributeAwarePointcut` pointcut can be a singleton definition, as it doesn't hold state for individual advised objects. + + + [[aop-targetsource]] === Using TargetSources Spring offers the concept of a __TargetSource__, expressed in the @@ -16872,6 +17665,8 @@ rather than a singleton bean definition. This allows Spring to create a new targ instance when required. ==== + + [[aop-ts-swap]] ==== Hot swappable target sources The `org.springframework.aop.target.HotSwappableTargetSource` exists to allow the target @@ -16914,6 +17709,8 @@ Although this example doesn't add any advice - and it's not necessary to add adv use a `TargetSource` - of course any `TargetSource` can be used in conjunction with arbitrary advice. + + [[aop-ts-pool]] ==== Pooling target sources Using a pooling target source provides a similar programming model to stateless session @@ -17000,6 +17797,8 @@ pooling is problematic if resources are cached. Simpler pooling is available using auto-proxying. It's possible to set the TargetSources used by any auto-proxy creator. + + [[aop-ts-prototype]] ==== Prototype target sources Setting up a "prototype" target source is similar to a pooling TargetSource. In this @@ -17023,6 +17822,8 @@ There's only one property: the name of the target bean. Inheritance is used in t TargetSource implementations to ensure consistent naming. As with the pooling target source, the target bean must be a prototype bean definition. + + [[aop-ts-threadlocal]] ==== ThreadLocal target sources @@ -17053,6 +17854,9 @@ ThreadLocal support does this for you and should always be considered in favor o ThreadLocals without other proper handling code. ==== + + + [[aop-extensibility]] === Defining new Advice types @@ -17069,6 +17873,9 @@ only constraint on a custom `Advice` type is that it must implement the Please refer to the `org.springframework.aop.framework.adapter` package's Javadocs for further information. + + + [[aop-api-resources]] === Further resources Please refer to the Spring sample applications for further examples of Spring AOP: @@ -17078,9 +17885,16 @@ Please refer to the Spring sample applications for further examples of Spring AO * The `/attributes` directory of the JPetStore illustrates the use of attribute-driven declarative transaction management. + + + + [[testing]] == Testing + + + [[testing-introduction]] === Introduction to Spring Testing Testing is an integral part of enterprise software development. This chapter focuses on @@ -17089,6 +17903,9 @@ of the Spring Framework's support for < thorough treatment of testing in the enterprise is beyond the scope of this reference manual.)__ + + + [[unit-testing]] === Unit Testing Dependency Injection should make your code less dependent on the container than it would @@ -17109,9 +17926,12 @@ you write effective unit tests for your IoC-based applications. For certain unit scenarios, however, the Spring Framework provides the following mock objects and testing support classes. + + [[mock-objects]] ==== Mock Objects + [[mock-objects-env]] ===== Environment The `org.springframework.mock.env` package contains mock implementations of the @@ -17120,6 +17940,7 @@ The `org.springframework.mock.env` package contains mock implementations of the `MockEnvironment` and `MockPropertySource` are useful for developing __out-of-container__ tests for code that depends on environment-specific properties. + [[mock-objects-jndi]] ===== JNDI The `org.springframework.mock.jndi` package contains an implementation of the JNDI SPI, @@ -17128,6 +17949,7 @@ applications. If, for example, JDBC `DataSource` s get bound to the same JNDI na test code as within a Java EE container, you can reuse both application code and configuration in testing scenarios without modification. + [[mock-objects-servlet]] ===== Servlet API The `org.springframework.mock.web` package contains a comprehensive set of Servlet API @@ -17136,14 +17958,18 @@ testing web contexts and controllers. These mock objects are generally more conv to use than dynamic mock objects such as http://www.easymock.org[EasyMock] or existing Servlet API mock objects such as http://www.mockobjects.com[MockObjects]. + [[mock-objects-portlet]] ===== Portlet API The `org.springframework.mock.web.portlet` package contains a set of Portlet API mock objects, targeted at usage with Spring's Portlet MVC framework. + + [[unit-testing-support-classes]] ==== Unit Testing support Classes + [[unit-testing-utilities]] ===== General utilities The `org.springframework.test.util` package contains `ReflectionTestUtils`, which is a @@ -17157,6 +17983,7 @@ a non- `public` setter method when testing application code involving, for examp which provides dependency injection for `private` or `protected` fields, setter methods, and configuration methods. + [[unit-testing-spring-mvc]] ===== Spring MVC The `org.springframework.test.web` package contains `ModelAndViewAssert`, which you can @@ -17172,9 +17999,14 @@ To test your Spring MVC `Controller` s, use `ModelAndViewAssert` combined with `org.springframework.mock.web`>> package. ==== + + + [[integration-testing]] === Integration Testing + + [[integration-testing-overview]] ==== Overview It is important to be able to perform some integration testing without requiring @@ -17200,6 +18032,8 @@ the annotation-driven <>. Th TestContext framework is agnostic of the actual testing framework in use, thus allowing instrumentation of tests in various environments including JUnit, TestNG, and so on. + + [[integration-testing-goals]] ==== Goals of Integration Testing Spring's integration testing support has the following primary goals: @@ -17214,6 +18048,7 @@ Spring's integration testing support has the following primary goals: The next few sections describe each goal and provide links to implementation and configuration details. + [[testing-ctx-management]] ===== Context management and caching The Spring TestContext Framework provides consistent loading of Spring @@ -17242,6 +18077,7 @@ configuration and rebuild the application context before executing the next test See <> and <> with the TestContext framework. + [[testing-fixture-di]] ===== Dependency Injection of test fixtures When the TestContext framework loads your application context, it can optionally @@ -17266,6 +18102,7 @@ integration tests that test the following areas: See dependency injection of test fixtures with the <>. + [[testing-tx]] ===== Transaction management One common issue in tests that access a real database is their effect on the state of @@ -17291,6 +18128,7 @@ instructed to cause the transaction to commit instead of roll back via the See transaction management with the <>. + [[testing-support-classes]] ===== Support classes for integration testing The Spring TestContext Framework provides several `abstract` support classes that @@ -17311,6 +18149,8 @@ instance variables and methods specific to your project. See support classes for the <>. + + [[integration-testing-support-jdbc]] ==== JDBC Testing Support The `org.springframework.test.jdbc` package contains `JdbcTestUtils`, which is a @@ -17325,9 +18165,12 @@ database which can be used in integration tests that interact with a database. F details, see <> and <>. + + [[integration-testing-annotations]] ==== Annotations + [[integration-testing-annotations-spring]] ===== Spring Testing Annotations The Spring Framework provides the following set of __Spring-specific__ annotations that @@ -17802,6 +18645,7 @@ public void afterTransaction() { } ---- + [[integration-testing-annotations-standard]] ===== Standard Annotation Support The following annotations are supported with standard semantics for all configurations @@ -17834,6 +18678,7 @@ therefore recommended to use test lifecycle callbacks from the underlying test f instead of `@PostConstruct` and `@PreDestroy`. ==== + [[integration-testing-annotations-junit]] ===== Spring JUnit Testing Annotations The following annotations are __only__ supported when used in conjunction with the @@ -17959,6 +18804,8 @@ public void testProcessRepeatedly() { } ---- + + [[testcontext-framework]] ==== Spring TestContext Framework The __Spring `TestContext` Framework__ (located in the @@ -17982,6 +18829,7 @@ to go directly to the configuration (<>), <>, and <> sections. + [[testcontext-key-abstractions]] ===== Key abstractions The core of the framework consists of the `TestContext` and `TestContextManager` classes @@ -18069,6 +18917,7 @@ The following sections explain how to configure the `TestContext` framework thro annotations and provide working examples of how to write unit and integration tests with the framework. + [[testcontext-ctx-management]] ===== Context management Each `TestContext` provides context management and caching support for the test instance @@ -19088,6 +19937,7 @@ cleared. For further details consult the discussion of `@DirtiesContext` in ==== -- + [[testcontext-fixture-di]] ===== Dependency injection of test fixtures When you use the `DependencyInjectionTestExecutionListener` -- which is configured by @@ -19238,6 +20088,7 @@ is used as a fallback qualifier value, so you may effectively also point to a sp bean by name there (as shown above, assuming that "myDataSource" is the bean id). ==== + [[testcontext-web-scoped-beans]] ===== Testing request and session scoped beans @@ -19374,6 +20225,7 @@ public class SessionScopedBeanTests { } ---- + [[testcontext-tx]] ===== Transaction management In the TestContext framework, transactions are managed by the @@ -19500,6 +20352,7 @@ public void updateWithSessionFlush() { ---- ==== + [[testcontext-support-classes]] ===== TestContext Framework support classes @@ -19619,6 +20472,8 @@ instrumenting your test class with a `TestContextManager`. See the source code o `AbstractTestNGSpringContextTests` for an example of how to instrument your test class. ==== + + [[spring-mvc-test-framework]] ==== Spring MVC Test Framework @@ -19649,6 +20504,7 @@ without requiring a running Servlet container. Client-side tests are `RestTemplate`-based and allow tests for code that relies on the `RestTemplate` without requiring a running server to respond to the requests. + [[spring-mvc-test-server]] ===== Server-Side Tests Before Spring Framework 3.2, the most likely way to test a Spring MVC controller was to @@ -20042,6 +20898,7 @@ for further ideas. Also the https://github.com/SpringSource/spring-mvc-showcase[spring-mvc-showcase] has full test coverage based on Spring MVC Test. + [[spring-mvc-test-client]] ===== Client-Side REST Tests Client-side tests are for code using the `RestTemplate`. The goal is to define expected @@ -20087,6 +20944,8 @@ Spring MVC Test's own tests include https://github.com/SpringSource/spring-framework/tree/master/spring-test/src/test/java/org/springframework/test/web/client/samples[example tests] of client-side REST tests. + + [[testing-examples-petclinic]] ==== PetClinic Example The PetClinic application, available from the <>, @@ -20186,6 +21045,9 @@ configuration, which will not vary between the test and production environments. addition, it is advisable to use properties files for connection settings. See the PetClinic application for an example. + + + [[testing-resources]] === Further Resources Consult the following resources for more information about testing: @@ -20209,6 +21071,11 @@ Consult the following resources for more information about testing: database into a known state between test runs. * http://grinder.sourceforge.net/[The Grinder]: Java load testing framework. + + + + + [[spring-data-tier]] = Data Access This part of the reference documentation is concerned with data access and the @@ -20224,9 +21091,16 @@ that the Spring Framework integrates with. * <> * <> + + + + [[transaction]] == Transaction Management + + + [[transaction-intro]] === Introduction to Spring Framework transaction management Comprehensive transaction support is among the most compelling reasons to use the Spring @@ -20260,6 +21134,9 @@ server integration, and solutions to common problems.) * <> covers support for programmatic (that is, explicitly coded) transaction management. + + + [[transaction-motivation]] === Advantages of the Spring Framework's transaction support model Traditionally, Java EE developers have had two choices for transaction management: @@ -20268,6 +21145,8 @@ and local transaction management is reviewed in the next two sections, followed discussion of how the Spring Framework's transaction management support addresses the limitations of the global and local transaction models. + + [[transaction-global]] ==== Global transactions Global transactions enable you to work with multiple transactional resources, typically @@ -20289,6 +21168,8 @@ implement business logic in EJBs, or at least behind a transactional EJB facade. 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. + + [[transaction-local]] ==== Local transactions Local transactions are resource-specific, such as a transaction associated with a JDBC @@ -20300,6 +21181,8 @@ correctness across multiple resources. (It is worth noting that most application single transaction resource.) Another downside is that local transactions are invasive to the programming model. + + [[transaction-programming-model]] ==== Spring Framework's consistent programming model @@ -20342,6 +21225,9 @@ transactions. With the Spring Framework, only some of the bean definitions in yo configuration file, rather than your code, need to change. **** + + + [[transaction-strategies]] === Understanding the Spring Framework transaction abstraction The key to the Spring transaction abstraction is the notion of a __transaction @@ -20566,6 +21452,9 @@ 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. + + + [[tx-resource-synchronization]] === Synchronizing resources with transactions It should now be clear how you create different transaction managers, and how they are @@ -20577,6 +21466,8 @@ ensures that these resources are created, reused, and cleaned up properly. The s also discusses how transaction synchronization is triggered (optionally) through the relevant `PlatformTransactionManager`. + + [[tx-resource-synchronization-high]] ==== High-level synchronization approach The preferred approach is to use Spring's highest level template based persistence @@ -20589,6 +21480,8 @@ persistence logic. Generally, you use the native ORM API or take a __template__ for JDBC access by using the `JdbcTemplate`. These solutions are detailed in subsequent chapters of this reference documentation. + + [[tx-resource-synchronization-low]] ==== Low-level synchronization approach Classes such as `DataSourceUtils` (for JDBC), `EntityManagerFactoryUtils` (for JPA), @@ -20629,6 +21522,8 @@ 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. + + [[tx-resource-synchronization-tadsp]] ==== TransactionAwareDataSourceProxy @@ -20643,6 +21538,9 @@ that case, it is possible that this code is usable, but participating in Spring transactions. It is preferable to write your new code by using the higher level abstractions mentioned above. + + + [[transaction-declarative]] === Declarative transaction managementWhere is [NOTE] @@ -20707,6 +21605,8 @@ 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. + + [[tx-decl-explained]] ==== Understanding the Spring Framework's declarative transaction implementation It is not sufficient to tell you simply to annotate your classes with the @@ -20732,6 +21632,8 @@ Conceptually, calling a method on a transactional proxy looks like this... image::images/tx.png[] + + [[transaction-declarative-first-example]] ==== Example of declarative transaction implementation Consider the following interface, and its attendant implementation. This example uses @@ -20963,6 +21865,8 @@ Exception in thread "main" java.lang.UnsupportedOperationException at Boot.main(Boot.java:11) ---- + + [[transaction-declarative-rolling-back]] ==== Rolling back a declarative transaction The previous section outlined the basics of how to specify transactional settings for @@ -21051,6 +21955,8 @@ You are strongly encouraged to use the declarative approach to rollback if at al possible. Programmatic rollback is available should you absolutely need it, but its usage flies in the face of achieving a clean POJO-based architecture. + + [[transaction-declarative-diff-tx]] ==== Configuring different transactional semantics for different beans Consider the scenario where you have a number of service layer objects, and you want to @@ -21165,6 +22071,8 @@ transactional settings. ---- + + [[transaction-declarative-txadvice-settings]] ==== settings @@ -21227,6 +22135,8 @@ that are nested within `` and `` tags are summarized `com.foo.MyBusinessException,ServletException.` |=== + + [[transaction-declarative-annotations]] ==== Using Method visibility and @Transactional @@ -21439,6 +22349,7 @@ public class DefaultFooService implements FooService { } ---- + [[transaction-declarative-attransactional-settings]] ===== @Transactional settings @@ -21507,6 +22418,7 @@ transactions, the transaction name is always the fully-qualified class name + ". `handlePayment(..)` method of the `BusinessService` class started a transaction, the name of the transaction would be: `com.foo.BusinessService.handlePayment`. + [[tx-multiple-tx-mgrs-with-attransactional]] ===== Multiple Transaction Managers with @Transactional Most Spring applications only need a single transaction manager, but there may be @@ -21553,6 +22465,7 @@ transaction managers, differentiated by the "order" and "account" qualifiers. Th default `` target bean name `transactionManager` will still be used if no specifically qualified PlatformTransactionManager bean is found. + [[tx-custom-attributes]] ===== Custom shortcut annotations If you find you are repeatedly using the same attributes with `@Transactional` on many @@ -21595,6 +22508,8 @@ Here we have used the syntax to define the transaction manager qualifier, but co have included propagation behavior, rollback rules, timeouts etc. + + [[tx-propagation]] ==== Transaction propagation This section describes some semantics of transaction propagation in Spring. Please note @@ -21604,6 +22519,7 @@ details some of the semantics regarding transaction propagation in Spring. In Spring-managed transactions, be aware of the difference between __physical__ and __logical__ transactions, and how the propagation setting applies to this difference. + [[tx-propagation-required]] ===== Required image::images/tx_prop_required.png[] @@ -21629,6 +22545,7 @@ is not aware) silently marks a transaction as rollback-only, the outer caller st calls commit. The outer caller needs to receive an `UnexpectedRollbackException` to indicate clearly that a rollback was performed instead. + [[tx-propagation-requires_new]] ===== RequiresNew image::images/tx_prop_requires_new.png[] @@ -21641,6 +22558,7 @@ underlying physical transactions are different and hence can commit or roll back independently, with an outer transaction not affected by an inner transaction's rollback status. + [[tx-propagation-nested]] ===== Nested `PROPAGATION_NESTED` uses a __single__ physical transaction with multiple savepoints @@ -21650,6 +22568,8 @@ the physical transaction despite some operations having been rolled back. This s is typically mapped onto JDBC savepoints, so will only work with JDBC resource transactions. See Spring's `DataSourceTransactionManager`. + + [[transaction-declarative-applying-more-than-just-tx-advice]] ==== Advising transactional operations Suppose you want to execute __both__ transactional __and__ some basic profiling advice. @@ -21818,6 +22738,8 @@ order value. You configure additional aspects in similar fashion. + + [[transaction-declarative-aspectj]] ==== Using @Transactional with AspectJ @@ -21870,6 +22792,9 @@ http://www.eclipse.org/aspectj/doc/released/devguide/index.html[AspectJ Developm Guide]) or use load-time weaving. See <> for a discussion of load-time weaving with AspectJ. + + + [[transaction-programmatic]] === Programmatic transaction management The Spring Framework provides two means of programmatic transaction management: @@ -21881,6 +22806,8 @@ The Spring team generally recommends the `TransactionTemplate` for programmatic transaction management. The second approach is similar to using the JTA `UserTransaction` API, although exception handling is less cumbersome. + + [[tx-prog-template]] ==== Using the TransactionTemplate @@ -21965,6 +22892,7 @@ transactionTemplate.execute(new TransactionCallbackWithoutResult() { }); ---- + [[tx-prog-template-settings]] ===== Specifying transaction settings You can specify transaction settings such as the propagation mode, the isolation level, @@ -22014,6 +22942,8 @@ of a `TransactionTemplate`, if a class needs to use a `TransactionTemplate` with different settings (for example, a different isolation level), then you need to create two distinct `TransactionTemplate` instances. + + [[transaction-programmatic-ptm]] ==== Using the PlatformTransactionManager @@ -22042,6 +22972,9 @@ catch (MyException ex) { txManager.commit(status); ---- + + + [[tx-decl-vs-prog]] === Choosing between programmatic and declarative transaction management Programmatic transaction management is usually a good idea only if you have a small @@ -22058,6 +22991,9 @@ management out of business logic, and is not difficult to configure. When using Spring Framework, rather than EJB CMT, the configuration cost of declarative transaction management is greatly reduced. + + + [[transaction-application-server-integration]] === Application server-specific integration Spring's transaction abstraction generally is application server agnostic. Additionally, @@ -22083,6 +23019,8 @@ configure server-specific adapter classes (as discussed in the following section explicitly; rather, they are chosen automatically, with the standard `JtaTransactionManager` as default fallback. + + [[transaction-application-server-integration-websphere]] ==== IBM WebSphere On WebSphere 6.1.0.9 and above, the recommended Spring JTA transaction manager to use is @@ -22091,6 +23029,8 @@ which is available in WebSphere Application Server 6.0.2.19 and later and 6.1.0. later. With this adapter, Spring-driven transaction suspension (suspend/resume as initiated by `PROPAGATION_REQUIRES_NEW`) is officially supported by IBM! + + [[transaction-application-server-integration-weblogic]] ==== Oracle WebLogic Server On WebLogic Server 9.0 or above, you typically would use the @@ -22100,9 +23040,14 @@ full power of Spring's transaction definitions in a WebLogic-managed transaction environment, beyond standard JTA semantics: Features include transaction names, per-transaction isolation levels, and proper resuming of transactions in all cases. + + + [[transaction-solutions-to-common-problems]] === Solutions to common problems + + [[transaction-solutions-to-common-problems-wrong-ptm]] ==== Use of the wrong transaction manager for a specific DataSource @@ -22117,6 +23062,9 @@ attempts to perform local transactions on resources such as container `DataSourc instances. Such local transactions do not make sense, and a good application server treats them as errors. + + + [[transaction-resources]] === Further Resources For more information about the Spring Framework's transaction support: @@ -22130,9 +23078,16 @@ For more information about the Spring Framework's transaction support: to transactions in Java. It also includes side-by-side examples of how to configure and use transactions with both the Spring Framework and EJB3. + + + + [[dao]] == DAO support + + + [[dao-introduction]] === Introduction The Data Access Object (DAO) support in Spring is aimed at making it easy to work with @@ -22141,6 +23096,9 @@ allows one to switch between the aforementioned persistence technologies fairly and it also allows one to code without worrying about catching exceptions that are specific to each technology. + + + [[dao-exceptions]] === Consistent exception hierarchy Spring provides a convenient translation from technology-specific exceptions like @@ -22174,6 +23132,9 @@ class hierarchy detailed in the image shows only a subset of the entire image::images/DataAccessException.gif[] + + + [[dao-annotations]] === Annotations used for configuring DAO or Repository classes The best way to guarantee that your Data Access Objects (DAOs) or repositories provide @@ -22260,9 +23221,16 @@ Please see the specific coverage of each persistence technology for details on h configure the application context to take advantage of these annotations. ==== + + + + [[jdbc]] == Data access with JDBC + + + [[jdbc-introduction]] === Introduction to Spring Framework JDBC The value-add provided by the Spring Framework JDBC abstraction is perhaps best shown by @@ -22319,6 +23287,8 @@ developer. The Spring Framework takes care of all the low-level details that can make JDBC such a tedious API to develop with. + + [[jdbc-choose-style]] ==== Choosing an approach for JDBC database access You can choose among several approaches to form the basis for your JDBC database access. @@ -22353,6 +23323,8 @@ and varargs. string, declare parameters, and compile the query. Once you do that, execute methods can be called multiple times with various parameter values passed in. + + [[jdbc-packages]] ==== Package hierarchy The Spring Framework's JDBC abstraction framework consists of four different packages, @@ -22387,9 +23359,14 @@ RDBMS-specific error handling. All translated exceptions are unchecked, which gi the option of catching the exceptions from which you can recover while allowing other exceptions to be propagated to the caller. See <>. + + + [[jdbc-core]] === Using the JDBC core classes to control basic JDBC processing and error handling + + [[jdbc-JdbcTemplate]] ==== JdbcTemplate @@ -22425,6 +23402,7 @@ corresponding to the fully qualified class name of the template instance (typica `JdbcTemplate`, but it may be different if you are using a custom subclass of the `JdbcTemplate` class). + [[jdbc-JdbcTemplate-examples]] ===== Examples of JdbcTemplate class usage This section provides some examples of `JdbcTemplate` class usage. These examples are @@ -22571,6 +23549,7 @@ this.jdbcTemplate.update( Long.valueOf(unionId)); ---- + [[jdbc-JdbcTemplate-idioms]] ===== JdbcTemplate best practices @@ -22695,6 +23674,8 @@ You may want multiple `JdbcTemplate` instances if your application accesses mult databases, which requires multiple `DataSources`, and subsequently multiple differently configured `JdbcTemplates`. + + [[jdbc-NamedParameterJdbcTemplate]] ==== NamedParameterJdbcTemplate @@ -22828,6 +23809,8 @@ functionality only present in the `JdbcTemplate` class, you can use the See also <> for guidelines on using the `NamedParameterJdbcTemplate` class in the context of an application. + + [[jdbc-SQLExceptionTranslator]] ==== SQLExceptionTranslator @@ -22919,6 +23902,8 @@ public void updateShippingCharge(long orderId, long pct) { The custom translator is passed a data source in order to look up the error codes in `sql-error-codes.xml`. + + [[jdbc-statements-executing]] ==== Executing statements Executing an SQL statement requires very little code. You need a `DataSource` and a @@ -22946,6 +23931,8 @@ public class ExecuteAStatement { } ---- + + [[jdbc-statements-querying]] ==== Running queries Some query methods return a single value. To retrieve a count or a specific value from @@ -23010,6 +23997,8 @@ The list returned would look something like this: [{name=Bob, id=1}, {name=Mary, id=2}] ---- + + [[jdbc-updates]] ==== Updating the database The following example shows a column updated for a certain primary key. In this example, @@ -23040,6 +24029,8 @@ public class ExecuteAnUpdate { } ---- + + [[jdbc-auto-genereted-keys]] ==== Retrieving auto-generated keys An `update()` convenience method supports the retrieval of primary keys generated by the @@ -23072,9 +24063,14 @@ jdbcTemplate.update( // keyHolder.getKey() now contains the generated key ---- + + + [[jdbc-connections]] === Controlling database connections + + [[jdbc-datasource]] ==== DataSource @@ -23168,6 +24164,8 @@ C3P0 configuration: ---- + + [[jdbc-DataSourceUtils]] ==== DataSourceUtils @@ -23175,6 +24173,8 @@ The `DataSourceUtils` class is a convenient and powerful helper class that provi `static` methods to obtain connections from JNDI and close connections if necessary. It supports thread-bound connections with, for example, `DataSourceTransactionManager`. + + [[jdbc-SmartDataSource]] ==== SmartDataSource @@ -23183,6 +24183,8 @@ connection to a relational database. It extends the `DataSource` interface to al classes using it to query whether the connection should be closed after a given operation. This usage is efficient when you know that you will reuse a connection. + + [[jdbc-AbstractDataSource]] ==== AbstractDataSource @@ -23191,6 +24193,8 @@ implementations that implements code that is common to all `DataSource` implemen You extend the `AbstractDataSource` class if you are writing your own `DataSource` implementation. + + [[jdbc-SingleConnectionDataSource]] ==== SingleConnectionDataSource @@ -23208,6 +24212,8 @@ application server, in conjunction with a simple JNDI environment. In contrast t `DriverManagerDataSource`, it reuses the same connection all the time, avoiding excessive creation of physical connections. + + [[jdbc-DriverManagerDataSource]] ==== DriverManagerDataSource @@ -23223,6 +24229,8 @@ using JavaBean-style connection pools such as `commons-dbcp` is so easy, even in environment, that it is almost always preferable to use such a connection pool over `DriverManagerDataSource`. + + [[jdbc-TransactionAwareDataSourceProxy]] ==== TransactionAwareDataSourceProxy @@ -23242,6 +24250,8 @@ own new code using the higher level abstractions for resource management, such a __(See the `TransactionAwareDataSourceProxy` Javadocs for more details.)__ + + [[jdbc-DataSourceTransactionManager]] ==== DataSourceTransactionManager @@ -23267,6 +24277,8 @@ resource case, as it does not require the container to support JTA. Switching be both is just a matter of configuration, if you stick to the required connection lookup pattern. JTA does not support custom isolation levels! + + [[jdbc-NativeJdbcExtractor]] ==== NativeJdbcExtractor Sometimes you need to access vendor specific JDBC methods that differ from the standard @@ -23289,12 +24301,17 @@ environment: Usually the `SimpleNativeJdbcExtractor` is sufficient for unwrapping a `Connection` object in most environments. See the Javadocs for more details. + + + [[jdbc-advanced-jdbc]] === JDBC batch operations Most JDBC drivers provide improved performance if you batch multiple calls to the same prepared statement. By grouping updates into batches you limit the number of round trips to the database. + + [[jdbc-batch-classic]] ==== Basic batch operations with the JdbcTemplate You accomplish `JdbcTemplate` batch processing by implementing two methods of a special @@ -23343,6 +24360,8 @@ If you are processing a stream of updates or reading from a interrupt a batch once the input source is exhausted. The `isBatchExhausted` method allows you to signal the end of the batch. + + [[jdbc-batch-list]] ==== Batch operations with a List of objects Both the `JdbcTemplate` and the `NamedParameterJdbcTemplate` provides an alternate way @@ -23420,6 +24439,8 @@ All of the above batch update methods return an int array is reported by the JDBC driver. If the count is not available, the JDBC driver returns a -2 value. + + [[jdbc-batch-multi]] ==== Batch operations with multiple batches The last example of a batch update deals with batches that are so large that you want to @@ -23474,6 +24495,9 @@ The batch update methods for this call returns an array of statement is the one reported by the JDBC driver. If the count is not available, the JDBC driver returns a -2 value. + + + [[jdbc-simple-jdbc]] === Simplifying JDBC operations with the SimpleJdbc classes The `SimpleJdbcInsert` and `SimpleJdbcCall` classes provide a simplified configuration @@ -23481,6 +24505,8 @@ by taking advantage of database metadata that can be retrieved through the JDBC This means there is less to configure up front, although you can override or turn off the metadata processing if you prefer to provide all the details in your code. + + [[jdbc-simple-jdbc-insert-1]] ==== Inserting data using SimpleJdbcInsert Let's start by looking at the `SimpleJdbcInsert` class with the minimal amount of @@ -23522,6 +24548,8 @@ important thing to note here is that the keys used for the Map must match the co names of the table as defined in the database. This is because we read the metadata in order to construct the actual insert statement. + + [[jdbc-simple-jdbc-insert-2]] ==== Retrieving auto-generated keys using SimpleJdbcInsert This example uses the same insert as the preceding, but instead of passing in the id it @@ -23565,6 +24593,8 @@ the base class that you can rely on. If you have multiple auto-generated columns generated values are non-numeric, then you can use a `KeyHolder` that is returned from the `executeReturningKeyHolder` method. + + [[jdbc-simple-jdbc-insert-3]] ==== Specifying columns for a SimpleJdbcInsert You can limit the columns for an insert by specifying a list of column names with the @@ -23601,6 +24631,8 @@ public class JdbcActorDao implements ActorDao { The execution of the insert is the same as if you had relied on the metadata to determine which columns to use. + + [[jdbc-simple-jdbc-parameters]] ==== Using SqlParameterSource to provide parameter values Using a `Map` to provide parameter values works fine, but it's not the most convenient @@ -23670,6 +24702,8 @@ As you can see, the configuration is the same; only the executing code has to change to use these alternative input classes. + + [[jdbc-simple-jdbc-call-1]] ==== Calling a stored procedure with SimpleJdbcCall The `SimpleJdbcCall` class leverages metadata in the database to look up names of `in` @@ -23782,6 +24816,8 @@ public class JdbcActorDao implements ActorDao { By taking this action, you avoid conflicts in the case used for the names of your returned `out` parameters. + + [[jdbc-simple-jdbc-call-2]] ==== Explicitly declaring parameters to use for a SimpleJdbcCall You have seen how the parameters are deduced based on metadata, but you can declare then @@ -23839,6 +24875,8 @@ The execution and end results of the two examples are the same; this one specifies all details explicitly rather than relying on metadata. + + [[jdbc-params]] ==== How to define SqlParameters To define a parameter for the SimpleJdbc classes and also for the RDBMS operations @@ -23876,6 +24914,8 @@ provide a `RowMapper` to handle mapping of rows returned from a `REF` cursor. An option is to specify an `SqlReturnType` that provides an opportunity to define customized handling of the return values. + + [[jdbc-simple-jdbc-call-3]] ==== Calling a stored function using SimpleJdbcCall You call a stored function in almost the same way as you call a stored procedure, except @@ -23935,6 +24975,8 @@ public class JdbcActorDao implements ActorDao { The execute method used returns a `String` containing the return value from the function call. + + [[jdbc-simple-jdbc-call-4]] ==== Returning ResultSet/REF Cursor from a SimpleJdbcCall Calling a stored procedure or function that returns a result set is a bit tricky. Some @@ -23994,6 +25036,9 @@ The execute call passes in an empty Map because this call does not take any parameters. The list of Actors is then retrieved from the results map and returned to the caller. + + + [[jdbc-object]] === Modeling JDBC operations as Java objects The `org.springframework.jdbc.object` package contains classes that allow you to access @@ -24014,6 +25059,8 @@ However, if you are getting measurable value from using the RDBMS operation clas continue using these classes. ==== + + [[jdbc-SqlQuery]] ==== SqlQuery @@ -24025,6 +25072,8 @@ the `MappingSqlQuery` subclass provides a much more convenient implementation fo mapping rows to Java classes. Other implementations that extend `SqlQuery` are `MappingSqlQueryWithParameters` and `UpdatableSqlQuery`. + + [[jdbc-MappingSqlQuery]] ==== MappingSqlQuery @@ -24098,6 +25147,8 @@ public List searchForActors(int age, String namePattern) { } ---- + + [[jdbc-SqlUpdate]] ==== SqlUpdate @@ -24140,6 +25191,8 @@ public class UpdateCreditRating extends SqlUpdate { } ---- + + [[jdbc-StoredProcedure]] ==== StoredProcedure @@ -24358,11 +25411,16 @@ public class TitlesAfterDateStoredProcedure extends StoredProcedure { } ---- + + + [[jdbc-parameter-handling]] === 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. + + [[jdbc-type-information]] ==== Providing SQL type information for parameters Usually Spring determines the SQL type of the parameters based on the type of parameter @@ -24383,6 +25441,8 @@ You can provide SQL type information in several ways: `BeanPropertySqlParameterSource` or `MapSqlParameterSource`. They both have methods for registering the SQL type for any of the named parameter values. + + [[jdbc-lob]] ==== Handling BLOB and CLOB objects You can store images, other binary objects, and large chunks of text. These large object @@ -24464,6 +25524,8 @@ Using the method `getClobAsString`, retrieve the contents of the CLOB. <<2>> Using the method `getBlobAsBytes`, retrieve the contents of the BLOB. + + [[jdbc-in-clause]] ==== Passing in lists of values for IN clause The SQL standard allows for selecting rows based on an expression that includes a @@ -24490,6 +25552,8 @@ of object arrays. This list would support multiple expressions defined for the ` clause such as `select * from T_ACTOR where (id, last_name) in ((1, 'Johnson'), (2, 'Harrop'))`. This of course requires that your database supports this syntax. + + [[jdbc-complex-types]] ==== Handling complex types for stored procedure calls When you call stored procedures you can sometimes use complex types specific to the @@ -24571,6 +25635,9 @@ SqlTypeValue value = new AbstractSqlTypeValue() { }; ---- + + + [[jdbc-embedded-database-support]] === Embedded database support The `org.springframework.jdbc.datasource.embedded` package provides support for embedded @@ -24579,12 +25646,16 @@ http://www.h2database.com[H2], and http://db.apache.org/derby[Derby] is provided natively. You can also use an extensible API to plug in new embedded database types and `DataSource` implementations. + + [[jdbc-why-embedded-database]] ==== Why use an embedded database? An embedded database is useful during the development phase of a project because of its lightweight nature. Benefits include ease of configuration, quick startup time, testability, and the ability to rapidly evolve SQL during development. + + [[jdbc-embedded-database-xml]] ==== Creating an embedded database instance using Spring XML If you want to expose an embedded database instance as a bean in a Spring @@ -24604,6 +25675,8 @@ schema.sql and testdata.sql resources in the classpath. The database instance is available to the Spring container as a bean of type `javax.sql.DataSource`. This bean can then be injected into data access objects as needed. + + [[jdbc-embedded-database-java]] ==== Creating an embedded database instance programmatically The `EmbeddedDatabaseBuilder` class provides a fluent API for constructing an embedded @@ -24619,6 +25692,8 @@ EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); db.shutdown() ---- + + [[jdbc-embedded-database-extension]] ==== Extending the embedded database support Spring JDBC embedded database support can be extended in two ways: @@ -24631,6 +25706,8 @@ Spring JDBC embedded database support can be extended in two ways: You are encouraged to contribute back extensions to the Spring community at jira.springframework.org[jira.springframework.org]. + + [[jdbc-embedded-database-using-HSQL]] ==== Using HSQL Spring supports HSQL 1.8.0 and above. HSQL is the default embedded database if no type @@ -24638,18 +25715,24 @@ is specified explicitly. To specify HSQL explicitly, set the `type` attribute of `embedded-database` tag to `HSQL`. If you are using the builder API, call the `setType(EmbeddedDatabaseType)` method with `EmbeddedDatabaseType.HSQL`. + + [[jdbc-embedded-database-using-H2]] ==== Using H2 Spring supports the H2 database as well. To enable H2, set the `type` attribute of the `embedded-database` tag to `H2`. If you are using the builder API, call the `setType(EmbeddedDatabaseType)` method with `EmbeddedDatabaseType.H2`. + + [[jdbc-embedded-database-using-Derby]] ==== Using Derby Spring also supports Apache Derby 10.5 and above. To enable Derby, set the `type` attribute of the `embedded-database` tag to `Derby`. If using the builder API, call the `setType(EmbeddedDatabaseType)` method with `EmbeddedDatabaseType.Derby`. + + [[jdbc-embedded-database-dao-testing]] ==== Testing data access logic with an embedded database Embedded databases provide a lightweight way to test data access code. The following is @@ -24683,6 +25766,9 @@ public class DataAccessUnitTestTemplate { } ---- + + + [[jdbc-intializing-datasource]] === Initializing a DataSource The `org.springframework.jdbc.datasource.init` package provides support for initializing @@ -24690,6 +25776,8 @@ an existing `DataSource`. The embedded database support provides one option for and initializing a `DataSource` for an application, but sometimes you need to initialize an instance running on a server somewhere. + + [[jdbc-initializing-datasource-xml]] ==== Initializing a database instance using Spring XML If you want to initialize a database and you can provide a reference to a DataSource @@ -24757,6 +25845,7 @@ drops) or `ALL` (ignore all failures). If you need more control than you get from the XML namespace, you can simply use the `DataSourceInitializer` directly, and define it as a component in your application. + [[jdbc-client-component-initialization]] ===== Initialization of Other Components that Depend on the Database A large class of applications can just use the database initializer with no further @@ -24802,9 +25891,16 @@ The second option can also be easy. Some suggestions on how to implement this ar components that depend on it. E.g. specify the bundle start up order as datasource -> initializer -> business components. + + + + [[orm]] == Object Relational Mapping (ORM) Data Access + + + [[orm-introduction]] === Introduction to ORM with Spring The Spring Framework supports integration with Hibernate, Java Persistence API (JPA), @@ -24867,6 +25963,9 @@ Benefits of using the Spring Framework to create your ORM DAOs include: __TODO: provide links to current samples__ + + + [[orm-general]] === General ORM integration considerations This section highlights considerations that apply to all ORM technologies. The @@ -24886,6 +25985,8 @@ many important objects are JavaBeans: data access templates, data access objects transaction managers, business services that use the data access objects and transaction managers, web view resolvers, web controllers that use the business services,and so on. + + [[orm-resource-mngmnt]] ==== Resource and transaction management Typical business applications are cluttered with repetitive resource management code. @@ -24909,6 +26010,8 @@ Spring transaction managers. For the supported ORM technologies Spring offers Hi JPA and JDO support through the Hibernate, JPA, and JDO transaction managers as well as JTA support. For details on transaction support, see the <> chapter. + + [[orm-exception-translation]] ==== Exception translation When you use Hibernate, JPA, or JDO in a DAO, you must decide how to handle the @@ -24958,6 +26061,9 @@ annotations, while still benefiting from Spring-managed transactions, dependency injection, and transparent exception conversion (if desired) to Spring's custom exception hierarchies. + + + [[orm-hibernate]] === Hibernate We will start with a coverage of http://www.hibernate.org/[Hibernate 3] in a Spring @@ -24972,6 +26078,8 @@ chapter will then cover the other ORM technologies, showing briefer examples the As of Spring 3.0, Spring requires Hibernate 3.2 or later. ==== + + [[orm-session-factory-setup]] ==== SessionFactory setup in a Spring container @@ -25031,6 +26139,8 @@ You can also access a JNDI-located `SessionFactory`, using Spring's `JndiObjectFactoryBean` / `` to retrieve and expose it. However, that is typically not common outside of an EJB context. + + [[orm-hibernate-straight]] ==== Implementing DAOs based on plain Hibernate 3 API Hibernate 3 has a feature called contextual sessions, wherein Hibernate itself manages @@ -25105,6 +26215,8 @@ This behavior applies regardless of whether you are using Spring's In summary: you can implement DAOs based on the plain Hibernate 3 API, while still being able to participate in Spring-managed transactions. + + [[orm-hibernate-tx-declarative]] ==== Declarative transaction demarcation We recommend that you use Spring's declarative transaction support, which enables you to @@ -25260,6 +26372,8 @@ provide is the TransactionManager implementation and a "" ---- + + [[orm-hibernate-tx-programmatic]] ==== Programmatic transaction demarcation You can demarcate transactions in a higher level of the application, on top of such @@ -25324,6 +26438,8 @@ unchecked application exception, or if the transaction is marked rollback-only b application (via `TransactionStatus`). `TransactionInterceptor` behaves the same way by default but allows configurable rollback policies per method. + + [[orm-hibernate-tx-strategies]] ==== Transaction management strategies Both `TransactionTemplate` and `TransactionInterceptor` delegate the actual transaction @@ -25432,6 +26548,8 @@ exposes the Hibernate transaction as a JDBC transaction if you have set up the p `DataSource` for which the transactions are supposed to be exposed through the `dataSource` property of the `HibernateTransactionManager` class. + + [[orm-hibernate-resources]] ==== Comparing container-managed and locally defined resources You can switch between a container-managed JNDI `SessionFactory` and a locally defined @@ -25476,6 +26594,8 @@ transactions, without the inconvenience of container deployment. JNDI registrati Hibernate `SessionFactory` through the JCA connector only adds value when used in conjunction with EJBs. + + [[orm-hibernate-invalid-jdbc-access-error]] ==== Spurious application server warnings with Hibernate In some JTA environments with very strict `XADataSource` implementations -- currently @@ -25542,12 +26662,17 @@ following events occur when a JTA transaction commits: through an__afterCompletion__ callback by the JTA transaction manager, and can properly clear its cache. + + + [[orm-jdo]] === JDO Spring supports the standard JDO 2.0 and 2.1 APIs as data access strategy, following the same style as the Hibernate support. The corresponding integration classes reside in the `org.springframework.orm.jdo` package. + + [[orm-jdo-setup]] ==== PersistenceManagerFactory setup @@ -25603,6 +26728,8 @@ context, no real benefit exists in holding the `PersistenceManagerFactory` in JN choose such a setup for a good reason. See <> for a discussion; the arguments there apply to JDO as well. + + [[orm-jdo-daos-straight]] ==== Implementing DAOs based on the plain JDO API DAOs can also be written directly against plain JDO API, without any Spring @@ -25741,6 +26868,8 @@ Spring-managed transactions. This strategy might appeal to you if you are alread familiar with JDO. However, such DAOs throw plain `JDOException`, and you would have to convert explicitly to Spring's `DataAccessException` (if desired). + + [[orm-jdo-tx]] ==== Transaction management [NOTE] @@ -25808,6 +26937,8 @@ that accesses the same JDBC `DataSource`, provided that the registered `JdoDiale supports retrieval of the underlying JDBC `Connection`. This is the case for JDBC-based JDO 2.0 implementations by default. + + [[orm-jdo-dialect]] ==== JdoDialect @@ -25830,6 +26961,9 @@ supported by Spring, usually in a vendor-specific manner: See the `JdoDialect` Javadoc for more details on its operations and how to use them within Spring's JDO support. + + + [[orm-jpa]] === JPA The Spring JPA, available under the `org.springframework.orm.jpa` package, offers @@ -25838,11 +26972,14 @@ http://java.sun.com/developer/technicalArticles/J2EE/jpa/index.html[Java Persist API] in a similar manner to the integration with Hibernate or JDO, while being aware of the underlying implementation in order to provide additional features. + + [[orm-jpa-setup]] ==== Three options for JPA setup in a Spring environment The Spring JPA support offers three ways of setting up the JPA `EntityManagerFactory` that will be used by the application to obtain an entity manager. + [[orm-jpa-setup-lemfb]] ===== LocalEntityManagerFactoryBean @@ -25877,6 +27014,7 @@ provider-specific, often requiring a specific JVM agent to specified on startup. option is sufficient only for stand-alone applications and test environments, for which the JPA specification is designed. + [[orm-jpa-setup-jndi]] ===== Obtaining an EntityManagerFactory from JNDI @@ -25918,6 +27056,7 @@ JNDI-retrieved persistence units should match the persistence unit names that th application uses to refer to them, for example, in `@PersistenceUnit` and `@PersistenceContext` annotations. + [[orm-jpa-setup-lcemfb]] ===== When is load-time weaving required? LocalContainerEntityManagerFactoryBean @@ -26055,6 +27194,7 @@ This is important especially when the hosting applications rely on different JPA implementations because the JPA transformers are applied only at class loader level and thus are isolated from each other. + [[orm-jpa-multiple-pu]] ===== Dealing with multiple persistence units For applications that rely on multiple persistence units locations, stored in various @@ -26098,6 +27238,8 @@ affect __all__ hosted units, or programmatically, through the `PersistenceUnitManager` is specified, one is created and used internally by `LocalContainerEntityManagerFactoryBean`. + + [[orm-jpa-straight]] ==== Implementing DAOs based on plain JPA [NOTE] @@ -26235,6 +27377,8 @@ import of any Spring class is required. Moreover, as the JPA annotations are und the injections are applied automatically by the Spring container. This is appealing from a non-invasiveness perspective, and might feel more natural to JPA developers. + + [[orm-jpa-tx]] ==== Transaction Management [NOTE] @@ -26292,6 +27436,8 @@ JDBC access code that accesses the same JDBC `DataSource`, provided that the reg Spring provides dialects for the Toplink, Hibernate and OpenJPA JPA implementations. See the next section for details on the `JpaDialect` mechanism. + + [[orm-jpa-dialect]] ==== JpaDialect @@ -26316,9 +27462,16 @@ specify the appropriate dialect. See the `JpaDialect` Javadoc for more details of its operations and how they are used within Spring's JPA support. + + + + [[oxm]] == Marshalling XML using O/X Mappers + + + [[oxm-introduction]] === Introduction In this chapter, we will describe Spring's Object/XML Mapping support. Object/XML @@ -26333,6 +27486,8 @@ stream, or a SAX handler. Some of the benefits of using Spring for your O/X mapping needs are: + + ==== Ease of configuration Spring's bean factory makes it easy to configure marshallers, without needing to construct JAXB context, JiBX binding factories, etc. The marshallers can be configured @@ -26340,6 +27495,8 @@ as any other bean in your application context. Additionally, XML Schema-based configuration is available for a number of marshallers, making the configuration even simpler. + + ==== Consistent Interfaces Spring's O/X mapping operates through two global interfaces: the `Marshaller` and `Unmarshaller` interface. These abstractions allow you to switch O/X mapping frameworks @@ -26349,17 +27506,24 @@ marshalling with a mix-and-match approach (e.g. some marshalling performed using other using XMLBeans) in a non-intrusive fashion, leveraging the strength of each technology. + + ==== Consistent Exception Hierarchy Spring provides a conversion from exceptions from the underlying O/X mapping tool to its own exception hierarchy with the `XmlMappingException` as the root exception. As can be expected, these runtime exceptions wrap the original exception so no information is lost. + + + [[oxm-marshaller-unmarshaller]] === Marshaller and Unmarshaller As stated in the introduction, a __marshaller__ serializes an object to XML, and an __unmarshaller__ deserializes XML stream to an object. In this section, we will describe the two Spring interfaces used for this purpose. + + [[oxm-marshaller]] ==== Marshaller Spring abstracts all marshalling operations behind the @@ -26407,6 +27571,8 @@ marshaller, or have a common base class. Refer to the further sections in this c to determine how your O/X technology of choice manages this. ==== + + [[oxm-unmarshaller]] ==== Unmarshaller Similar to the `Marshaller`, there is the `org.springframework.oxm.Unmarshaller` @@ -26450,6 +27616,8 @@ Even though there are two separate marshalling interfaces ( `Marshaller` and This means that you can wire up one marshaller class and refer to it both as a marshaller and an unmarshaller in your `applicationContext.xml`. + + [[oxm-xmlmappingexception]] ==== XmlMappingException Spring converts exceptions from the underlying O/X mapping tool to its own exception @@ -26465,6 +27633,9 @@ image::images/oxm-exceptions.png[] O/X Mapping exception hierarchy + + + [[oxm-usage]] === Using Marshaller and Unmarshaller Spring's OXM can be used for a wide variety of situations. In the following example, we @@ -26587,6 +27758,9 @@ This sample application produces the following `settings.xml` file: ---- + + + [[oxm-schema-based-config]] === XML Schema-based Configuration Marshallers could be configured more concisely using tags from the OXM namespace. To @@ -26618,6 +27792,9 @@ here is how the configuration of a JAXB2 marshaller might look like: ---- + + + [[oxm-jaxb]] === JAXB The JAXB binding compiler translates a W3C XML Schema into one or more Java classes, a @@ -26629,6 +27806,8 @@ Spring supports the JAXB 2.0 API as XML marshalling strategies, following the The corresponding integration classes reside in the `org.springframework.oxm.jaxb` package. + + [[oxm-jaxb2]] ==== Jaxb2Marshaller The `Jaxb2Marshaller` class implements both the Spring `Marshaller` and `Unmarshaller` @@ -26657,6 +27836,7 @@ validation is performed by specifying one or more schema resource to the bean, l ---- + [[oxm-jaxb2-xsd]] ===== XML Schema-based Configuration The `jaxb2-marshaller` tag configures a `org.springframework.oxm.jaxb.Jaxb2Marshaller`. @@ -26695,6 +27875,9 @@ Available attributes are: | no |=== + + + [[oxm-castor]] === Castor Castor XML mapping is an open source XML binding framework. It allows you to transform @@ -26706,6 +27889,8 @@ For more information on Castor, refer to the http://castor.codehaus.org/xml-framework.html[__Castor web site__]. The Spring integration classes reside in the `org.springframework.oxm.castor` package. + + [[oxm-castor-marshaller]] ==== CastorMarshaller As with JAXB, the `CastorMarshaller` implements both the `Marshaller` and `Unmarshaller` @@ -26722,6 +27907,8 @@ interface. It can be wired up as follows: ---- + + [[oxm-castor-mapping]] ==== Mapping Although it is possible to rely on Castor's default marshalling behavior, it might be @@ -26742,6 +27929,7 @@ with a classpath resource. ---- + [[oxm-castor-xsd]] ===== XML Schema-based Configuration The `castor-marshaller` tag configures a @@ -26788,6 +27976,9 @@ Available attributes are: | no |=== + + + [[oxm-xmlbeans]] === XMLBeans XMLBeans is an XML binding tool that has full XML Schema support, and offers full XML @@ -26799,6 +27990,8 @@ For more information on XMLBeans, refer to the http://xmlbeans.apache.org/[__XML web site __]. The Spring-WS integration classes reside in the `org.springframework.oxm.xmlbeans` package. + + [[oxm-xmlbeans-marshaller]] ==== XmlBeansMarshaller The `XmlBeansMarshaller` implements both the `Marshaller` and `Unmarshaller` interfaces. @@ -26821,6 +28014,7 @@ Note that the `XmlBeansMarshaller` can only marshal objects of type `XmlObject`, every `java.lang.Object`. ==== + [[oxm-xmlbeans-xsd]] ===== XML Schema-based Configuration The `xmlbeans-marshaller` tag configures a @@ -26847,6 +28041,9 @@ Available attributes are: | no |=== + + + [[oxm-jibx]] === JiBX The JiBX framework offers a solution similar to that which JDO provides for ORM: a @@ -26859,6 +28056,8 @@ For more information on JiBX, refer to the http://jibx.sourceforge.net/[__JiBX w site__]. The Spring integration classes reside in the `org.springframework.oxm.jibx` package. + + [[oxm-jibx-marshaller]] ==== JibxMarshaller The `JibxMarshaller` class implements both the `Marshaller` and `Unmarshaller` @@ -26882,6 +28081,7 @@ A `JibxMarshaller` is configured for a single class. If you want to marshal mult classes, you have to configure multiple `JibxMarshaller` s with different `targetClass` property values. + [[oxm-jibx-xsd]] ===== XML Schema-based Configuration The `jibx-marshaller` tag configures a `org.springframework.oxm.jibx.JibxMarshaller`. @@ -26911,6 +28111,9 @@ Available attributes are: | no |=== + + + [[oxm-xstream]] === XStream XStream is a simple library to serialize objects to XML and back again. It does not @@ -26920,6 +28123,8 @@ For more information on XStream, refer to the http://xstream.codehaus.org/[__XSt web site__]. The Spring integration classes reside in the `org.springframework.oxm.xstream` package. + + [[oxm-xstream-marshaller]] ==== XStreamMarshaller The `XStreamMarshaller` does not require any configuration, and can be configured in an @@ -26977,6 +28182,11 @@ NOTE: Note that XStream is an XML serialization library, not a data binding libr Therefore, it has limited namespace support. As such, it is rather unsuitable for usage within Web services. + + + + + [[spring-web]] = The Web @@ -26995,9 +28205,16 @@ This section concludes with coverage of Spring's MVC <> * <> + + + + [[mvc]] == Web MVC framework + + + [[mvc-introduction]] === Introduction to Spring Web MVC framework The Spring Web model-view-controller (MVC) framework is designed around a @@ -27049,6 +28266,8 @@ such as JSP, Velocity and Freemarker, or directly generate XML, JSON, Atom, and other types of content. The model `Map` is simply transformed into an appropriate format, such as JSP request attributes, a Velocity template model. + + [[mvc-features]] ==== Features of Spring Web MVC @@ -27108,6 +28327,8 @@ Spring's web module includes many unique web support features: `WebApplicationContext` container(s) that Spring MVC uses. These bean scopes are described in <> + + [[mvc-introduction-pluggability]] ==== Pluggability of other MVC implementations Non-Spring MVC implementations are preferable for some projects. Many teams expect to @@ -27132,6 +28353,9 @@ configuration to data access and transaction handling. So you can enrich your application with a Spring middle tier and/or data access tier, even if you just want to use, for example, the transaction abstraction with JDBC or Hibernate. + + + [[mvc-servlet]] === The DispatcherServlet @@ -27255,6 +28479,8 @@ a link to the `ServletContext`). The `WebApplicationContext` is bound in the `ServletContext`, and by using static methods on the `RequestContextUtils` class you can always look up the `WebApplicationContext` if you need access to it. + + [[mvc-servlet-special-bean-types]] ==== Special Bean Types In the WebApplicationContext @@ -27304,6 +28530,8 @@ a| <> attributes from one request to another, usually across a redirect. |=== + + [[mvc-servlet-config]] ==== Default DispatcherServlet Configuration As mentioned in the previous section for each special bean the `DispatcherServlet` @@ -27328,6 +28556,8 @@ and assume little knowledge of how Spring MVC works. Regardless of how you choos configure your application, the concepts explained in this section are fundamental should be of help to you. + + [[mvc-servlet-sequence]] ==== DispatcherServlet Processing Sequence After you set up a `DispatcherServlet`, and a request comes in for that specific @@ -27388,6 +28618,9 @@ initialization parameters ( `init-param` elements) to the Servlet declaration in | Namespace of the `WebApplicationContext`. Defaults to `[servlet-name]-servlet`. |=== + + + [[mvc-controller]] === Implementing Controllers Controllers provide access to the application behavior that you typically define through @@ -27433,6 +28666,8 @@ a number of other annotations form the basis for the Spring MVC implementation. section documents these annotations and how they are most commonly used in a Servlet environment. + + [[mvc-ann-controller]] ==== Defining a controller with @Controller @@ -27475,6 +28710,8 @@ snippet: ---- + + [[mvc-ann-requestmapping]] ==== Mapping Requests With Using @RequestMapping @@ -27587,6 +28824,7 @@ Note however that method argument annotations, e.g. `@RequestParam`, must be pre the method signatures of the controller class. ==== + [[mvc-ann-requestmapping-31-vs-30]] ===== New Support Classes for @RequestMapping methods in Spring MVC 3.1 Spring 3.1 introduced a new set of support classes for `@RequestMapping` methods called @@ -27629,6 +28867,7 @@ There are also several things no longer possible: The above features are still supported with the existing support classes. However to take advantage of new Spring MVC 3.1 features you'll need to use the new support classes. + [[mvc-ann-requestmapping-uri-templates]] ===== URI Template Patterns __URI templates__ can be used for convenient access to selected parts of a URL in a @@ -27729,6 +28968,7 @@ Spring automatically converts to the appropriate type or throws a `TypeMismatchException` if it fails to do so. You can also register support for parsing additional data types. See <> and <>. + [[mvc-ann-requestmapping-uri-templates-regex]] ===== URI Template Patterns with Regular Expressions Sometimes you need more precision in defining URI template variables. Consider the URL @@ -27748,12 +28988,14 @@ name and the second - the regular expression.For example: } ---- + [[mvc-ann-requestmapping-patterns]] ===== Path Patterns In addition to URI templates, the `@RequestMapping` annotation also supports Ant-style path patterns (for example, `/myPath/*.do`). A combination of URI templates and Ant-style globs is also supported (for example, `/owners/*/pets/{petId}`). + [[mvc-ann-requestmapping-placeholders]] ===== Patterns with Placeholders Patterns in `@RequestMapping` annotations support ${...} placeholders against local @@ -27762,6 +29004,7 @@ cases where the path a controller is mapped to may need to be customized through configuration. For more information on placeholders see the Javadoc for `PropertyPlaceholderConfigurer`. + [[mvc-ann-matrix-variables]] ===== Matrix Variables The URI specification http://tools.ietf.org/html/rfc3986#section-3.3[RFC 3986] defines @@ -27853,6 +29096,7 @@ Note that to enable the use of matrix variables, you must set the `removeSemicolonContent` property of `RequestMappingHandlerMapping` to `false`. By default it is set to `false`. + [[mvc-ann-requestmapping-consumes]] ===== Consumable Media Types You can narrow the primary mapping by specifying a list of consumable media types. The @@ -27880,6 +29124,7 @@ other conditions, when used at the type level, method-level consumable types ove rather than extend type-level consumable types. ==== + [[mvc-ann-requestmapping-produces]] ===== Producible Media Types You can narrow the primary mapping by specifying a list of producible media types. The @@ -27910,6 +29155,7 @@ other conditions, when used at the type level, method-level producible types ove rather than extend type-level producible types. ==== + [[mvc-ann-requestmapping-params-and-headers]] ===== Request Parameters and Header Values You can narrow request matching through request parameter conditions such as @@ -27957,6 +29203,8 @@ __"text/html"__), it is recommended to use the __consumes__ and __produces__ con respectively instead. They are intended specifically for that purpose. ==== + + [[mvc-ann-methods]] ==== Defining @RequestMapping handler methods @@ -27975,6 +29223,7 @@ namespace and with use of the MVC Java config but must be configured explicitly neither. ==== + [[mvc-ann-arguments]] ===== Supported method argument types The following are the supported method arguments: @@ -28070,6 +29319,7 @@ this working you have to reorder the parameters as follows: public String processSubmit(**@ModelAttribute("pet") Pet pet**, **BindingResult result**, Model model) { ... } ---- + [[mvc-ann-return-types]] ===== Supported method return types The following are the supported return types: @@ -28110,6 +29360,7 @@ The following are the supported return types: is implicitly enriched with command objects and the results of `@ModelAttribute` annotated reference data accessor methods. + [[mvc-ann-requestparam]] ===== Binding request parameters to method parameters with @RequestParam @@ -28144,6 +29395,7 @@ parameter is optional by setting `@RequestParam`'s `required` attribute to `fals Type conversion is applied automatically if the target method parameter type is not `String`. See <>. + [[mvc-ann-requestbody]] ===== Mapping the request body with the @RequestBody annotation The `@RequestBody` method parameter annotation indicates that a method parameter should @@ -28222,6 +29474,7 @@ information on configuring message converters and a validator through the MVC na or the MVC Java config. ==== + [[mvc-ann-responsebody]] ===== Mapping the response body with the @ResponseBody annotation @@ -28246,6 +29499,7 @@ As with `@RequestBody`, Spring converts the returned object to a response body b an `HttpMessageConverter`. For more information on these converters, see the previous section and <>. + [[mvc-ann-httpentity]] ===== Using HttpEntity @@ -28277,6 +29531,7 @@ As with `@RequestBody` and `@ResponseBody`, Spring uses `HttpMessageConverter` t convert from and to the request and response streams. For more information on these converters, see the previous section and <>. + [[mvc-ann-modelattrib-methods]] ===== Using @ModelAttribute on a method @@ -28345,6 +29600,7 @@ that case the return value of the `@RequestMapping` method is interpreted as a m attribute rather than as a view name. The view name is derived from view name conventions instead much like for methods returning void -- see <>. + [[mvc-ann-modelattrib-method-args]] ===== Using @ModelAttribute on a method argument @@ -28464,6 +29720,7 @@ public String processSubmit(**@Valid @ModelAttribute("pet") Pet pet**, BindingRe See <> and <> for details on how to configure and use validation. + [[mvc-ann-sessionattrib]] ===== Using @SessionAttributes to store model attributes in the HTTP session between requests @@ -28493,6 +29750,7 @@ __all__ your mapping annotations - such as `@RequestMapping` and `@SessionAttrib on the controller __interface__ rather than on the implementation class. ==== + [[mvc-ann-redirect-attributes]] ===== Specifying redirect and flash attributes By default all model attributes are considered to be exposed as URI template variables @@ -28521,6 +29779,7 @@ controller serving the target redirect URL automatically receives these flash at after which they are removed from the session. See <> for an overview of the general support for flash attributes in Spring MVC. + [[mvc-ann-form-urlencoded-data]] ===== Working with "application/x-www-form-urlencoded" data @@ -28567,6 +29826,7 @@ configured for PUT or PATCH URLs that rely on other converters for String>` and `HttpEntity>`. ==== + [[mvc-ann-cookievalue]] ===== Mapping cookie values with the @CookieValue annotation The `@CookieValue` annotation allows a method parameter to be bound to the value of an @@ -28597,6 +29857,7 @@ Type conversion is applied automatically if the target method parameter type is This annotation is supported for annotated handler methods in Servlet and Portlet environments. + [[mvc-ann-requestheader]] ===== Mapping request header attributes with the @RequestHeader annotation The `@RequestHeader` annotation allows a method parameter to be bound to a request header. @@ -28641,6 +29902,7 @@ example a method parameter annotated with `@RequestHeader("Accept")` may be of t This annotation is supported for annotated handler methods in Servlet and Portlet environments. + [[mvc-ann-typeconversion]] ===== Method Parameters And Type Conversion String-based values extracted from the request including request parameters, path @@ -28652,6 +29914,7 @@ long, Date, etc. are supported. You can further customize the conversion process a `WebDataBinder` (see <>) or by registering `Formatters` with the `FormattingConversionService` (see <>). + [[mvc-ann-webdatabinder]] ===== Customizing WebDataBinder initialization To customize request parameter binding with PropertyEditors through Spring's @@ -28726,6 +29989,7 @@ which case they apply to all controllers. This provides an alternative to using The `@ControllerAdvice` annotation is a component annotation allowing implementation classes to be autodetected through classpath scanning. + [[mvc-ann-lastmodified]] ===== Support for the Last-Modified Response Header To Facilitate Content Caching An `@RequestMapping` method may wish to support `'Last-Modified'` HTTP requests, as @@ -28759,6 +30023,8 @@ returning `null`. The former sets the response status to 304 before it returns ` The latter, in combination with the former, causes Spring MVC to do no further processing of the request. + + [[mvc-ann-async]] ==== Asynchronous Request Processing Spring MVC 3.2 introduced Servlet 3 based asynchronous request processing. Instead of @@ -28848,6 +30114,7 @@ beyond the scope of this document. For further information you may wish to read http://spring.io/blog/2012/05/07/spring-mvc-3-2-preview-introducing-servlet-3-async-support[this blog post series]. + [[mvc-ann-async-exceptions]] ===== Exception Handling for Async Requests What happens if a `Callable` returned from a controller method raises an Exception while @@ -28869,6 +30136,7 @@ If the result is an `Exception`, it will be processed with a matching `@ExceptionHandler` method in the same controller or with any configured `HandlerExceptionResolver` instance. + [[mvc-ann-async-interception]] ===== Intercepting Async Requests An existing `HandlerInterceptor` can implement `AsyncHandlerInterceptor`, which provides @@ -28893,6 +30161,7 @@ You can also register a `CallableProcessingInterceptor` or a namespace. Those interceptors provide a full set of callbacks and apply every time a `Callable` or a `DeferredResult` is used. + [[mvc-ann-async-configuration]] ===== Configuration for Async Request Processing @@ -28948,11 +30217,16 @@ can wrap it in a `WebAsyncTask` and use the appropriate class constructor to cus the timeout value. The class constructor of `WebAsyncTask` also allows providing an `AsyncTaskExecutor`. + + [[mvc-ann-tests]] ==== Testing Controllers The `spring-test` module offers first class support for testing annotated controllers. See <>. + + + [[mvc-handlermapping]] === Handler mappings In previous versions of Spring, users were required to define one or more @@ -28996,6 +30270,8 @@ The following example shows how to configure an interceptor: ---- + + [[mvc-handlermapping-interceptor]] ==== Intercepting requests with a HandlerInterceptor @@ -29100,6 +30376,9 @@ bean instances of type `MappedInterceptor` to do that. See <>. ==== + + + [[mvc-viewresolver]] === Resolving views All MVC frameworks for web applications provide a way to address views. Spring provides @@ -29113,6 +30392,8 @@ and `View`. The `ViewResolver` provides a mapping between view names and actual The `View` interface addresses the preparation of the request and hands the request over to one of the view technologies. + + [[mvc-viewresolver-resolver]] ==== Resolving views with the ViewResolver interface @@ -29210,6 +30491,8 @@ certain view at runtime (for example when a Velocity template is modified), you the `removeFromCache(String viewName, Locale loc)` method. ==== + + [[mvc-viewresolver-chaining]] ==== Chaining ViewResolvers Spring supports multiple view resolvers. Thus you can chain resolvers and, for example, @@ -29260,6 +30543,8 @@ putting an `InternalResourceViewResolver` in the chain in a place other than the results in the chain not being fully inspected, because the `InternalResourceViewResolver` will __always__ return a view! + + [[mvc-redirecting]] ==== Redirecting to views As mentioned previously, a controller typically returns a logical view name, which a @@ -29286,6 +30571,7 @@ the result of a `POST` but rather of a `GET`. The end effect is that there is no user can accidentally re- `POST` the same data by performing a refresh. The refresh forces a `GET` of the result page, not a resend of the initial `POST` data. + [[mvc-redirecting-redirect-view]] ===== RedirectView @@ -29329,6 +30615,7 @@ recommended that you configure the redirect URL to be injected into the controll that it is not baked into the controller but configured in the context along with the view names. The next section discusses this process. + [[mvc-redirecting-redirect-prefix]] ===== The redirect: prefix @@ -29349,6 +30636,7 @@ name such as `redirect:/myapp/some/resource` will redirect relative to the curre Servlet context, while a name such as `redirect:http://myhost.com/some/arbitrary/path` will redirect to an absolute URL. + [[mvc-redirecting-forward-prefix]] ===== The forward: prefix @@ -29365,6 +30653,8 @@ As with the `redirect:` prefix, if the view name with the `forward:` prefix is i into the controller, the controller does not detect that anything special is happening in terms of handling the response. + + [[mvc-multiple-representations]] ==== ContentNegotiatingViewResolver @@ -29504,6 +30794,9 @@ public class ContentController { } ---- + + + [[mvc-flash-attributes]] === Using flash attributes Flash attributes provide a way for one request to store attributes intended for use in @@ -29548,6 +30841,9 @@ reduces it greatly with information that is already available in the redirect UR Therefore the use of flash attributes is recommended mainly for redirect scenarios . **** + + + [[mvc-construct-encode-uri]] === Building URIs @@ -29624,6 +30920,9 @@ ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromServletMapping(request).path("/accounts").build() ---- + + + [[mvc-localeresolver]] === Using locales Most parts of Spring's architecture support internationalization, just as the Spring web @@ -29644,6 +30943,8 @@ Locale resolvers and interceptors are defined in the context in the normal way. Here is a selection of the locale resolvers included in Spring. + + [[mvc-localeresolver-acceptheader]] ==== AcceptHeaderLocaleResolver @@ -29651,6 +30952,8 @@ This locale resolver inspects the `accept-language` header in the request that w by the client (e.g., a web browser). Usually this header field contains the locale of the client's operating system. + + [[mvc-localeresolver-cookie]] ==== CookieLocaleResolver @@ -29694,12 +30997,16 @@ below an example of defining a `CookieLocaleResolver`. specified, the cookie will only be visible to that path and the paths below it. |=== + + [[mvc-localeresolver-session]] ==== SessionLocaleResolver The `SessionLocaleResolver` allows you to retrieve locales from the session that might be associated with the user's request. + + [[mvc-localeresolver-interceptor]] ==== LocaleChangeInterceptor @@ -29735,9 +31042,14 @@ change the site language to Dutch. ---- + + + [[mvc-themeresolver]] === Using themes + + [[mvc-themeresolver-introduction]] ==== Overview of themes You can apply Spring Web MVC framework themes to set the overall look-and-feel of your @@ -29745,6 +31057,8 @@ application, thereby enhancing user experience. A theme is a collection of stati resources, typically style sheets and images, that affect the visual style of the application. + + [[mvc-themeresolver-defining]] ==== Defining themes To use themes in your web application, you must set up an implementation of the @@ -29794,6 +31108,8 @@ resource bundle loading mechanism, allowing for full internationalization of the example, we could have a `/WEB-INF/classes/cool_nl.properties` that references a special background image with Dutch text on it. + + [[mvc-themeresolver-resolving]] ==== Theme resolvers After you define themes, as in the preceding section, you decide which theme to use. The @@ -29822,9 +31138,14 @@ alter the request's theme. The following theme resolvers are provided by Spring: Spring also provides a `ThemeChangeInterceptor` that allows theme changes on every request with a simple request parameter. + + + [[mvc-multipart]] === Spring's multipart (file upload) support + + [[mvc-multipart-introduction]] ==== Introduction Spring's built-in multipart support handles file uploads in web applications. You enable @@ -29841,6 +31162,8 @@ multipart is found in the request, the `MultipartResolver` that has been declare your context is used. After that, the multipart attribute in your request is treated like any other attribute. + + [[mvc-multipart-resolver-commons]] ==== Using a MultipartResolver with __Commons FileUpload__ @@ -29868,6 +31191,8 @@ supports multipart file uploads. Using the `MultipartHttpServletRequest`, you ca information about the multiparts contained by this request and actually get access to the multipart files themselves in your controllers. + + [[mvc-multipart-resolver-standard]] ==== Using a MultipartResolver with __Servlet 3.0__ @@ -29890,6 +31215,8 @@ you can add the `StandardServletMultipartResolver` to your Spring configuration: ---- + + [[mvc-multipart-forms]] ==== Handling a file upload in a form After the `MultipartResolver` completes its job, the request is processed like any @@ -29967,6 +31294,8 @@ public class FileUploadController { } ---- + + [[mvc-multipart-forms-non-browsers]] ==== Handling a file upload request from programmatic clients Multipart requests can also be submitted from non-browser clients in a RESTful service @@ -30023,9 +31352,14 @@ Notice how `MultipartFile` method arguments can be accessed with `@RequestParam` argument in this case is read as JSON content based on its `'Content-Type'` header and converted with the help of the `MappingJackson2HttpMessageConverter`. + + + [[mvc-exceptionhandlers]] === Handling exceptions + + [[mvc-exceptionhandlers-resolver]] ==== HandlerExceptionResolver @@ -30051,6 +31385,8 @@ within an `@Controller` or may apply globally to all `@RequestMapping` methods w defined within an `@ControllerAdvice` class. The following sections explain this in more detail. + + [[mvc-ann-exceptionhandler]] ==== @ExceptionHandler @@ -30103,6 +31439,8 @@ interpreted as a view name, a `ModelAndView` object, a `ResponseEntity`, or you add the `@ResponseBody` to have the method return value converted with message converters and written to the response stream. + + [[mvc-ann-rest-spring-mvc-exceptions]] ==== Handling Standard Spring MVC Exceptions Spring MVC may raise a number of exceptions while processing a request. The @@ -30175,6 +31513,8 @@ Spring MVC exceptions and return `ResponseEntity`. That allows you to customize response and write error content with message converters. See the Javadoc of `ResponseEntityExceptionHandler` for more details. + + [[mvc-ann-annotated-exceptions]] ==== Annotating Business Exceptions With @ResponseStatus @@ -30183,6 +31523,8 @@ raised, the `ResponseStatusExceptionResolver` handles it by setting the status o response accordingly. By default the `DispatcherServlet` registers the `ResponseStatusExceptionResolver` and it is available for use. + + [[mvc-ann-customer-servlet-container-error-page]] ==== Customizing the Default Servlet Container Error Page When the status of the response is set to an error status code and the body of the @@ -30239,6 +31581,9 @@ or in a JSP: } ---- + + + [[mvc-coc]] === Convention over configuration support For a lot of projects, sticking to established conventions and having reasonable @@ -30253,6 +31598,8 @@ you choose to move forward with it into production. Convention-over-configuration support addresses the three core areas of MVC: models, views, and controllers. + + [[mvc-coc-ccnhm]] ==== The Controller ControllerClassNameHandlerMapping @@ -30315,6 +31662,8 @@ The `ControllerClassNameHandlerMapping` class extends the `AbstractHandlerMappin class so you can define `HandlerInterceptor` instances and everything else just as you would with many other `HandlerMapping` implementations. + + [[mvc-coc-modelmap]] ==== The Model ModelMap (ModelAndView) @@ -30386,6 +31735,8 @@ semantics of name generation for collections clearer: * An __empty__ `java.util.ArrayList` will not be added at all (in effect, the `addObject(..)` call will essentially be a no-op). + + [[mvc-coc-r2vnt]] ==== The View - RequestToViewNameTranslator @@ -30464,6 +31815,9 @@ your own `DefaultRequestToViewNameTranslator` bean explicitly. Consult the compr Javadoc for the `DefaultRequestToViewNameTranslator` class for details of the various properties that can be configured. + + + [[mvc-etag]] === ETag support An http://en.wikipedia.org/wiki/HTTP_ETag[ETag] (entity tag) is an HTTP response header @@ -30500,6 +31854,9 @@ You configure the `ShallowEtagHeaderFilter` in `web.xml`: ---- + + + [[mvc-container-config]] === Code-based Servlet container initialization In a Servlet 3.0+ environment, you have the option of configuring the Servlet container @@ -30610,6 +31967,9 @@ The `isAsyncSupported` protected method of `AbstractDispatcherServletInitializer provides a single place to enable async support on the `DispatcherServlet` and all filters mapped to it. By default this flag is set to `true`. + + + [[mvc-config]] === Configuring Spring MVC <> and <> explained about Spring @@ -30628,6 +31988,8 @@ preference. Also as you will see further below, with the MVC Java config it is e see the underlying configuration as well as to make fine-grained customizations directly to the created Spring MVC beans. But let's start from the beginning. + + [[mvc-config-enable]] ==== Enabling the MVC Java Config or the MVC XML Namespace To enable MVC Java config add the annotation `@EnableWebMvc` to one of your @@ -30703,6 +32065,8 @@ classpath. .. `RssChannelHttpMessageConverter` converts RSS feeds -- added if Rome is present on the classpath. + + [[mvc-config-customize]] ==== Customizing the Provided Configuration To customize the default configuration in Java you simply implement the @@ -30757,6 +32121,8 @@ available. The sample below shows a subset of what is available: ---- + + [[mvc-config-interceptors]] ==== Configuring Interceptors You can configure `HandlerInterceptors` or `WebRequestInterceptors` to be applied to all @@ -30800,6 +32166,8 @@ And in XML use the `` element: ---- + + [[mvc-config-content-negotiation]] ==== Configuring Content Negotiation Staring with Spring Framework 3.2, you can configure how Spring MVC determines the @@ -30870,6 +32238,8 @@ resolves the requested media type to `"application/json"`. Or you may want to pl custom strategy that has some logic to select a default content type (e.g. either XML or JSON) if no content types were requested. + + [[mvc-config-view-controller]] ==== Configuring View Controllers This is a shortcut for defining a `ParameterizableViewController` that immediately @@ -30901,6 +32271,8 @@ And the same in XML use the `` element: ---- + + [[mvc-config-static-resources]] ==== Configuring Serving of Resources This option allows static resource requests following a particular URL pattern to be @@ -31073,6 +32445,8 @@ Spring JSP tags: ---- + + [[mvc-default-servlet-handler]] ==== mvc:default-servlet-handler This tag allows for mapping the `DispatcherServlet` to "/" (thus overriding the mapping @@ -31144,6 +32518,8 @@ Or in XML: ---- + + [[mvc-resources]] ==== More Spring Web MVC Resources See the following links and pointers for more resources about Spring Web MVC: @@ -31154,6 +32530,8 @@ See the following links and pointers for more resources about Spring Web MVC: * "Expert Spring Web MVC and Web Flow" by Seth Ladd and others (published by Apress) is an excellent hard copy source of Spring Web MVC goodness. + + [[mvc-config-advanced-java]] ==== Advanced Customizations with MVC Java Config As you can see from the above examples, MVC Java config and the MVC namespace provide @@ -31199,6 +32577,8 @@ public class WebConfig extends WebMvcConfigurationSupport { Note that modifying beans in this way does not prevent you from using any of the higher-level constructs shown earlier in this section. + + [[mvc-config-advanced-xml]] ==== Advanced Customizations with the MVC Namespace Fine-grained control over the configuration created for you is a bit harder with the MVC @@ -31227,9 +32607,16 @@ Note that `MyPostProcessor` needs to be included in an `` in o it to be detected or if you prefer you can declare it explicitly with an XML bean declaration. + + + + [[view]] == View technologies + + + [[view-introduction]] === Introduction One of the areas in which Spring excels is in the separation of view technologies from @@ -31239,6 +32626,9 @@ view technologies that work with Spring and touches briefly on how to add new on chapter assumes you are already familiar with <> which covers the basics of how views in general are coupled to the MVC framework. + + + [[view-jsp]] === JSP & JSTL Spring provides a couple of out-of-the-box solutions for JSP and JSTL views. Using JSP @@ -31257,6 +32647,8 @@ servlet version is 2.4 (JSP 2.0 and JSTL 1.1), which reduces the scope for confu somewhat. ==== + + [[view-jsp-resolver]] ==== View resolvers Just as with any other view technology you're integrating with Spring, for JSPs you'll @@ -31298,12 +32690,16 @@ The `InternalResourceBundleViewResolver` can be configured for using JSPs as des above. As a best practice, we strongly encourage placing your JSP files in a directory under the `'WEB-INF'` directory, so there can be no direct access by clients. + + [[view-jsp-jstl]] ==== 'Plain-old' JSPs versus JSTL When using the Java Standard Tag Library you must use a special view class, the `JstlView`, as JSTL needs some preparation before things such as the I18N features will work. + + [[view-jsp-tags]] ==== Additional tags facilitating development Spring provides data binding of request parameters to command objects as described in @@ -31315,6 +32711,8 @@ The tag library descriptor (TLD) is included in the `spring-webmvc.jar`. Further information about the individual tags can be found in the appendix entitled <>. + + [[view-jsp-formtaglib]] ==== Using Spring's form tag library As of version 2.0, Spring provides a comprehensive set of data binding-aware tags for @@ -31330,6 +32728,7 @@ JSPs easier to develop, read and maintain. Let's go through the form tags and look at an example of how each tag is used. We have included generated HTML snippets where certain tags require further commentary. + [[view-jsp-formtaglib-configuration]] ===== Configuration The form tag library comes bundled in `spring-webmvc.jar`. The library descriptor is @@ -31346,6 +32745,7 @@ page: where `form` is the tag name prefix you want to use for the tags from this library. + [[view-jsp-formtaglib-formtag]] ===== The form tag @@ -31435,6 +32835,7 @@ The preceding JSP assumes that the variable name of the form backing object is ---- + [[view-jsp-formtaglib-inputtag]] ===== The input tag @@ -31443,6 +32844,7 @@ For an example of this tag, see <>. Starting with S 3.1 you can use other types such HTML5-specific types like 'email', 'tel', 'date', and others. + [[view-jsp-formtaglib-checkboxtag]] ===== The checkbox tag @@ -31562,6 +32964,7 @@ prefixed by an underscore ("_") for each checkbox. By doing this, you are effect telling Spring that "__the checkbox was visible in the form and I want my object to which the form data will be bound to reflect the state of the checkbox no matter what__". + [[view-jsp-formtaglib-checkboxestag]] ===== The checkboxes tag @@ -31597,6 +33000,7 @@ the map entry key will be used as the value and the map entry's value will be us the label to be displayed. You can also use a custom object where you can provide the property names for the value using "itemValue" and the label using "itemLabel". + [[view-jsp-formtaglib-radiobuttontag]] ===== The radiobutton tag @@ -31615,6 +33019,7 @@ but with different values. ---- + [[view-jsp-formtaglib-radiobuttonstag]] ===== The radiobuttons tag @@ -31637,6 +33042,7 @@ label using "itemLabel". ---- + [[view-jsp-formtaglib-passwordtag]] ===== The password tag @@ -31668,6 +33074,7 @@ true, like so. ---- + [[view-jsp-formtaglib-selecttag]] ===== The select tag @@ -31701,6 +33108,7 @@ like: ---- + [[view-jsp-formtaglib-optiontag]] ===== The option tag @@ -31742,6 +33150,7 @@ like: ---- + [[view-jsp-formtaglib-optionstag]] ===== The options tag @@ -31793,6 +33202,7 @@ values and the map values correspond to option labels. If `itemValue` and/or `it happen to be specified as well, the item value property will apply to the map key and the item label property will apply to the map value. + [[view-jsp-formtaglib-textAreatag]] ===== The textarea tag @@ -31808,6 +33218,7 @@ This tag renders an HTML 'textarea'. ---- + [[view-jsp-formtaglib-hiddeninputtag]] ===== The hidden tag @@ -31830,6 +33241,7 @@ If we choose to submit the 'house' value as a hidden one, the HTML would look li ---- + [[view-jsp-formtaglib-errorstag]] ===== The errors tag @@ -31978,6 +33390,7 @@ The HTML would look like: ---- + [[rest-method-conversion]] ===== HTTP Method Conversion A key principle of REST is the use of the Uniform Interface. This means that all @@ -32037,6 +33450,7 @@ public String deletePet(@PathVariable int ownerId, @PathVariable int petId) { } ---- + [[view-jsp-formtaglib-html5]] ===== HTML5 Tags Starting with Spring 3, the Spring form tag library allows entering dynamic attributes, @@ -32047,6 +33461,9 @@ This is intended to allow rendering new HTML5 specific input types such as 'emai 'date', 'range', and others. Note that entering type='text' is not required since 'text' is the default type. + + + [[view-tiles]] === Tiles It is possible to integrate Tiles - just as any other view technology - in web @@ -32059,6 +33476,8 @@ package. Spring also continues to support Tiles 1.x (a.k.a. "Struts Tiles", as s with Struts 1.1+; compatible with Java 1.4) in the original `org.springframework.web.servlet.view.tiles` package. + + [[view-tiles-dependencies]] ==== Dependencies To be able to use Tiles you have to have a couple of additional dependencies included in @@ -32069,6 +33488,8 @@ your project. The following is the list of dependencies you need. * `Commons Digester` * `Commons Logging` + + [[view-tiles-integrate]] ==== How to integrate Tiles To be able to use Tiles, you have to configure it using files containing definitions @@ -32100,6 +33521,7 @@ Spring web application. To be able to use the views you have to have a `ViewReso just as with any other view technology used with Spring. Below you can find two possibilities, the `UrlBasedViewResolver` and the `ResourceBundleViewResolver`. + [[view-tiles-url]] ===== UrlBasedViewResolver @@ -32114,6 +33536,7 @@ resolve. ---- + [[view-tiles-resource]] ===== ResourceBundleViewResolver @@ -32150,6 +33573,7 @@ Note that the `TilesView` class for Tiles 2 supports JSTL (the JSP Standard Tag out of the box, whereas there is a separate `TilesJstlView` subclass in the Tiles 1.x support. + [[view-tiles-preparer]] ===== SimpleSpringPreparerFactory and SpringBeanPreparerFactory @@ -32192,6 +33616,9 @@ per preparer name (as used in your Tiles definitions). ---- + + + [[view-velocity]] === Velocity & FreeMarker http://velocity.apache.org[Velocity] and http://www.freemarker.org[FreeMarker] are two @@ -32200,6 +33627,8 @@ applications. The languages are quite similar and serve similar needs and so are considered together in this section. For semantic and syntactic differences between the two languages, see the http://www.freemarker.org[FreeMarker] web site. + + [[view-velocity-dependencies]] ==== Dependencies Your web application will need to include `velocity-1.x.x.jar` or `freemarker-2.x.jar` @@ -32211,6 +33640,8 @@ your `'WEB-INF/lib'` directory too! If you make use of Spring's 'dateToolAttribu 'numberToolAttribute' in your Velocity views, you will also need to include the `velocity-tools-generic-1.x.jar` + + [[view-velocity-contextconfig]] ==== Context configuration A suitable configuration is initialized by adding the relevant configurer bean @@ -32268,6 +33699,8 @@ For non web-apps add a `VelocityConfigurationFactoryBean` or a `FreeMarkerConfigurationFactoryBean` to your application context definition file. ==== + + [[view-velocity-createtemplates]] ==== Creating templates Your templates need to be stored in the directory specified by the `*Configurer` bean @@ -32279,12 +33712,15 @@ returns a ModelAndView object containing a view name of "welcome" then the resol will look for the `/WEB-INF/freemarker/welcome.ftl` or `/WEB-INF/velocity/welcome.vm` template as appropriate. + + [[view-velocity-advancedconfig]] ==== Advanced configuration The basic configurations highlighted above will be suitable for most application requirements, however additional configuration options are available for when unusual or advanced requirements dictate. + [[view-velocity-example-velocityproperties]] ===== velocity.properties This file is completely optional, but if specified, contains the values that are passed @@ -32326,6 +33762,7 @@ http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/ui/vel documentation] for Spring configuration of Velocity, or the Velocity documentation for examples and definitions of the `'velocity.properties'` file itself. + [[views-freemarker]] ===== FreeMarker FreeMarker 'Settings' and 'SharedVariables' can be passed directly to the FreeMarker @@ -32352,6 +33789,8 @@ the `FreeMarkerConfigurer` bean. The `freemarkerSettings` property requires a See the FreeMarker documentation for details of settings and variables as they apply to the `Configuration` object. + + [[view-velocity-forms]] ==== Bind support and form handling Spring provides a tag library for use in JSP's that contains (amongst other things) a @@ -32361,6 +33800,7 @@ web or business tier. From version 1.1, Spring now has support for the same functionality in both Velocity and FreeMarker, with additional convenience macros for generating form input elements themselves. + [[view-bind-macros]] ===== The bind macros A standard set of macros are maintained within the `spring-webmvc.jar` file for both @@ -32374,6 +33814,7 @@ directly, the files are called spring.vm / spring.ftl and are in the packages `org.springframework.web.servlet.view.velocity` or `org.springframework.web.servlet.view.freemarker` respectively. + [[view-simple-binding]] ===== Simple binding In your html forms (vm / ftl templates) that act as the 'formView' for a Spring form @@ -32441,6 +33882,7 @@ the status error messages or values. Set to true or false as required. Additiona handling macros simplify the use of HTML escaping and these macros should be used wherever possible. They are explained in the next section. + [[views-form-macros]] ===== Form input generation macros Additional convenience macros for both languages simplify both binding and form @@ -32688,6 +34130,7 @@ Paris New York ---- + [[views-form-macros-html-escaping]] ===== HTML escaping and XHTML compliance Default usage of the form macros above will result in HTML tags that are HTML 4.01 @@ -32729,6 +34172,9 @@ In similar fashion, HTML escaping can be specified per field: <#-- all future fields will be bound with HTML escaping off --> ---- + + + [[view-xslt]] === XSLT XSLT is a transformation language for XML and is popular as a view technology within web @@ -32737,6 +34183,8 @@ naturally deals with XML, or if your model can easily be converted to XML. The f section shows how to produce an XML document as model data and have it transformed with XSLT in a Spring Web MVC application. + + [[view-xslt-firstwords]] ==== My First Words This example is a trivial Spring application that creates a list of words in the @@ -32745,6 +34193,7 @@ name of our XSLT view. See <> for details of Spring Web MVC's `Controller` interface. The XSLT view will turn the list of words into a simple XML document ready for transformation. + [[view-xslt-beandefs]] ===== Bean definitions Configuration is standard for a simple Spring application. The dispatcher servlet config @@ -32759,6 +34208,7 @@ bean... ... that encapsulates our word generation logic. + [[view-xslt-controllercode]] ===== Standard MVC controller code The controller logic is encapsulated in a subclass of `AbstractController`, with the @@ -32794,6 +34244,7 @@ complete flexibility to create the DOM from your model in any way you choose. Th prevents the transformation of XML playing too great a part in the structure of your model data which is a danger when using tools to manage the domification process. + [[view-xslt-subclassing]] ===== Convert the model data to XML In order to create a DOM document from our list of words or any other model data, we @@ -32840,6 +34291,7 @@ name="myParam">defaultValue`. To specify the parameters, override th name/value pairs. If your parameters need to derive information from the current request, you can override the `getParameters(HttpServletRequest request)` method instead. + [[view-xslt-viewdefinitions]] ===== Defining the view properties The views.properties file (or equivalent xml definition if you're using an XML based @@ -32861,6 +34313,7 @@ transformation into HTML for us and the final property `'.root'` is the name tha be used as the root of the XML document. This gets passed to the `HomePage` class above in the second parameter to the `createXsltSource(..)` method(s). + [[view-xslt-transforming]] ===== Document transformation Finally, we have the XSLT code used for transforming the above document. As shown in the @@ -32892,6 +34345,8 @@ the war file in the `'WEB-INF/xsl'` directory. ---- + + [[view-xslt-summary]] ==== Summary A summary of the files discussed and their location in the WAR file is shown in the @@ -32930,9 +34385,14 @@ You will also need to ensure that an XML parser and an XSLT engine are available classpath. JDK 1.4 provides them by default, and most Java EE containers will also make them available by default, but it's a possible source of errors to be aware of. + + + [[view-document]] === Document views (PDF/Excel) + + [[view-document-intro]] ==== Introduction Returning an HTML page isn't always the best way for the user to view the model output, @@ -32944,6 +34404,8 @@ spreadsheet or PDF viewer application in response. In order to use Excel views, you need to add the 'poi' library to your classpath, and for PDF generation, the iText library. + + [[view-document-config]] ==== Configuration and setup Document based views are handled in an almost identical fashion to XSLT views, and the @@ -32951,6 +34413,7 @@ following sections build upon the previous one by demonstrating how the same con used in the XSLT example is invoked to render the same model as both a PDF document and an Excel spreadsheet (which can also be viewed or manipulated in Open Office). + [[view-document-configviews]] ===== Document view definitions First, let's amend the views.properties file (or xml equivalent) and add a simple view @@ -32972,6 +34435,7 @@ pdf.(class)=pdf.HomePage __If you want to start with a template spreadsheet or a fillable PDF form to add your model data to, specify the location as the 'url' property in the view definition__ + [[view-document-configcontroller]] ===== Controller code The controller code we'll use remains exactly the same from the XSLT example earlier @@ -32979,6 +34443,7 @@ other than to change the name of the view to use. Of course, you could be clever have this selected based on a URL parameter or some other logic - proof that Spring really is very good at decoupling the views from the controllers! + [[view-document-configsubclasses]] ===== Subclassing for Excel views Exactly as we did for the XSLT example, we'll subclass suitable abstract classes in @@ -33069,6 +34534,7 @@ If you now amend the controller such that it returns `xl` as the name of the vie that the Excel spreadsheet is created and downloaded automatically when you request the same page as before. + [[view-document-configsubclasspdf]] ===== Subclassing for PDF views The PDF version of the word list is even simpler. This time, the class extends @@ -33105,6 +34571,9 @@ Once again, amend the controller to return the `pdf` view with `return new ModelAndView("pdf", map);`, and reload the URL in your application. This time a PDF document should appear listing each of the words in the model map. + + + [[view-jasper-reports]] === JasperReports JasperReports ( http://jasperreports.sourceforge.net[]) is a powerful open-source @@ -33112,6 +34581,8 @@ reporting engine that supports the creation of report designs using an easily un XML file format. JasperReports is capable of rendering reports in four different formats: CSV, Excel, HTML and PDF. + + [[view-jasper-reports-dependencies]] ==== Dependencies Your application will need to include the latest release of JasperReports, which at the @@ -33127,12 +34598,15 @@ time of writing was 0.6.1. JasperReports itself depends on the following project JasperReports also requires a JAXP compliant XML parser. + + [[view-jasper-reports-configuration]] ==== Configuration To configure JasperReports views in your Spring container configuration you need to define a `ViewResolver` to map view names to the appropriate view class depending on which format you want your report rendered in. + [[view-jasper-reports-configuration-resolver]] ===== Configuring the ViewResolver @@ -33151,6 +34625,7 @@ Here we've configured an instance of the `ResourceBundleViewResolver` class that look for view mappings in the resource bundle with base name `views`. (The content of this file is described in the next section.) + [[view-jasper-reports-configuration-views]] ===== Configuring the Views @@ -33196,6 +34671,7 @@ Here you can see that the view with name `simpleReport` is mapped to the format. The `url` property of the view is set to the location of the underlying report file. + [[view-jasper-reports-configuration-report-files]] ===== About Report Files JasperReports has two distinct types of report file: the design file, which has a @@ -33208,6 +34684,7 @@ file is compiled by the Spring Framework, the compiled report is cached for the of the application. Thus, to make changes to the file you will need to restart your application. + [[view-jasper-reports-configuration-multiformat-view]] ===== Using JasperReportsMultiFormatView @@ -33268,6 +34745,8 @@ So in the example above a request to URI /foo/myReport.pdf would be mapped to th `JasperReportsPdfView` class. You can override the mapping key to view class mappings using the `formatMappings` property of `JasperReportsMultiFormatView`. + + [[view-jasper-reports-model]] ==== Populating the ModelAndView @@ -33327,6 +34806,8 @@ Be aware that when using the first approach, Spring will use the first instance instances of `JRDataSource` or `Collection` into the model you need to use the second approach. + + [[view-jasper-reports-subreports]] ==== Working with Sub-Reports JasperReports provides support for embedded sub-reports within your master report files. @@ -33337,6 +34818,7 @@ hard-coded into your report files reducing reusability and making it harder to m and update report designs. To overcome this you can configure sub-reports declaratively, and you can include additional data for these sub-reports directly from your controllers. + [[view-jasper-reports-subreports-config-reports]] ===== Configuring Sub-Report Files To control which sub-report files are included in a master report using Spring, your @@ -33387,6 +34869,7 @@ report design file, and the entry is the URL of the report file. Spring will loa report file, compiling it if necessary, and pass it into the JasperReports engine under the given key. + [[view-jasper-reports-subreports-config-datasources]] ===== Configuring Sub-Report Data Sources This step is entirely optional when using Spring to configure your sub-reports. If you @@ -33405,6 +34888,8 @@ using the `subReportDataKeys` property of your chosen view class: Here, the key you supply __must__ correspond to both the key used in your `ModelAndView` and the key used in your report design file. + + [[view-jasper-reports-exporter-parameters]] ==== Configuring Exporter Parameters If you have special requirements for exporter configuration -- perhaps you want a @@ -33437,6 +34922,9 @@ Here you can see that the `JasperReportsHtmlView` is configured with an exporter parameter for `net.sf.jasperreports.engine.export.JRHtmlExporterParameter.HTML_FOOTER` which will output a footer in the resulting HTML. + + + [[view-feeds]] === Feed Views Both `AbstractAtomFeedView` and `AbstractRssFeedView` inherit from the base class @@ -33501,6 +34989,9 @@ For an example of creating an Atom view please refer to Alef Arendsen's SpringSo Team Blog http://spring.io/blog/2009/03/16/adding-an-atom-view-to-an-application-using-spring-s-rest-support[entry]. + + + [[view-xml-marshalling]] === XML Marshalling View The `MarhsallingView` uses an XML `Marshaller` defined in the `org.springframework.oxm` @@ -33511,6 +35002,9 @@ by the `Marshaller`. For more information on the functionality in the `org.springframework.oxm` package refer to the chapter <>. + + + [[view-json-mapping]] === JSON Mapping View The `MappingJackson2JsonView` (or `MappingJacksonJsonView` depending on the the Jackson @@ -33527,9 +35021,16 @@ annotations. When further control is needed, a custom `ObjectMapper` can be inje through the `ObjectMapper` property for cases where custom JSON serializers/deserializers need to be provided for specific types. + + + + [[web-integration]] == Integrating with other web frameworks + + + [[intro]] === Introduction @@ -33588,6 +35089,9 @@ Struts. If you need further details about any of the supported web frameworks themselves, please do consult <> at the end of this chapter. ==== + + + [[web-integration-common]] === Common configuration Before diving into the integration specifics of each supported web framework, let us @@ -33669,6 +35173,9 @@ beans. Not only do they make it easy to get beans from a Spring container, but t allow you to use dependency injection on their controllers. Each web framework section has more detail on its specific integration strategies. + + + [[jsf]] === JavaServer Faces 1.1 and 1.2 JavaServer Faces (JSF) is the JCP's standard component-based, event-driven web user @@ -33691,6 +35198,8 @@ The key element in Spring's JSF integration is the JSF 1.1 `VariableResolver` me On JSF 1.2, Spring supports the `ELResolver` mechanism as a next-generation version of JSF EL integration. + + [[jsf-delegatingvariableresolver]] ==== DelegatingVariableResolver (JSF 1.1/1.2) The easiest way to integrate one's Spring middle-tier with one's JSF web layer is to use @@ -33740,6 +35249,8 @@ Managed beans are defined in one's `faces-config.xml` file. Find below an exampl ---- + + [[jsf-springbeanvariableresolver]] ==== SpringBeanVariableResolver (JSF 1.1/1.2) `SpringBeanVariableResolver` is a variant of `DelegatingVariableResolver`. It delegates @@ -33762,6 +35273,8 @@ __faces-context.xml__ file: ---- + + [[jsf-springbeanfaceselresolver]] ==== SpringBeanFacesELResolver (JSF 1.2+) `SpringBeanFacesELResolver` is a JSF 1.2 compliant `ELResolver` implementation, @@ -33784,6 +35297,8 @@ __faces-context.xml__ file: ---- + + [[jsf-facescontextutils]] ==== FacesContextUtils A custom `VariableResolver` works well when mapping one's properties to beans @@ -33798,6 +35313,9 @@ takes a `FacesContext` parameter rather than a `ServletContext` parameter. ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()); ---- + + + [[struts]] === Apache Struts 1.x and 2.x http://struts.apache.org[Struts] used to be the __de facto__ web framework for Java @@ -33828,6 +35346,8 @@ To integrate your Struts 1.x application with Spring, you have two options: * Subclass Spring's `ActionSupport` classes and grab your Spring-managed beans explicitly using a__getWebApplicationContext()__ method. + + [[struts-contextloaderplugin]] ==== ContextLoaderPlugin The @@ -33892,6 +35412,7 @@ You must define that Action's bean with the "/users" name in __action-servlet.xm ---- + [[struts-delegatingrequestprocessor]] ===== DelegatingRequestProcessor To configure the @@ -33931,6 +35452,7 @@ http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/st instead. ==== + [[struts-delegatingactionproxy]] ===== DelegatingActionProxy If you have a custom `RequestProcessor` and can't use the `DelegatingRequestProcessor` @@ -33963,6 +35485,8 @@ add__scope="prototype"__ to your Action's bean definition. class="org.example.web.UserAction"/> ---- + + [[struts-actionsupport]] ==== ActionSupport Classes As previously mentioned, you can retrieve the `WebApplicationContext` from the @@ -34011,6 +35535,9 @@ are resolved. In contrast, using the `ContextLoaderPlugin` allows you to easily dependencies in your context XML file. Either way, Spring provides some nice options for integrating with Struts. + + + [[webwork]] === WebWork 2.x From the http://www.opensymphony.com/webwork/[WebWork homepage]: @@ -34047,6 +35574,9 @@ the WebWork site and forums if you are having issues with the integration. But f to post comments and queries regarding the Spring-WebWork integration on the http://forum.springframework.org/forumdisplay.php?f=25[Spring support forums], too. + + + [[tapestry]] === Tapestry 3.x and 4.x From the http://tapestry.apache.org/[Tapestry homepage]: @@ -34083,6 +35613,8 @@ Spring-Tapestry integration code was written - and continues to be maintained - Tapestry creator http://howardlewisship.com/blog/[Howard M. Lewis Ship], so hats off to him for what is really some silky smooth integration). + + [[tapestry-di]] ==== Injecting Spring-managed beans Assume we have the following simple Spring container definition (in the ubiquitous XML @@ -34177,6 +35709,7 @@ This next section is applicable to Tapestry 3.x. If you are using Tapestry versi please consult the section entitled <>. ==== + [[tapestry-pre4-style-di]] ===== Dependency Injecting Spring Beans into Tapestry pages First we need to make the `ApplicationContext` available to the Tapestry page or @@ -34235,6 +35768,7 @@ file: xportal.application: ---- + [[tapestry-componentdefs]] ===== Component definition files Now in our page or component definition file (*.page or *.jwc), we simply add @@ -34302,6 +35836,7 @@ like this: ---- + [[tapestry-getters]] ===== Adding abstract accessors Now in the Java class definition for the page or component itself, all we need to do is @@ -34437,6 +35972,7 @@ public abstract class Login extends BasePage implements ErrorProperty, PageRende } ---- + [[tapestry-4-style-di]] ===== Dependency Injecting Spring Beans into Tapestry pages - Tapestry 4.x style Effecting the dependency injection of Spring-managed beans into Tapestry pages in @@ -34520,6 +36056,9 @@ another implementation, for example, during testing. This inversion of control i the prime goals and benefits of the Spring Framework, and we have managed to extend it throughout the stack in this Tapestry application. + + + [[web-integration-resources]] === Further Resources Find below links to further resources about the various web frameworks described in this @@ -34530,9 +36069,16 @@ chapter. * The http://www.opensymphony.com/webwork/[WebWork] homepage * The http://tapestry.apache.org/[Tapestry] homepage + + + + [[portlet]] == Portlet MVC Framework + + + [[portlet-introduction]] === Introduction @@ -34609,6 +36155,8 @@ level. However, all mechanisms in Spring that depend on the locale (such as internationalization of messages) will still function properly because `DispatcherPortlet` exposes the current locale in the same way as `DispatcherServlet`. + + [[portlet-introduction-controller]] ==== Controllers - The C in MVC The default handler is still a very simple `Controller` interface, offering just two @@ -34621,6 +36169,8 @@ The framework also includes most of the same controller implementation hierarchy as `AbstractController`, `SimpleFormController`, and so on. Data binding, command object usage, model handling, and view resolution are all the same as in the servlet framework. + + [[portlet-introduction-view]] ==== Views - The V in MVC All the view rendering capabilities of the servlet framework are used directly via a @@ -34629,6 +36179,8 @@ request is converted into a servlet request and the view can be rendered using t entire normal servlet infrastructure. This means all the existing renderers, such as JSP, Velocity, etc., can still be used within the portlet. + + [[portlet-introduction-scope]] ==== Web-scoped beans Spring Portlet MVC supports beans whose lifecycle is scoped to the current HTTP request @@ -34637,6 +36189,9 @@ Portlet MVC itself, but rather of the `WebApplicationContext` container(s) that Portlet MVC uses. These bean scopes are described in detail in <> + + + [[portlet-dispatcher]] === The DispatcherPortlet @@ -34767,6 +36322,9 @@ You can customize Spring's `DispatcherPortlet` by adding context parameters in t (see <>). |=== + + + [[portlet-viewservlet]] === The ViewRendererServlet @@ -34808,6 +36366,9 @@ the appropriate arguments. The actual URL for the `ViewRendererServlet` can be changed using `DispatcherPortlet`'s `viewRendererUrl` configuration parameter. + + + [[portlet-controller]] === Controllers The controllers in Portlet MVC are very similar to the Web MVC Controllers, and porting @@ -34845,6 +36406,8 @@ these are very similar to controllers from Spring Web MVC. The `Controller` inte just defines the most common functionality required of every controller: handling an action request, handling a render request, and returning a model and a view. + + [[portlet-controller-abstractcontroller]] ==== AbstractController and PortletContentGenerator @@ -34929,6 +36492,8 @@ The class above and the declaration in the web application context is all you ne besides setting up a handler mapping (see<>) to get this very simple controller working. + + [[portlet-controller-simple]] ==== Other simple controllers Although you can extend `AbstractController`, Spring Portlet MVC provides a number of @@ -34943,6 +36508,8 @@ The `PortletModeNameViewController` uses the current mode of the portlet as the name. So, if your portlet is in View mode (i.e. `PortletMode.VIEW`) then it uses "view" as the view name. + + [[portlet-controller-command]] ==== Command Controllers Spring Portlet MVC has the exact same hierarchy of __command controllers__ as Spring Web @@ -34981,6 +36548,8 @@ understanding of how they operate in order to use them efficiently. Carefully re Javadocs for this entire hierarchy and then look at some sample implementations before you start using them. + + [[portlet-controller-wrapping]] ==== PortletWrappingController @@ -35005,6 +36574,9 @@ post-process requests going to these portlets. Since JSR-168 does not support an of filter mechanism, this is quite handy. For example, this can be used to wrap the Hibernate `OpenSessionInViewInterceptor` around a MyFaces JSF Portlet. + + + [[portlet-handlermapping]] === Handler mappings Using a handler mapping you can map incoming portlet requests to appropriate handlers. @@ -35055,6 +36627,8 @@ properties: handlers are always lazily initialized). Default value is false. This property is directly implemented in the three concrete Handlers. + + [[portlet-handlermapping-portletmode]] ==== PortletModeHandlerMapping @@ -35075,6 +36649,8 @@ of the portlet (e.g. 'view', 'edit', 'help'). An example: ---- + + [[portlet-handlermapping-parameter]] ==== ParameterHandlerMapping @@ -35102,6 +36678,8 @@ The bean configuration for this mapping will look something like this: ---- + + [[portlet-handlermapping-portletmodeparameter]] ==== PortletModeParameterHandlerMapping @@ -35146,6 +36724,8 @@ The bean configuration for this mapping will look something like this: This mapping can be chained ahead of a `PortletModeHandlerMapping`, which can then provide defaults for each mode and an overall default as well. + + [[portlet-handlermapping-interceptor]] ==== Adding HandlerInterceptors @@ -35174,6 +36754,8 @@ The `postHandle` method is only called on a `RenderRequest`. The `preHandle` and If you need to execute logic in these methods for just one type of request, be sure to check what kind of request it is before processing it. + + [[portlet-handlermapping-interceptoradapter]] ==== HandlerInterceptorAdapter @@ -35182,6 +36764,8 @@ As with the servlet package, the portlet package has a concrete implementation o of all the methods so that you can inherit from this class and implement just one or two methods when that is all you need. + + [[portlet-handlermapping-parameterinterceptor]] ==== ParameterMappingInterceptor @@ -35199,6 +36783,9 @@ which means that you cannot call `sendRedirect` in your handler when using this interceptor. If you need to do external redirects then you will either need to forward the mapping parameter manually or write a different interceptor to handle this for you. + + + [[portlet-viewresolver]] === Views and resolving them As mentioned previously, Spring Portlet MVC directly reuses all the view technologies @@ -35225,6 +36812,9 @@ mentioning: Also, for JSP development, the new Spring Taglib and the new Spring Form Taglib both work in portlet views in exactly the same way that they work in servlet views. + + + [[portlet-multipart]] === Multipart (file upload) support Spring Portlet MVC has built-in multipart support to handle file uploads in portlet @@ -35252,6 +36842,8 @@ any other name, then the `DispatcherPortlet` will __not__ find your `PortletMultipartResolver`, and consequently no multipart support will be in effect. ==== + + [[portlet-multipart-resolver]] ==== Using the PortletMultipartResolver @@ -35284,6 +36876,8 @@ request and actually get access to the multipart files themselves in your contro Note that you can only receive multipart file uploads as part of an `ActionRequest`, not as part of a `RenderRequest`. + + [[portlet-multipart-forms]] ==== Handling a file upload in a form After the `PortletMultipartResolver` has finished doing its job, the request will be @@ -35480,6 +37074,9 @@ public class FileUploadBean { } ---- + + + [[portlet-exceptionresolver]] === Handling exceptions Just like Servlet MVC, Portlet MVC provides `HandlerExceptionResolver` s to ease the @@ -35488,6 +37085,9 @@ handler that matched the request. Portlet MVC also provides a portlet-specific, `SimpleMappingExceptionResolver` that enables you to take the class name of any exception that might be thrown and map it to a view name. + + + [[portlet-annotation]] === Annotation-based controller configuration Spring 2.5 introduced an annotation-based programming model for MVC controllers, using @@ -35501,6 +37101,8 @@ facilities if desired. The following sections document these annotations and how they are most commonly used in a Portlet environment. + + [[portlet-ann-setup]] ==== Setting up the dispatcher for annotation support __ `@RequestMapping` will only be processed if a corresponding `HandlerMapping` (for @@ -35535,6 +37137,8 @@ Defining a `DefaultAnnotationHandlerMapping` and/or `AnnotationMethodHandlerAdap explicitly also makes sense if you would like to customize the mapping strategy, e.g. specifying a custom `WebBindingInitializer` (see below). + + [[portlet-ann-controller]] ==== Defining a controller with @Controller @@ -35577,6 +37181,8 @@ schema as shown in the following XML snippet: ---- + + [[portlet-ann-requestmapping]] ==== Mapping requests with @RequestMapping @@ -35653,6 +37259,8 @@ public class PetSitesEditController { } ---- + + [[portlet-ann-requestmapping-arguments]] ==== Supported handler method arguments Handler methods which are annotated with `@RequestMapping` are allowed to have very @@ -35722,6 +37330,8 @@ The following return types are supported for handler methods: model will be implicitly enriched with command objects and the results of `@ModelAttribute` annotated reference data accessor methods. + + [[portlet-ann-requestparam]] ==== Binding request parameters to method parameters with @RequestParam @@ -35752,6 +37362,8 @@ Parameters using this annotation are required by default, but you can specify th parameter is optional by setting `@RequestParam`'s `required` attribute to `false` (e.g., `@RequestParam(value="id", required=false)`). + + [[portlet-ann-modelattrib]] ==== Providing a link to data from the model with @ModelAttribute @@ -35801,6 +37413,8 @@ public class PetSitesEditController { } ---- + + [[portlet-ann-sessionattrib]] ==== Specifying attributes to store in a Session with @SessionAttributes @@ -35822,6 +37436,8 @@ public class PetSitesEditController { } ---- + + [[portlet-ann-webdatabinder]] ==== Customizing WebDataBinder initialization @@ -35830,6 +37446,7 @@ To customize request parameter binding with PropertyEditors, etc. via Spring's controller or externalize your configuration by providing a custom `WebBindingInitializer`. + [[portlet-ann-initbinder]] ===== Customizing data binding with @InitBinder @@ -35864,6 +37481,7 @@ public class MyFormController { } ---- + [[portlet-ann-webbindinginitializer]] ===== Configuring a custom WebBindingInitializer @@ -35872,6 +37490,9 @@ the `WebBindingInitializer` interface, which you then enable by supplying a cust configuration for an `AnnotationMethodHandlerAdapter`, thus overriding the default configuration. + + + [[portlet-deployment]] === Portlet application deployment The process of deploying a Spring Portlet MVC application is no different than deploying @@ -35907,6 +37528,11 @@ Once you have deployed your portlet, review the resulting `web.xml` file for san Some older portals have been known to corrupt the definition of the `ViewRendererServlet`, thus breaking the rendering of your portlets. + + + + + [[spring-integration]] = Integration This part of the reference documentation covers the Spring Framework's integration with @@ -35922,9 +37548,16 @@ a number of Java EE (and related) technologies. * <> * <> + + + + [[remoting]] == Remoting and web services using Spring + + + [[remoting-introduction]] === Introduction Spring features integration classes for remoting support using various technologies. The @@ -36013,6 +37646,9 @@ We will start exposing the service to a remote client by using RMI and talk a bi the drawbacks of using RMI. We'll then continue to show an example using Hessian as the protocol. + + + [[remoting-rmi]] === Exposing services using RMI Using Spring's support for RMI, you can transparently expose your services through the @@ -36022,6 +37658,8 @@ context propagation or remote transaction propagation. Spring does provide hooks such additional invocation context when using the RMI invoker, so you can for example plug in security frameworks or custom security credentials here. + + [[remoting-rmi-server]] ==== Exporting the service using the RmiServiceExporter @@ -36067,6 +37705,8 @@ The `servicePort` property has been omitted (it defaults to 0). This means that anonymous port will be used to communicate with the service. ==== + + [[remoting-rmi-client]] ==== Linking in the service at the client Our client is a simple object using the `AccountService` to manage accounts: @@ -36107,11 +37747,16 @@ That's all we need to do to support the remote account service on the client. Sp will transparently create an invoker and remotely enable the account service through the `RmiServiceExporter`. At the client we're linking it in using the `RmiProxyFactoryBean`. + + + [[remoting-caucho-protocols]] === Using Hessian or Burlap to remotely call services via HTTP Hessian offers a binary HTTP-based remoting protocol. It is developed by Caucho and more information about Hessian itself can be found at http://www.caucho.com[]. + + [[remoting-caucho-protocols-hessian]] ==== Wiring up the DispatcherServlet for Hessian and co. @@ -36146,6 +37791,8 @@ default in `'WEB-INF/applicationContext.xml'`), with individual servlet definiti pointing to specific exporter beans. Each servlet name needs to match the bean name of its target exporter in this case. + + [[remoting-caucho-protocols-hessian-server]] ==== Exposing your beans by using the HessianServiceExporter @@ -36202,6 +37849,8 @@ the target exporter. ---- + + [[remoting-caucho-protocols-hessian-client]] ==== Linking in the service on the client Using the `HessianProxyFactoryBean` we can link in the service at the client. The same @@ -36222,12 +37871,16 @@ the `AccountService` to manage accounts: ---- + + [[remoting-caucho-protocols-burlap]] ==== Using Burlap We won't discuss Burlap, the XML-based equivalent of Hessian, in detail here, since it is configured and set up in exactly the same way as the Hessian variant explained above. Just replace the word `Hessian` with `Burlap` and you're all set to go. + + [[remoting-caucho-protocols-security]] ==== Applying HTTP basic authentication to a service exposed through Hessian or Burlap One of the advantages of Hessian and Burlap is that we can easily apply HTTP basic @@ -36261,6 +37914,9 @@ more options as far as security is concerned, have a look at the Spring Security at http://projects.spring.io/spring-security/[]. ==== + + + [[remoting-httpinvoker]] === Exposing services using HTTP invokers As opposed to Burlap and Hessian, which are both lightweight protocols using their own @@ -36276,6 +37932,8 @@ easy-to-use functionality. Refer to http://jakarta.apache.org/commons/httpclient[jakarta.apache.org/commons/httpclient] for more info. + + [[remoting-httpinvoker-server]] ==== Exposing the service object Setting up the HTTP invoker infrastructure for a service object resembles closely the @@ -36353,6 +38011,8 @@ shown in this example: ---- + + [[remoting-httpinvoker-client]] ==== Linking in the service at the client Again, linking in the service from the client much resembles the way you would do it @@ -36380,6 +38040,9 @@ As mentioned before, you can choose what HTTP client you want to use. By default ---- + + + [[remoting-web-services]] === Web services Spring provides full support for standard Java web services APIs: @@ -36392,6 +38055,8 @@ features http://www.springframework.org/spring-ws[Spring Web Services], a soluti contract-first, document-driven web services - highly recommended for building modern, future-proof web services. + + [[remoting-web-services-jaxws-export-servlet]] ==== Exposing servlet-based web services using JAX-WS Spring provides a convenient base class for JAX-WS servlet endpoint implementations - @@ -36444,6 +38109,8 @@ context to allow for access to Spring's facilities. This is the case by default EE 5 environments, using the standard contract for JAX-WS servlet endpoint deployment. See Java EE 5 web service tutorials for details. + + [[remoting-web-services-jaxws-export-standalone]] ==== Exporting standalone web services using JAX-WS The built-in JAX-WS provider that comes with Sun's JDK 1.6 supports exposure of web @@ -36498,6 +38165,8 @@ public class AccountServiceEndpoint { } ---- + + [[remoting-web-services-jaxws-export-ri]] ==== Exporting web services using the JAX-WS RI's Spring support Sun's JAX-WS RI, developed as part of the GlassFish project, ships Spring support as @@ -36518,6 +38187,8 @@ Check out https://jax-ws-commons.dev.java.net/spring/[https://jax-ws-commons.dev.java.net/spring/] for the details on setup and usage style. + + [[remoting-web-services-jaxws-access]] ==== Accessing web services using JAX-WS Spring provides two factory beans to create JAX-WS web service proxies, namely @@ -36581,6 +38252,9 @@ annotations. This means that you cannot (easily) use plain Java interfaces and implementation classes as JAX-WS endpoint artifacts; you need to annotate them accordingly first. Check the JAX-WS documentation for details on those requirements. + + + [[remoting-jms]] === JMS It is also possible to expose services transparently using JMS as the underlying @@ -36642,6 +38316,8 @@ the client and server. ---- + + [[remoting-jms-server]] ==== Server-side configuration On the server, you just need to expose the service object using the @@ -36689,6 +38365,8 @@ public class Server { } ---- + + [[remoting-jms-client]] ==== Client-side configuration The client merely needs to create a client-side proxy that will implement the agreed @@ -36739,11 +38417,17 @@ http://lingo.codehaus.org/[Lingo] project, which (to quote the homepage blurb) " a lightweight POJO based remoting and messaging library based on the Spring Framework's remoting libraries which extends it to support JMS.__" + + + [[remoting-amqp]] === AMQP Refer to the http://docs.spring.io/spring-amqp/reference/html/amqp.html#remoting[Spring AMQP Reference Document 'Spring Remoting with AMQP' section] for more information. + + + [[remoting-autodection-remote-interfaces]] === Auto-detection is not implemented for remote interfaces The main reason why auto-detection of implemented interfaces does not occur for remote @@ -36762,6 +38446,9 @@ This is a trade-off between configuration convenience and the risk of accidental exposure of internal methods. Always specifying a service interface is not too much effort, and puts you on the safe side regarding controlled exposure of specific methods. + + + [[remoting-considerations]] === Considerations when choosing a technology Each and every technology presented here has its drawbacks. You should carefully @@ -36798,6 +38485,9 @@ possible to get RMI invokers or HTTP invokers to support security context propag well, although this is not provided by core Spring: There are just appropriate hooks for plugging in third-party or custom solutions here. + + + [[rest-client-access]] === Accessing RESTful services on the Client The `RestTemplate` is the core class for client-side access to RESTful services. It is @@ -36813,6 +38503,8 @@ range of choices of XML to Object mapping technologies to choose from. This section describes how to use the `RestTemplate` and its associated `HttpMessageConverters`. + + [[rest-resttemplate]] ==== RestTemplate Invoking RESTful services in Java is typically done using a helper class such as Jakarta @@ -36996,6 +38688,7 @@ template will always close the request and handle any errors. Refer to the API documentation for more information on using the execute method and the meaning of its other method arguments. + [[rest-resttemplate-uri]] ===== Working with the URI For each of the main HTTP methods, the `RestTemplate` provides variants that either take @@ -37046,6 +38739,7 @@ UriComponents uriComponents = URI uri = uriComponents.toUri(); ---- + [[rest-template-headers]] ===== Dealing with request and response headers Besides the methods described above, the `RestTemplate` also has the `exchange()` @@ -37073,6 +38767,8 @@ In the above example, we first prepare a request entity that contains the `MyRequestHeader` header. We then retrieve the response, and read the `MyResponseHeader` and body. + + [[rest-message-conversion]] ==== HTTP Message Conversion Objects passed to and returned from the methods `getForObject()`, `postForLocation()`, @@ -37113,12 +38809,14 @@ The implementations of `HttpMessageConverter` s are described in the following s For all converters a default media type is used but can be overridden by setting the `supportedMediaTypes` bean property + [[rest-string-converter]] ===== StringHttpMessageConverter An `HttpMessageConverter` implementation that can read and write Strings from the HTTP request and response. By default, this converter supports all text media types ( `text/*`), and writes with a `Content-Type` of `text/plain`. + [[rest-form-converter]] ===== FormHttpMessageConverter An `HttpMessageConverter` implementation that can read and write form data from the HTTP @@ -37126,6 +38824,7 @@ request and response. By default, this converter reads and writes the media type `application/x-www-form-urlencoded`. Form data is read from and written into a `MultiValueMap`. + [[rest-byte-converter]] ===== ByteArrayHttpMessageConverter An `HttpMessageConverter` implementation that can read and write byte arrays from the @@ -37133,6 +38832,7 @@ HTTP request and response. By default, this converter supports all media types ( and writes with a `Content-Type` of `application/octet-stream`. This can be overridden by setting the `supportedMediaTypes` property, and overriding `getContentType(byte[])`. + [[rest-marhsalling-converter]] ===== MarshallingHttpMessageConverter An `HttpMessageConverter` implementation that can read and write XML using Spring's @@ -37141,6 +38841,7 @@ This converter requires a `Marshaller` and `Unmarshaller` before it can be used. can be injected via constructor or bean properties. By default this converter supports ( `text/xml`) and ( `application/xml`). + [[rest-mapping-json-converter]] ===== MappingJackson2HttpMessageConverter (or MappingJacksonHttpMessageConverter with Jackson 1.x) An `HttpMessageConverter` implementation that can read and write JSON using Jackson's @@ -37150,6 +38851,7 @@ injected through the `ObjectMapper` property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supports ( `application/json`). + [[rest-source-converter]] ===== SourceHttpMessageConverter An `HttpMessageConverter` implementation that can read and write @@ -37157,15 +38859,23 @@ An `HttpMessageConverter` implementation that can read and write `SAXSource`, and `StreamSource` are supported. By default, this converter supports ( `text/xml`) and ( `application/xml`). + [[rest-buffered-image-converter]] ===== BufferedImageHttpMessageConverter An `HttpMessageConverter` implementation that can read and write `java.awt.image.BufferedImage` from the HTTP request and response. This converter reads and writes the media type supported by the Java I/O API. + + + + [[ejb]] == Enterprise JavaBeans (EJB) integration + + + [[ejb-introduction]] === Introduction As a lightweight container, Spring is often considered an EJB replacement. We do believe @@ -37185,9 +38895,14 @@ In this chapter, we look at how Spring can help you access and implement EJBs. S provides particular value when accessing stateless session beans (SLSBs), so we'll begin by discussing this. + + + [[ejb-access]] === Accessing EJBs + + [[ejb-access-concepts]] ==== Concepts To invoke a method on a local or remote stateless session bean, client code must @@ -37214,6 +38929,8 @@ configured inside a Spring container, which act as codeless business delegates. not need to write another Service Locator, another JNDI lookup, or duplicate methods in a hand-coded Business Delegate unless you are actually adding real value in such code. + + [[ejb-access-local]] ==== Accessing local SLSBs Assume that we have a web controller that needs to use a local EJB. We'll follow best @@ -37320,6 +39037,8 @@ controlled via the `lazy-init` attribute. Although this will not be of interest to the majority of Spring users, those doing programmatic AOP work with EJBs may want to look at `LocalSlsbInvokerInterceptor`. + + [[ejb-access-remote]] ==== Accessing remote SLSBs Accessing remote EJBs is essentially identical to accessing local EJBs, except that the @@ -37348,6 +39067,8 @@ between a local EJB or remote EJB (or even plain Java object) implementation, wi the client code knowing or caring. Of course, this is optional; there is nothing stopping you from declaring `RemoteExceptions` in your business interface. + + [[ejb-access-ejb2-ejb3]] ==== Accessing EJB 2.x SLSBs versus EJB 3 SLSBs Accessing EJB 2.x Session Beans and EJB 3 Session Beans via Spring is largely @@ -37361,9 +39082,14 @@ Note: For EJB 3 Session Beans, you could effectively use a `JndiObjectFactoryBea plain JNDI lookups there. Defining explicit `` / `` lookups simply provides consistent and more explicit EJB access configuration. + + + [[ejb-implementation]] === Using Spring's EJB implementation support classes + + [[ejb-implementation-ejb3]] ==== EJB 3 injection interceptor For EJB 3 Session Beans and Message-Driven Beans, Spring provides a convenient @@ -37403,9 +39129,16 @@ through overriding the `getBeanFactoryLocatorKey` method in a custom Alternatively, consider overriding `SpringBeanAutowiringInterceptor`'s `getBeanFactory` method, e.g. obtaining a shared `ApplicationContext` from a custom holder class. + + + + [[jms]] == JMS (Java Message Service) + + + [[jms-introduction]] === Introduction Spring provides a JMS integration framework that simplifies the use of the JMS API much @@ -37446,9 +39179,14 @@ implementation of Spring's `PlatformTransactionManager` for JMS (the cunningly n `JmsTransactionManager`). This allows for seamless integration of JMS as a transactional resource into Spring's transaction management mechanisms. + + + [[jms-using]] === Using Spring JMS + + [[jms-jmstemplate]] ==== JmsTemplate @@ -37487,6 +39225,8 @@ clear, the `JmsTemplate` is stateful, in that it maintains a reference to a `ConnectionFactory`, but this state is __not__ conversational state. ==== + + [[jms-connections]] ==== Connections The `JmsTemplate` requires a reference to a `ConnectionFactory`. The `ConnectionFactory` @@ -37503,6 +39243,7 @@ the EJB or servlet deployment descriptors. To ensure the use of these features w `JmsTemplate` inside an EJB, the client application should ensure that it references the managed implementation of the `ConnectionFactory`. + [[jms-caching-resources]] ===== Caching Messaging Resources The standard API involves creating many intermediate objects. To send a message the @@ -37518,6 +39259,7 @@ Between the ConnectionFactory and the Send operation there are three intermediat objects that are created and destroyed. To optimise the resource usage and increase performance two implementations of IConnectionFactory are provided. + [[jms-connection-factory]] ===== SingleConnectionFactory Spring provides an implementation of the `ConnectionFactory` interface, @@ -37527,6 +39269,7 @@ standalone environments so that the same connection can be used for multiple `JmsTemplate` calls that may span any number of transactions. `SingleConnectionFactory` takes a reference to a standard `ConnectionFactory` that would typically come from JNDI. + [[jdbc-connection-factory-caching]] ===== CachingConnectionFactory The `CachingConnectionFactory` extends the functionality of `SingleConnectionFactory` @@ -37541,6 +39284,8 @@ consumers when caching. MessageProducers are cached based on their destination. MessageConsumers are cached based on a key composed of the destination, selector, noLocal delivery flag, and the durable subscription name (if creating durable consumers). + + [[jms-destinations]] ==== Destination Management Destinations, like ConnectionFactories, are JMS administered objects that can be stored @@ -37584,6 +39329,8 @@ You can also configure the `JmsTemplate` with a default destination via the prop `defaultDestination`. The default destination will be used with send and receive operations that do not refer to a specific destination. + + [[jms-mdp]] ==== Message Listener Containers One of the most common uses of JMS messages in the EJB world is to drive message-driven @@ -37604,6 +39351,7 @@ boilerplate JMS infrastructure concerns to the framework. There are two standard JMS message listener containers packaged with Spring, each with its specialised feature set. + [[jms-mdp-simple]] ===== SimpleMessageListenerContainer This message listener container is the simpler of the two standard flavors. It creates a @@ -37614,6 +39362,7 @@ to runtime demands or for participation in externally managed transactions. Compatibility-wise, it stays very close to the spirit of the standalone JMS specification - but is generally not compatible with Java EE's JMS restrictions. + [[jms-mdp-default]] ===== DefaultMessageListenerContainer This message listener container is the one used in most cases. In contrast to @@ -37625,6 +39374,8 @@ This listener container strikes a good balance between low requirements on the J provider, advanced functionality such as transaction participation, and compatibility with Java EE environments. + + [[jms-tx]] ==== Transaction management Spring provides a `JmsTransactionManager` that manages transactions for a single JMS @@ -37657,6 +39408,9 @@ properties `sessionTransacted` and `sessionAcknowledgeMode`. When using a `PlatformTransactionManager` with `JmsTemplate`, the template will always be given a transactional JMS `Session`. + + + [[jms-sending]] === Sending a Message @@ -37717,6 +39471,8 @@ you should set the `destinationResolver` property of the template to an instance If you created the `JmsTemplate` and specified a default destination, the `send(MessageCreator c)` sends a message to that destination. + + [[jms-msg-conversion]] ==== Using Message Converters In order to facilitate the sending of domain model objects, the `JmsTemplate` has @@ -37778,6 +39534,8 @@ MapMessage={ } ---- + + [[jms-callbacks]] ==== SessionCallback and ProducerCallback @@ -37787,9 +39545,14 @@ want to perform multiple operations on a JMS `Session` or `MessageProducer`. The `MessageProducer` pair respectively. The `execute()` methods on `JmsTemplate` execute these callback methods. + + + [[jms-receiving]] === Receiving a message + + [[jms-receiving-sync]] ==== Synchronous Reception While JMS is typically associated with asynchronous processing, it is possible to @@ -37799,6 +39562,8 @@ becomes available. This can be a dangerous operation since the calling thread ca potentially be blocked indefinitely. The property `receiveTimeout` specifies how long the receiver should wait before giving up waiting for a message. + + [[jms-asynchronousMessageReception]] ==== Asynchronous Reception - Message-Driven POJOs In a fashion similar to a Message-Driven Bean (MDB) in the EJB world, the Message-Driven @@ -37859,6 +39624,8 @@ containers that ships with Spring (in this case the `DefaultMessageListenerConta Please refer to the Spring Javadoc of the various message listener containers for a full description of the features supported by each implementation. + + [[jms-receiving-async-session-aware-message-listener]] ==== the SessionAwareMessageListener interface @@ -37892,6 +39659,8 @@ interface throws `JMSException`. In contrast to the standard JMS `MessageListene interface, when using the `SessionAwareMessageListener` interface, it is the responsibility of the client code to handle any exceptions thrown. + + [[jms-receiving-async-message-listener-adapter]] ==== the MessageListenerAdapter @@ -38025,6 +39794,8 @@ if no `Destination` is found then an `InvalidDestinationException` will be throw please note that this exception __will not__ be swallowed and __will__ propagate up the call stack). + + [[jms-tx-participation]] ==== Processing messages within transactions Invoking a message listener within a transaction only requires reconfiguration of the @@ -38082,6 +39853,9 @@ take care of the rest. ---- + + + [[jms-jca-message-endpoint-manager]] === Support for JCA Message Endpoints Beginning with version 2.5, Spring also provides support for a JCA-based @@ -38171,6 +39945,9 @@ simply because JMS is the most common endpoint API used with the JCA endpoint ma contract. ==== + + + [[jms-namespace]] === JMS Namespace Support Spring 2.5 introduces an XML namespace for simplifying JMS configuration. To use the JMS @@ -38429,9 +40206,16 @@ table: number might lead to starvation of concurrent consumers! |=== + + + + [[jmx]] == JMX + + + [[jmx-introduction]] === Introduction The JMX support in Spring provides you with the features to easily and transparently @@ -38456,6 +40240,9 @@ either Spring or JMX interfaces and classes. Indeed, for the most part your appl classes need not be aware of either Spring or JMX in order to take advantage of the Spring JMX features. + + + [[jmx-exporting]] === Exporting your beans to JMX The core class in Spring's JMX framework is the `MBeanExporter`. This class is @@ -38533,6 +40320,8 @@ With this configuration the `testBean` bean is exposed as an MBean under the are exposed as attributes and all __public__ methods (bar those inherited from the `Object` class) are exposed as operations. + + [[jmx-exporting-mbeanserver]] ==== Creating an MBeanServer @@ -38584,6 +40373,8 @@ supplied to the `MBeanExporter` via the server property. When you supply your ow `MBeanServer` and will use the supplied `MBeanServer` instance. For this to work correctly, you must (of course) have a JMX implementation on your classpath. + + [[jmx-mbean-server]] ==== Reusing an existing MBeanServer @@ -38630,6 +40421,8 @@ For platforms/cases where the existing `MBeanServer` has a dynamic (or unknown) ---- + + [[jmx-exporting-lazy]] ==== Lazy-initialized MBeans If you configure a bean with the `MBeanExporter` that is also configured for lazy @@ -38638,6 +40431,8 @@ instantiating the bean. Instead, it will register a proxy with the `MBeanServer` will defer obtaining the bean from the container until the first invocation on the proxy occurs. + + [[jmx-exporting-auto]] ==== Automatic registration of MBeans Any beans that are exported through the `MBeanExporter` and are already valid MBeans are @@ -38660,6 +40455,8 @@ automatically registered by Spring. By default, beans that are autodetected for registration have their bean name used as the `ObjectName`. This behavior can be overridden as detailed in <>. + + [[jmx-exporting-registration-behavior]] ==== Controlling the registration behavior Consider the scenario where a Spring `MBeanExporter` attempts to register an `MBean` @@ -38729,6 +40526,9 @@ behavior to the `REGISTRATION_REPLACE_EXISTING` behavior: ---- + + + [[jmx-interface]] === Controlling the management interface of your beans In the previous example, you had little control over the management interface of your @@ -38738,6 +40538,8 @@ exactly which properties and methods of your exported beans are actually exposed attributes and operations, Spring JMX provides a comprehensive and extensible mechanism for controlling the management interfaces of your beans. + + [[jmx-interface-assembler]] ==== the MBeanInfoAssembler Interface @@ -38751,6 +40553,8 @@ saw in the previous examples). Spring provides two additional implementations of `MBeanInfoAssembler` interface that allow you to control the generated management interface using either source-level metadata or any arbitrary interface. + + [[jmx-interface-metadata]] ==== Using Source-Level Metadata (JDK 5.0 annotations) Using the `MetadataMBeanInfoAssembler` you can define the management interfaces for your @@ -38881,6 +40685,8 @@ instance of the `AnnotationJmxAttributeSource` class and passed to the `MBeanExp through the assembler property. This is all that is required to take advantage of metadata-driven management interfaces for your Spring-exposed MBeans. + + [[jmx-interface-metadata-types]] ==== Source-Level Metadata Types The following source level metadata types are available for use in Spring JMX: @@ -38965,6 +40771,8 @@ metadata types: | `ManagedOperationParameter` |=== + + [[jmx-interface-autodetect]] ==== the AutodetectCapableMBeanInfoAssembler interface @@ -39011,6 +40819,8 @@ only problem with this approach is that the name of the `JmxTestBean` now has bu meaning. You can address this issue by changing the default behavior for `ObjectName` creation as defined in <>. + + [[jmx-interface-java]] ==== Defining management interfaces using Java interfaces In addition to the `MetadataMBeanInfoAssembler`, Spring also includes the @@ -39095,6 +40905,8 @@ If no management interface is specified through either the `managedInterfaces` o on the bean and use all of the interfaces implemented by that bean to create the management interface. + + [[jmx-interface-methodnames]] ==== Using MethodNameBasedMBeanInfoAssembler @@ -39128,6 +40940,9 @@ beans that are exposed to JMX. To control method exposure on a bean-by-bean basi the `methodMappings` property of `MethodNameMBeanInfoAssembler` to map bean names to lists of method names. + + + [[jmx-naming]] === Controlling the ObjectNames for your beans @@ -39141,6 +40956,8 @@ of the `beans` `Map` to an entry in a `Properties` file (or files) to resolve th `ObjectName` based on the JVM identity of the bean and the `MetadataNamingStrategy` that uses source level metadata to obtain the `ObjectName`. + + [[jmx-naming-properties]] ==== Reading ObjectNames from Properties @@ -39195,6 +41012,8 @@ bean key. If no entry in the `Properties` instance can be found then the bean key name is used as the `ObjectName`. + + [[jmx-naming-metadata]] ==== Using the MetadataNamingStrategy @@ -39243,6 +41062,8 @@ __com.foo:type=MyClass,name=myBean__. ---- + + [[jmx-context-mbeanexport]] ==== Configuring annotation based MBean export If you prefer using <> to define @@ -39304,12 +41125,17 @@ case: through setting the 'proxy-target-class' flag on ``, startup... ==== + + + [[jmx-jsr160]] === JSR-160 Connectors For remote access, Spring JMX module offers two `FactoryBean` implementations inside the `org.springframework.jmx.support` package for creating both server- and client-side connectors. + + [[jmx-jsr160-server]] ==== Server-side Connectors To have Spring JMX create, start and expose a JSR-160 `JMXConnectorServer` use the @@ -39379,6 +41205,8 @@ snippet of configuration: ---- + + [[jmx-jsr160-client]] ==== Client-side Connectors To create an `MBeanServerConnection` to a remote JSR-160 enabled `MBeanServer` use the @@ -39392,6 +41220,8 @@ To create an `MBeanServerConnection` to a remote JSR-160 enabled `MBeanServer` u ---- + + [[jmx-jsr160-protocols]] ==== JMX over Burlap/Hessian/SOAP JSR-160 permits extensions to the way in which communication is done between the client @@ -39413,6 +41243,9 @@ others: In the case of the above example, MX4J 3.0.0 was used; see the official MX4J documentation for more information. + + + [[jmx-proxy]] === Accessing MBeans via Proxies Spring JMX allows you to create proxies that re-route calls to MBeans registered in a @@ -39461,10 +41294,15 @@ passed to the `MBeanProxyFactoryBean` via the `server` property. The proxy that created will forward all invocations to the `MBeanServer` via this `MBeanServerConnection`. + + + [[jmx-notifications]] === Notifications Spring's JMX offering includes comprehensive support for JMX notifications. + + [[jmx-notifications-listeners]] ==== Registering Listeners for Notifications Spring's JMX support makes it very easy to register any number of @@ -39668,6 +41506,8 @@ specification (1.2) entitled 'The JMX Notification Model'.) ---- + + [[jmx-notifications-publishing]] ==== Publishing Notifications Spring provides support not just for registering to receive `Notifications`, but also @@ -39748,6 +41588,9 @@ coupling your classes to both Spring and JMX; as always, the advice here is to b pragmatic... if you need the functionality offered by the `NotificationPublisher` and you can accept the coupling to both Spring and JMX, then do so. + + + [[jmx-resources]] === Further Resources This section contains links to further resources about JMX. @@ -39762,9 +41605,16 @@ This section contains links to further resources about JMX. * http://java.sun.com/developer/technicalArticles/J2SE/jmx.html[Getting Started with JMX] - an introductory article from Sun. + + + + [[cci]] == JCA CCI + + + [[cci-introduction]] === Introduction Java EE provides a specification to standardize access to enterprise information systems @@ -39794,9 +41644,14 @@ container (connection pooling, global transactions, security). Spring does not o special support for such connector-specific APIs. ==== + + + [[cci-config]] === Configuring CCI + + [[cci-config-connector]] ==== Connector configuration The base resource to use JCA CCI is the `ConnectionFactory` interface. The connector @@ -39828,6 +41683,8 @@ current thread. The resource is simply not aware of any global Java EE transacti might be running. ==== + + [[cci-config-connectionfactory]] ==== ConnectionFactory configuration in Spring @@ -39870,6 +41727,8 @@ the corresponding implementation of the `ManagedConnectionFactory` interface for connector. This interface is part of the JCA SPI specification. ==== + + [[cci-config-cci-connections]] ==== Configuring CCI connections JCA CCI allow the developer to configure the connections to the EIS using the @@ -39925,6 +41784,8 @@ with the `ConnectionSpec` argument, otherwise the variant without argument. ---- + + [[cci-config-single-connection]] ==== Using a single CCI connection If you want to use a single CCI connection, Spring provides a further @@ -39962,9 +41823,14 @@ Use an intermediary `ConnectionSpecConnectionFactoryAdapter` that the `ConnectionSpec`. ==== + + + [[cci-using]] === Using Spring's CCI access support + + [[cci-record-creator]] ==== Record conversion One of the aims of the JCA CCI support is to provide convenient facilities for @@ -40034,6 +41900,8 @@ public class MyRecordExtractor implements RecordExtractor { } ---- + + [[cci-using-template]] ==== the CciTemplate @@ -40130,6 +41998,8 @@ public class CciTemplate implements CciOperations { } ---- + + [[cci-using-dao]] ==== DAO support Spring's CCI support provides a abstract class for DAOs, supporting injection of a @@ -40152,6 +42022,8 @@ public abstract class CciDaoSupport { } ---- + + [[automatic-output-generation]] ==== Automatic output record generation If the connector used only supports the `Interaction.execute(..)` method with input and @@ -40192,6 +42064,8 @@ As the `CciTemplate` class is thread-safe, it will usually be configured as a sh instance. ==== + + [[template-summary]] ==== Summary The following table summarizes the mechanisms of the `CciTemplate` class and the @@ -40244,6 +42118,8 @@ corresponding methods called on the CCI `Interaction` interface: | void execute(InteractionSpec, Record, Record) |=== + + [[cci-straight]] ==== Using a CCI Connection and Interaction directly @@ -40286,6 +42162,8 @@ public interface InteractionCallback { created inside every callback method. This is completely up to the DAO implementation. ==== + + [[cci-template-example]] ==== Example for CciTemplate usage @@ -40427,6 +42305,9 @@ follows: ---- + + + [[cci-object]] === Modeling CCI access as operation objects The `org.springframework.jca.cci.object` package contains support classes that allow you @@ -40440,6 +42321,8 @@ __Note__: This approach is internally based on the `CciTemplate` class and the `RecordCreator` / `RecordExtractor` interfaces, reusing the machinery of Spring's core CCI support. + + [[cci-object-mapping-record]] ==== MappingRecordOperation @@ -40495,6 +42378,8 @@ MyMappingRecordOperation eisOperation = new MyMappingRecordOperation(getConnecti ... ---- + + [[cci-object-mapping-comm-area]] ==== MappingCommAreaOperation @@ -40520,6 +42405,8 @@ public abstract class MappingCommAreaOperation extends MappingRecordOperation { } ---- + + [[cci-automatic-record-gen]] ==== Automatic output record generation As every `MappingRecordOperation` subclass is based on CciTemplate internally, the same @@ -40527,6 +42414,8 @@ way to automatically generate output records as with `CciTemplate` is available. operation object provides a corresponding `setOutputRecordCreator(..)` method. For further information, see <>. + + [[cci-object-summary]] ==== Summary The operation object approach uses records in the same manner as the `CciTemplate` class. @@ -40546,6 +42435,8 @@ The operation object approach uses records in the same manner as the `CciTemplat | boolean execute(InteractionSpec, Record, Record) |=== + + [[cci-objects-mappring-record-example]] ==== Example for MappingRecordOperation usage @@ -40671,6 +42562,8 @@ follows: ---- + + [[cci-objects-mapping-comm-area-example]] ==== Example for MappingCommAreaOperation usage @@ -40765,6 +42658,9 @@ follows: ---- + + + [[cci-tx]] === Transactions JCA specifies several levels of transaction support for resource adapters. The kind of @@ -40820,9 +42716,16 @@ the actual execution strategy. Simply switch between `JtaTransactionManager` and For more information on Spring's transaction facilities, see the chapter entitled <>. + + + + [[mail]] == Email + + + [[mail-introduction]] === Introduction @@ -40857,6 +42760,9 @@ which it inherits). `JavaMailSender` also provides a callback interface for prep of JavaMail MIME messages, called `org.springframework.mail.javamail.MimeMessagePreparator` + + + [[mail-usage]] === Usage Let's assume there is a business interface called `OrderManager`: @@ -40873,6 +42779,8 @@ public interface OrderManager { Let us also assume that there is a requirement stating that an email message with an order number needs to be generated and sent to a customer placing the relevant order. + + [[mail-usage-simple]] ==== Basic MailSender and SimpleMailMessage usage @@ -40942,6 +42850,8 @@ Find below the bean definitions for the above code: ---- + + [[mail-usage-mime]] ==== Using the JavaMailSender and the MimeMessagePreparator @@ -41011,6 +42921,9 @@ joinpoints on the `OrderManager` target. The Spring Framework's mail support ships with the standard JavaMail implementation. Please refer to the relevant JavaDocs for more information. + + + [[mail-javamail-mime]] === Using the JavaMail MimeMessageHelper @@ -41034,12 +42947,15 @@ helper.setText("Thank you for ordering!"); sender.send(message); ---- + + [[mail-javamail-mime-attachments]] ==== Sending attachments and inline resources Multipart email messages allow for both attachments and inline resources. Examples of inline resources would be images or a stylesheet you want to use in your message, but that you don't want displayed as an attachment. + [[mail-javamail-mime-attachments-attachment]] ===== Attachments The following example shows you how to use the `MimeMessageHelper` to send an email @@ -41066,6 +42982,7 @@ helper.addAttachment("CoolImage.jpg", file); sender.send(message); ---- + [[mail-javamail-mime-attachments-inline]] ===== Inline resources The following example shows you how to use the `MimeMessageHelper` to send an email @@ -41102,6 +43019,8 @@ the resource are __very__ important. Be sure to __first add the text__ and after the resources. If you are doing it the other way around, it won't work! ==== + + [[mail-templates]] ==== Creating email content using a templating library The code in the previous examples explicitly created the content of the email message, @@ -41125,6 +43044,7 @@ your emails becomes even moderately complex, and with the Spring Framework's sup classes for FreeMarker and Velocity becomes quite easy to do. Find below an example of using the Velocity template library to create email content. + [[mail-templates-example]] ===== A Velocity-based example To use http://velocity.apache.org[Velocity] to create your email template(s), you will @@ -41236,9 +43156,16 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans ---- + + + + [[scheduling]] == Task Execution and Scheduling + + + [[scheduling-introduction]] === Introduction The Spring Framework provides abstractions for asynchronous execution and scheduling of @@ -41256,6 +43183,9 @@ the Quartz Scheduler and the `Timer` is available that allows you to invoke a me an existing target object (analogous to the normal `MethodInvokingFactoryBean` operation). + + + [[scheduling-task-executor]] === The Spring TaskExecutor abstraction @@ -41277,6 +43207,8 @@ JMS's `AbstractMessageListenerContainer`, and Quartz integration all use the `TaskExecutor` abstraction to pool threads. However, if your beans need thread pooling behavior, it is possible to use this abstraction for your own needs. + + [[scheduling-task-executor-types]] ==== TaskExecutor types @@ -41341,6 +43273,8 @@ context. Similar to the <>, this class implements the WorkManager interface and therefore can be used directly as a WorkManager as well. + + [[scheduling-task-executor-usage]] ==== Using a TaskExecutor @@ -41404,6 +43338,9 @@ been exposed. ---- + + + [[scheduling-task-scheduler]] === The Spring TaskScheduler abstraction @@ -41436,6 +43373,8 @@ are capable of scheduling tasks to run repeatedly. The fixed-rate and fixed-dela methods are for simple, periodic execution, but the method that accepts a Trigger is much more flexible. + + [[scheduling-trigger-interface]] ==== the Trigger interface @@ -41475,6 +43414,8 @@ public interface TriggerContext { } ---- + + [[scheduling-trigger-implementations]] ==== Trigger implementations @@ -41500,6 +43441,8 @@ cron-based triggers, and even custom trigger implementations to be used intercha Such a component could take advantage of dependency injection so that such `Triggers` could be configured externally. + + [[scheduling-task-scheduler-implementations]] ==== TaskScheduler implementations @@ -41518,11 +43461,16 @@ Spring's `TaskExecutor` interface as well, so that a single instance can be used asynchronous execution __as soon as possible__ as well as scheduled, and potentially recurring, executions. + + + [[scheduling-annotation-support]] === Annotation Support for Scheduling and Asynchronous Execution Spring provides annotation support for both task scheduling and asynchronous method execution. + + [[scheduling-enable-annotation-support]] ==== Enable scheduling annotations To enable support for `@Scheduled` and `@Async` annotations add `@EnableScheduling` and @@ -41557,6 +43505,8 @@ Notice with the above XML that an executor reference is provided for handling th tasks that correspond to methods with the `@Async` annotation, and the scheduler reference is provided for managing those methods annotated with `@Scheduled`. + + [[scheduling-annotation-support-scheduled]] ==== The @Scheduled Annotation The @Scheduled annotation can be added to a method along with trigger metadata. For @@ -41625,6 +43575,8 @@ once through the @Configurable aspect, with the consequence of each @Scheduled m being invoked twice. ==== + + [[scheduling-annotation-support-async]] ==== The @Async Annotation The `@Async` annotation can be provided on a method so that invocation of that method @@ -41699,6 +43651,8 @@ public class SampleBeanInititalizer { } ---- + + [[scheduling-annotation-support-qualification]] ==== Executor qualification with @Async By default when specifying `@Async` on a method, the executor that will be used is the @@ -41719,12 +43673,17 @@ In this case, "otherExecutor" may be the name of any `Executor` bean in the Spri container, or may be the name of a __qualifier__ associated with any `Executor`, e.g. as specified with the `` element or Spring's `@Qualifier` annotation. + + + [[scheduling-task-namespace]] === The Task Namespace Beginning with Spring 3.0, there is an XML namespace for configuring `TaskExecutor` and `TaskScheduler` instances. It also provides a convenient way to configure tasks to be scheduled with a trigger. + + [[scheduling-task-namespace-scheduler]] ==== The 'scheduler' element The following element will create a `ThreadPoolTaskScheduler` instance with the @@ -41741,6 +43700,8 @@ within the pool. The 'scheduler' element is relatively straightforward. If you d provide a 'pool-size' attribute, the default thread pool will only have a single thread. There are no other configuration options for the scheduler. + + [[scheduling-task-namespace-executor]] ==== The 'executor' element The following will create a `ThreadPoolTaskExecutor` instance: @@ -41816,6 +43777,8 @@ element. rejection-policy="CALLER_RUNS"/> ---- + + [[scheduling-task-namespace-scheduled-tasks]] ==== The 'scheduled-tasks' element The most powerful feature of Spring's task namespace is the support for configuring @@ -41857,6 +43820,9 @@ provided instead. Here is an example demonstrating these other options. ---- + + + [[scheduling-quartz]] === Using the Quartz Scheduler Quartz uses `Trigger`, `Job` and `JobDetail` objects to realize scheduling of all kinds @@ -41864,6 +43830,8 @@ of jobs. For the basic concepts behind Quartz, have a look at http://quartz-scheduler.org[]. For convenience purposes, Spring offers a couple of classes that simplify the usage of Quartz within Spring-based applications. + + [[scheduling-quartz-jobdetail]] ==== Using the JobDetailBean `JobDetail` objects contain all information needed to run a job. The Spring Framework @@ -41919,6 +43887,8 @@ __Note: Using the `name` and `group` properties, you can modify the name and the of the job, respectively. By default, the name of the job matches the bean name of the job detail bean (in the example above, this is `exampleJob`).__ + + [[scheduling-quartz-method-invoking-job]] ==== Using the MethodInvokingJobDetailFactoryBean @@ -41983,6 +43953,8 @@ job will not start before the first one has finished. To make jobs resulting fro By default, jobs will run in a concurrent fashion. ==== + + [[scheduling-quartz-cron]] ==== Wiring up jobs using triggers and the SchedulerFactoryBean @@ -42041,9 +44013,16 @@ at the http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/quartz/SchedulerFactoryBean.html[SchedulerFactoryBean Javadoc] for more information. + + + + [[dynamic-language]] == Dynamic language support + + + [[dynamic-language-introduction]] === Introduction .Why only these languages? @@ -42079,6 +44058,9 @@ __Note:__ Only the specific versions as listed above are supported in Spring 2.5 particular, JRuby 1.1 (which introduced many incompatible API changes) is __not__ supported at this point of time. + + + [[dynamic-language-a-first-example]] === A first example This bulk of this chapter is concerned with describing the dynamic language support in @@ -42191,6 +44173,9 @@ Hopefully the above XML snippet is self-explanatory, but don't worry unduly if i Keep reading for the in-depth detail on the whys and wherefores of the above configuration. + + + [[dynamic-language-beans]] === Defining beans that are backed by dynamic languages This section describes exactly how you define Spring managed beans in any of the @@ -42202,6 +44187,8 @@ the classes in your application, then the assumption is that you already know Gr you need further details about the dynamic languages themselves, please consult<> at the end of this chapter. + + [[dynamic-language-beans-concepts]] ==== Common concepts The steps involved in using dynamic-language-backed beans are as follows: @@ -42223,6 +44210,7 @@ source files. You __will__ first want to read the rest of this chapter though, a Spring's dynamic language support does make some (small) assumptions about the contents of your dynamic language source files. + [[dynamic-language-beans-concepts-xml-language-element]] ===== The element @@ -42254,6 +44242,7 @@ The exact attributes and child elements that are available for configuration dep exactly which language the bean has been defined in (the language-specific sections below provide the full lowdown on this). + [[dynamic-language-refreshable-beans]] ===== Refreshable beans One of the (if not __the__) most compelling value adds of the dynamic language support @@ -42388,6 +44377,7 @@ changes to the underlying source file can actually be detected; for example, by that checks the last modified date of a dynamic language source file that exists on the filesystem. + [[dynamic-language-beans-inline]] ===== Inline dynamic language source files The dynamic language support can also cater for dynamic language source files that are @@ -42451,6 +44441,7 @@ end ---- + [[dynamic-language-beans-ctor-injection]] ===== Understanding Constructor Injection in the context of dynamic-language-backed beans There is one __very__ important thing to be aware of with regard to Spring's dynamic @@ -42502,6 +44493,8 @@ In practice this limitation is not as significant as it first appears since sett injection is the injection style favored by the overwhelming majority of developers anyway (let's leave the discussion as to whether that is a good thing to another day). + + [[dynamic-language-beans-jruby]] ==== JRuby beans @@ -42628,6 +44621,8 @@ configure). See <> for some scenarios where you might want to use JRuby-based beans. + + [[dynamic-language-beans-groovy]] ==== Groovy beans @@ -42718,6 +44713,7 @@ While this is perfectly legal in Groovy, it is (arguably) a bad practice: in the interests of a consistent approach, you should (in the opinion of this author) respect the standard Java conventions of one (public) class per source file. + [[dynamic-language-beans-groovy-customizer]] ===== Customising Groovy objects via a callback The `GroovyObjectCustomizer` interface is a callback that allows you to hook additional @@ -42793,6 +44789,8 @@ If you are not using the Spring 2.0 namespace support, you can still use the ---- + + [[dynamic-language-beans-bsh]] ==== BeanShell beans @@ -42869,12 +44867,17 @@ term is used very loosely here). See <> for some scenarios where you might want to use BeanShell-based beans. + + + [[dynamic-language-scenarios]] === Scenarios The possible scenarios where defining Spring managed beans in a scripting language would be beneficial are, of course, many and varied. This section describes two possible use cases for the dynamic language support in Spring. + + [[dynamic-language-scenarios-controllers]] ==== Scripted Spring MVC Controllers One group of classes that may benefit from using dynamic-language-backed beans is that @@ -42940,6 +44943,8 @@ class FortuneController implements Controller { ---- + + [[dynamic-language-scenarios-validators]] ==== Scripted Validators Another area of application development with Spring that may benefit from the @@ -42986,10 +44991,15 @@ class TestBeanValidator implements Validator { } ---- + + + [[dynamic-language-final-notes]] === Bits and bobs This last section contains some bits and bobs related to the dynamic language support. + + [[dynamic-language-final-notes-aop]] ==== AOP - advising scripted beans It is possible to use the Spring AOP framework to advise scripted beans. The Spring AOP @@ -43004,6 +45014,8 @@ aspects themselves in a supported dynamic language and use such beans to advise Spring beans. This really would be an advanced use of the dynamic language support though. + + [[dynamic-language-final-notes-scopes]] ==== Scoping In case it is not immediately obvious, scripted beans can of course be scoped just like @@ -43039,6 +45051,9 @@ http://www.springframework.org/schema/lang http://www.springframework.org/schema See <> in <> for a fuller discussion of the scoping support in the Spring Framework. + + + [[dynamic-language-resources]] === Further Resources Find below links to further resources about the various dynamic languages described in @@ -43055,9 +45070,16 @@ list of languages supported by the main Spring distribution, your best bet for s your favourite scripting language is supported is the https://springmodules.dev.java.net/[Spring Modules project]. + + + + [[cache]] == Cache Abstraction + + + [[cache-introduction]] === Introduction Since version 3.1, Spring Framework provides support for transparently adding caching @@ -43065,6 +45087,9 @@ into an existing Spring application. Similar to the <> the caching abstraction allows consistent use of various caching solutions with minimal impact on the code. + + + [[cache-strategies]] === Understanding the cache abstraction .Cache vs Buffer @@ -43118,12 +45143,17 @@ available out of the box, for JDK `java.util.concurrent.ConcurrentMap` and http://ehcache.org/[EhCache] - see <> for more information on plugging in other cache stores/providers. + + + [[cache-annotations]] === Declarative annotation-based caching For caching declaration, the abstraction provides two Java annotations: `@Cacheable` and `@CacheEvict` which allow methods to trigger cache population or cache eviction. Let us take a closer look at each annotation: + + [[cache-annotations-cacheable]] ==== @Cacheable annotation @@ -43161,6 +45191,7 @@ the cached method was not actually executed. public Book findBook(ISBN isbn) {...} ---- + [[cache-annotations-cacheable-default-key]] ===== Default Key Generation Since caches are essentially key-value stores, each invocation of a cached method needs @@ -43182,6 +45213,7 @@ To provide a different __default__ key generator, one needs to implement the be used for each declaration that does not specify its own key generation strategy (see below). + [[cache-annotations-cacheable-key]] ===== Custom Key Generation Declaration Since caching is generic, it is quite likely the target methods have various signatures @@ -43228,6 +45260,7 @@ public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed) The snippets above, show how easy it is to select a certain argument, one of its properties or even an arbitrary (static) method. + [[cache-annotations-cacheable-condition]] ===== Conditional caching Sometimes, a method might not be suitable for caching all the time (for example, it @@ -43257,6 +45290,7 @@ perhaps we only want to cache paperback books: public Book findBook(String name) ---- + [[cache-spel-context]] ===== Available caching SpEL evaluation context @@ -43315,6 +45349,8 @@ conditional(see next section) computations: | `#result` |=== + + [[cache-annotations-put]] ==== @CachePut annotation @@ -43331,6 +45367,8 @@ execute a cache update. This leads to unexpected behavior and with the exception specific corner-cases (such as annotations having conditions that exclude them from each other), such declarations should be avoided. + + [[cache-annotations-evict]] ==== @CacheEvict annotation @@ -43370,6 +45408,8 @@ methods act as triggers, the return values are ignored (as they don't interact w cache) - this is not the case with `@Cacheable` which adds/update data into the cache and thus requires a result. + + [[cache-annotations-caching]] ==== @Caching annotation @@ -43387,6 +45427,8 @@ this case, `@Caching`. `@Caching` allows multiple nested `@Cacheable`, `@CachePu public Book importBooks(String deposit, Date date) ---- + + [[cache-annotation-enable]] ==== Enable caching annotations It is important to note that even though declaring the cache annotations does not @@ -43508,6 +45550,8 @@ caching at runtime even if the invoked method is marked with `@Cacheable` - cons using the aspectj mode in this case. ==== + + [[cache-annotation-stereotype]] ==== Using custom annotations The caching abstraction allows one to use her own annotations to identify what method @@ -43553,6 +45597,9 @@ Even though `@SlowService` is not a Spring annotation, the container automatical up its declaration at runtime and understands its meaning. Note that as mentioned <>, the annotation-driven behavior needs to be enabled. + + + [[cache-declarative-xml]] === Declarative XML-based caching If annotations are not an option (no access to the sources or no external code), one can @@ -43605,6 +45652,9 @@ caching (again due to the AspectJ pointcut) and to create template-like definiti we did in the example above by defining the target cache through the `cache:definitions` `cache` attribute). + + + [[cache-store-configuration]] === Configuring the cache storage Out of the box, the cache abstraction provides integration with two storages - one on @@ -43612,6 +45662,8 @@ top of the JDK `ConcurrentMap` and one for http://ehcache.org/[EhCache] library. them, one needs to simply declare an appropriate `CacheManager` - an entity that controls and manages `Cache` s and can be used to retrieve these for storage. + + [[cache-store-configuration-jdk]] ==== JDK ConcurrentMap-based Cache @@ -43642,6 +45694,8 @@ suitable for basic use cases, tests or simple applications. The cache scales wel very fast but it does not provide any management or persistence capabilities nor eviction contracts. + + [[cache-store-configuration-ehcache]] ==== EhCache-based Cache @@ -43661,6 +45715,8 @@ This setup bootstraps ehcache library inside Spring IoC (through bean `ehcache`) is then wired into the dedicated `CacheManager` implementation. Note the entire ehcache-specific configuration is read from the resource `ehcache.xml`. + + [[cache-store-configuration-gemfire]] ==== GemFire-based Cache @@ -43671,6 +45727,8 @@ GemFire as a CacheManager (and more), please refer to the http://docs.spring.io/spring-gemfire/docs/current/reference/htmlsingle/[Spring GemFire reference documentation]. + + [[cache-store-configuration-noop]] ==== Dealing with caches without a backing store Sometimes when switching environments or doing testing, one might have cache @@ -43701,6 +45759,9 @@ definition not found in either `jdkCache` or `gemfireCache` (configured above) w handled by the no op cache, which will not store any information causing the target method to be executed every time. + + + [[cache-plug]] === Plugging-in different back-end caches Clearly there are plenty of caching products out there that can be used as a backing @@ -43714,6 +45775,9 @@ package, such as `AbstractCacheManager` which takes care of the boiler-plate cod leaving only the actual __mapping__ to be completed. We hope that in time, the libraries that provide integration with Spring can fill in this small configuration gap. + + + [[cache-specific-config]] === How can I set the TTL/TTI/Eviction policy/XXX feature? Directly through your cache provider. The cache abstraction is... well, an abstraction @@ -43723,9 +45787,18 @@ policies and different topologies which other solutions do not (take for example because there would no backing support. Such functionality should be controlled directly through the backing cache, when configuring it or through its native API. + + + + + [[spring-appendices]] = Appendices + + + + [[classic-spring]] == Classic Spring Usage This appendix discusses some classic Spring usage patterns as a reference for developers @@ -43733,16 +45806,22 @@ maintaining legacy Spring applications. These usage patterns no longer reflect t recommended way of using these features and the current recommended usage is covered in the respective sections of the reference manual. + + + [[classic-spring-orm]] === Classic ORM usage This section documents the classic usage patterns that you might encounter in a legacy Spring application. For the currently recommended usage patterns, please refer to the <> chapter. + + [[classic-spring-hibernate]] ==== Hibernate For the currently recommended usage patterns for Hibernate see <> + [[orm-hibernate-template]] ===== the HibernateTemplate @@ -43839,6 +45918,7 @@ public class ProductDaoImpl extends HibernateDaoSupport implements ProductDao { } ---- + [[orm-hibernate-daos]] ===== Implementing Spring-based DAOs without callbacks As alternative to using Spring's `HibernateTemplate` to implement DAOs, data access code @@ -43883,10 +45963,13 @@ throwing of application exceptions to after the callback, which still allows wor with `HibernateTemplate`. In general, the `HibernateTemplate` class' convenience methods are simpler and more convenient for many scenarios. + + [[classic-spring-jdo]] ==== JDO For the currently recommended usage patterns for JDO see <> + [[orm-jdo-template]] ===== JdoTemplate and `JdoDaoSupport` @@ -43963,10 +46046,13 @@ is that your data access code is able to throw checked exceptions. `JdoDaoSuppor offers a variety of support methods for this scenario, for fetching and releasing a transactional `PersistenceManager` as well as for converting exceptions. + + [[classic-spring-jpa]] ==== JPA For the currently recommended usage patterns for JPA see <> + [[orm-jpa-template]] ===== JpaTemplate and `JpaDaoSupport` @@ -44046,10 +46132,16 @@ support methods for this scenario, for retrieving and releasing a transaction __JpaTemplate mainly exists as a sibling of JdoTemplate and HibernateTemplate, offering the same style for people used to it.__ + + + [[clasic-spring-mvc]] === Classic Spring MVC ... + + + [[classic-spring-jms]] === JMS Usage @@ -44082,6 +46174,8 @@ in widespread use (such as BEA WebLogic 8.1 and IBM WebSphere 5.1) are based on ==== **** + + [[classic-spring-jms-template]] ==== JmsTemplate Located in the package `org.springframework.jms.core` the class `JmsTemplate102` @@ -44092,6 +46186,8 @@ the `JmsTemplate` with knowledge of what JMS domain is being used. By default th of this property is false, indicating that the point-to-point domain, Queues, will be used. + + [[classic-spring-aysnc-messages]] ==== Asynchronous Message Reception <> are used in @@ -44102,6 +46198,8 @@ you are using the JMS 1.0.2 API, you will want to use the 1.0.2 specific classes `DefaultMessageListenerContainer102`. These classes provide the same functionality as the JMS 1.1 based counterparts but rely only on the JMS 1.0.2 API. + + [[classic-spring-jms-connections]] ==== Connections The `ConnectionFactory` interface is part of the JMS specification and serves as the @@ -44112,6 +46210,8 @@ calls to `close()`. You will need to set the boolean property `pubSubDomain` to which messaging domain is used as `SingleConnectionFactory102` will always explicitly differentiate between a `javax.jms.QueueConnection` and a `javax.jmsTopicConnection`. + + [[classic-spring-jms-tx-management]] ==== Transaction Management In a JMS 1.0.2 environment the class `JmsTransactionManager102` provides support for @@ -44119,6 +46219,10 @@ managing JMS transactions for a single Connection Factory. Please refer to the r documentation on <> for more information on this functionality. + + + + [[classic-aop-spring]] == Classic Spring AOP Usage In this appendix we discuss the lower-level Spring AOP APIs and the AOP support used in @@ -44128,10 +46232,15 @@ applications, or when reading books and articles, you may come across Spring 1.2 examples. Spring 2.0 is fully backwards compatible with Spring 1.2 and everything described in this appendix is fully supported in Spring 2.0. + + + [[classic-aop-api-pointcuts]] === Pointcut API in Spring Let's look at how Spring handles the crucial pointcut concept. + + [[classic-aop-api-concepts]] ==== Concepts Spring's pointcut model enables pointcut reuse independent of advice types. It's @@ -44203,6 +46312,8 @@ If possible, try to make pointcuts static, allowing the AOP framework to cache t results of pointcut evaluation when an AOP proxy is created. ==== + + [[classic-aop-api-pointcut-ops]] ==== Operations on pointcuts Spring supports operations on pointcuts: notably, __union__ and __intersection__. @@ -44215,6 +46326,8 @@ Spring supports operations on pointcuts: notably, __union__ and __intersection__ __ComposablePointcut__ class in the same package. However, using AspectJ pointcut expressions is usually a simpler approach. + + [[classic-aop-api-pointcuts-aspectj]] ==== AspectJ expression pointcuts Since 2.0, the most important type of pointcut used by Spring is @@ -44223,11 +46336,14 @@ uses an AspectJ supplied library to parse an AspectJ pointcut expression string. See the previous chapter for a discussion of supported AspectJ pointcut primitives. + + [[classic-aop-api-pointcuts-impls]] ==== Convenience pointcut implementations Spring provides several convenient pointcut implementations. Some can be used out of the box; others are intended to be subclassed in application-specific pointcuts. + [[classic-aop-api-pointcuts-static]] ===== Static pointcuts Static pointcuts are based on method and target class, and cannot take into account the @@ -44298,6 +46414,7 @@ __RegexpMethodPointcutAdvisor__ can be used with any Advice type. An important type of static pointcut is a __metadata-driven__ pointcut. This uses the values of metadata attributes: typically, source-level metadata. + [[classic-aop-api-pointcuts-dynamic]] ===== Dynamic pointcuts Dynamic pointcuts are costlier to evaluate than static pointcuts. They take into account @@ -44322,6 +46439,8 @@ other dynamic pointcuts. In Java 1.4, the cost is about 5 times that of other dy pointcuts. ==== + + [[classic-aop-api-pointcuts-superclasses]] ==== Pointcut superclasses Spring provides useful pointcut superclasses to help you to implement your own pointcuts. @@ -44345,6 +46464,8 @@ There are also superclasses for dynamic pointcuts. You can use custom pointcuts with any advice type in Spring 1.0 RC2 and above. + + [[classic-aop-api-pointcuts-custom]] ==== Custom pointcuts Because pointcuts in Spring AOP are Java classes, rather than language features (as in @@ -44358,10 +46479,15 @@ Later versions of Spring may offer support for "semantic pointcuts" as offered b for example, "all methods that change instance variables in the target object." ==== + + + [[classic-aop-api-advice]] === Advice API in Spring Let's now look at how Spring AOP handles advice. + + [[classic-aop-api-advice-lifecycle]] ==== Advice lifecycles Each advice is a Spring bean. An advice instance can be shared across all advised @@ -44377,11 +46503,14 @@ the advice adds state to the proxied object. It's possible to use a mix of shared and per-instance advice in the same AOP proxy. + + [[classic-aop-api-advice-types]] ==== Advice types in Spring Spring provides several advice types out of the box, and is extensible to support arbitrary advice types. Let us look at the basic concepts and standard advice types. + [[classic-aop-api-advice-around]] ===== Interception around advice The most fundamental advice type in Spring is __interception around advice__. @@ -44437,6 +46566,7 @@ are not currently interoperable between frameworks, and the AOP Alliance does no currently define pointcut interfaces. ==== + [[classic-aop-api-advice-before]] ===== Before advice A simpler advice type is a __before advice__. This does not need a `MethodInvocation` @@ -44491,6 +46621,7 @@ public class CountingBeforeAdvice implements MethodBeforeAdvice { Before advice can be used with any pointcut. ==== + [[classic-aop-api-advice-throws]] ===== Throws advice __Throws advice__ is invoked after the return of the join point if the join point threw @@ -44570,6 +46701,7 @@ exception that is incompatible with the target method's signature!__ Throws advice can be used with any pointcut. ==== + [[classic-aop-api-advice-after-returning]] ===== After Returning advice An after returning advice in Spring must implement the @@ -44618,6 +46750,7 @@ thrown up the interceptor chain instead of the return value. After returning advice can be used with any pointcut. ==== + [[classic-aop-api-advice-introduction]] ===== Introduction advice Spring treats introduction advice as a special kind of interception advice. @@ -44777,6 +46910,9 @@ We can apply this advisor programmatically, using the `Advised.addAdvisor()` met choices discussed below, including "auto proxy creators," correctly handle introductions and stateful mixins. + + + [[classic-aop-api-advisor]] === Advisor API in Spring In Spring, an Advisor is an aspect that contains just a single advice object associated @@ -44792,6 +46928,9 @@ example, you could use a interception around advice, throws advice and before ad one proxy configuration: Spring will automatically create the necessary interceptor chain. + + + [[classic-aop-pfb]] === Using the ProxyFactoryBean to create AOP proxies If you're using the Spring IoC container (an ApplicationContext or BeanFactory) for your @@ -44809,6 +46948,8 @@ __org.springframework.aop.framework.ProxyFactoryBean__. This gives complete cont the pointcuts and advice that will apply, and their ordering. However, there are simpler options that are preferable if you don't need such control. + + [[classic-aop-pfb-1]] ==== Basics The `ProxyFactoryBean`, like other Spring `FactoryBean` implementations, introduces a @@ -44824,6 +46965,8 @@ achieve with other AOP frameworks. For example, an advice may itself reference application objects (besides the target, which should be available in any AOP framework), benefiting from all the pluggability provided by Dependency Injection. + + [[classic-aop-pfb-2]] ==== JavaBean properties In common with most `FactoryBean` implementations provided with Spring, the @@ -44880,6 +47023,8 @@ to be applied. An example of using this feature can be found in < ---- + + + [[classic-aop-concise-proxy]] === Concise proxy definitions Especially when defining transactional proxies, you may end up with many similar proxy @@ -45169,6 +47323,9 @@ and this definition specifies a class, you must make sure to set the__abstract__ attribute to __true__, otherwise the application context will actually try to pre-instantiate it. + + + [[classic-aop-prog]] === Creating AOP proxies programmatically with the ProxyFactory It's easy to create AOP proxies programmatically using Spring. This enables you to use @@ -45208,6 +47365,9 @@ applications. We recommend that you externalize configuration from Java code wit as in general. ==== + + + [[classic-aop-api-advised]] === Manipulating advised objects However you create AOP proxies, you can manipulate them using the @@ -45299,6 +47459,9 @@ prevent calling code removing a security interceptor. It may also be used in Spr to allow aggressive optimization if runtime advice modification is known not to be required. + + + [[classic-aop-autoproxy]] === Using the "autoproxy" facility So far we've considered explicit creation of AOP proxies using a `ProxyFactoryBean` or @@ -45318,11 +47481,14 @@ There are two ways to do this: * A special case of autoproxy creation that deserves to be considered separately; autoproxy creation driven by source-level metadata attributes. + + [[classic-aop-autoproxy-choices]] ==== Autoproxy bean definitions The `org.springframework.aop.framework.autoproxy` package provides the following standard autoproxy creators. + [[classic-aop-api-autoproxy]] ===== BeanNameAutoProxyCreator The `BeanNameAutoProxyCreator` class is a `BeanPostProcessor` that automatically creates @@ -45356,6 +47522,7 @@ created automatically by the `BeanNameAutoProxyCreator`. The same advice will be to all matching beans. Note that if advisors are used (rather than the interceptor in the above example), the pointcuts may apply differently to different beans. + [[classic-aop-api-autoproxy-default]] ===== DefaultAdvisorAutoProxyCreator A more general and extremely powerful auto proxy creator is @@ -45417,6 +47584,7 @@ Advisors can implement the `org.springframework.core.Ordered` interface to ensur correct ordering if this is an issue. The TransactionAttributeSourceAdvisor used in the above example has a configurable order value; the default setting is unordered. + [[classic-aop-api-autoproxy-abstract]] ===== AbstractAdvisorAutoProxyCreator This is the superclass of DefaultAdvisorAutoProxyCreator. You can create your own @@ -45424,6 +47592,8 @@ autoproxy creators by subclassing this class, in the unlikely event that advisor definitions offer insufficient customization to the behavior of the framework `DefaultAdvisorAutoProxyCreator`. + + [[classic-aop-autoproxy-metadata]] ==== Using metadata-driven auto-proxying A particularly important type of autoproxying is driven by metadata. This produces a @@ -45560,6 +47730,9 @@ definitions, the mixin will be applied. Note that both `lockMixin` and `lockable definitions are prototypes. The `myAttributeAwarePointcut` pointcut can be a singleton definition, as it doesn't hold state for individual advised objects. + + + [[classic-aop-targetsource]] === Using TargetSources Spring offers the concept of a __TargetSource__, expressed in the @@ -45586,6 +47759,8 @@ rather than a singleton bean definition. This allows Spring to create a new targ instance when required. ==== + + [[classic-aop-ts-swap]] ==== Hot swappable target sources The `org.springframework.aop.target.HotSwappableTargetSource` exists to allow the target @@ -45628,6 +47803,8 @@ Although this example doesn't add any advice - and it's not necessary to add adv use a `TargetSource` - of course any `TargetSource` can be used in conjunction with arbitrary advice. + + [[classic-aop-ts-pool]] ==== Pooling target sources Using a pooling target source provides a similar programming model to stateless session @@ -45714,6 +47891,8 @@ pooling is problematic if resources are cached. Simpler pooling is available using autoproxying. It's possible to set the TargetSources used by any autoproxy creator. + + [[classic-aop-ts-prototype]] ==== Prototype target sources Setting up a "prototype" target source is similar to a pooling TargetSource. In this @@ -45737,6 +47916,8 @@ There's only one property: the name of the target bean. Inheritance is used in t TargetSource implementations to ensure consistent naming. As with the pooling target source, the target bean must be a prototype bean definition. + + [[classic-aop-ts-threadlocal]] ==== ThreadLocal target sources @@ -45767,6 +47948,9 @@ ThreadLocal support does this for you and should always be considered in favor o ThreadLocals without other proper handling code. ==== + + + [[classic-aop-extensibility]] === Defining new Advice types @@ -45783,6 +47967,9 @@ only constraint on a custom `Advice` type is that it must implement the Please refer to the `org.springframework.aop.framework.adapter` package's Javadocs for further information. + + + [[classic-aop-api-resources]] === Further resources Please refer to the Spring sample applications for further examples of Spring AOP: @@ -45792,11 +47979,18 @@ Please refer to the Spring sample applications for further examples of Spring AO * The `/attributes` directory of the JPetStore illustrates the use of attribute-driven declarative transaction management. + + + + [[migration-3.1]] == Migrating to Spring Framework 3.1 In this appendix we discuss what users will want to know when upgrading to Spring Framework 3.1. For a general overview of features, please see<> + + + [[migration-3.1-component-scan]] === Component scanning against the "org" base package Spring Framework 3.1 introduces a number of `@Configuration` classes such as @@ -45825,11 +48019,18 @@ updated to at least one more level of qualification e.g.: Alternatively, an `exclude-filter` may be used. See <> documentation for details. + + + + [[migration-3.2]] == Migrating to Spring Framework 3.2 In this appendix we discuss what users will want to know when upgrading to Spring Framework 3.2. For a general overview of features, please see<> + + + [[migration-3.2-new-optional-deps]] === Newly optional dependencies Certain inter-module dependencies are now `optional` at the Maven POM level where they @@ -45839,12 +48040,18 @@ been relying on transitive dependency management to pull in affected downstream `spring-*`. To resolve this problem, simply add the appropriate missing jars to your build configuration. + + + [[migration-3.2-ehcache-support]] === EHCache support moved to spring-context-support Along with Spring's new JCache support, the EHCache support classes in the `org.springframework.cache.ehcache` package moved from the `spring-context` module to `spring-context-support`. + + + [[migration-3.2-inline-asm]] === Inlining of spring-asm jar In versions 3.0 and 3.1, we published a discrete `spring-asm` containing repackaged @@ -45855,6 +48062,9 @@ most users; but on the off chance that you have `spring-asm` declared directly w your project's build script, you'll want to remove it when upgrading to Spring Framework 3.2. + + + [[migration-3.2-inline-cglib]] === Explicit CGLIB dependency no longer required In prior versions, users of Spring's subclass-based AOP proxies (e.g. via @@ -45867,12 +48077,18 @@ users who are creating subclass proxies of types that contain `invokedynamic` by instructions. Repackaging CGLIB internally ensures no classpath conflicts with other third party frameworks that may depend on other versions of CGLIB. + + + [[migration-3.2-osgi-users]] === For OSGi users OSGi metadata is no longer published within individual Spring Framework jar MANIFEST.MF files. For more information about how users can get OSGi-ready versions of Spring Framework 3.2 jars. + + + [[migration-3.2-compatibility-mvc-config]] === MVC Java Config and MVC Namespace As explained in <>, both the MVC Java config and the MVC @@ -45889,21 +48105,33 @@ MVC namespace, semicolon content is left in the URI so that matrix variables are automatically supported. The removal of semicolon content is controlled through the `UrlPathHelper` property of `RequestMappingHandlerMapping`. + + + [[migration-3.2-compatibility-uri-variable-values]] === Decoding of URI Variable Values URI variable values now get decoded when `UrlPathHelper.setUrlDecode` is set to `false`. See https://jira.springsource.org/browse/SPR-9098[SPR-9098]. + + + [[migration-3.2-compatibility-http-patch]] === HTTP PATCH method The `DispatcherServlet` now allows the HTTP PATCH method where previously it didn't. + + + [[migration-3.2-compatibility-tiles3]] === Tiles 3 Besides the version number change, the set of Tiles dependencies has also changed. You will need to have a subset or all of `tiles-request-api`, `tiles-api`, `tiles-core`, `tiles-servlet`, `tiles-jsp`, `tiles-el`. + + + [[migration-3.2-compatibility-spring-mvc-test]] === Spring MVC Test standalone project If migrating from the https://github.com/SpringSource/spring-test-mvc[spring-test-mvc] @@ -45916,6 +48144,9 @@ You will no longer be able to use the `MockMvcBuilders` `annotationConfigSetup` inject a `WebApplicationContext` into the test and use it to create a `MockMvc`. See <> for details. + + + [[migration-3.2-compatibility-spring-test]] === Spring Test Dependencies The `spring-test` module has been upgraded to depend on JUnit 4.11 ( `junit:junit`), @@ -45927,9 +48158,14 @@ has stopped inlining Hamcrest Core within the `junit:junit` Maven artifact as of may therefore need to remove any exclusions on `hamcrest-core` that they had previously configured for their build. + + + [[migration-3.2-changes]] === Public API changes + + [[migration-3.2-api-changes]] ==== JDiff reports Select JDiff reports are now being published to provide users with a convenient means of @@ -45942,6 +48178,8 @@ next-generation development, e.g. http://docs.spring.io/spring-framework/docs/3.2.0.RC2_to_3.2.0.RELEASE[3.2.0.RC2 to 3.2.0.RELEASE]. + + [[migration-3.2-removals-and-deprecations]] ==== Deprecations The following packages and types have been wholly or partially deprecated in Spring @@ -45986,9 +48224,16 @@ list of deprecations] in the framework. * http://docs.spring.io/spring/docs/3.2.0.RELEASE/javadoc-api/org/springframework/orm/jpa/vendor/TopLinkJpaVendorAdapter.html[org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter] * http://docs.spring.io/spring/docs/3.2.0.RELEASE/javadoc-api/org/springframework/util/CachingMapDecorator.html[org.springframework.orm.util.CachingMapDecorator] + + + + [[xsd-config]] == XML Schema-based configuration + + + [[xsd-config-introduction]] === Introduction This appendix details the XML Schema-based configuration introduced in Spring 2.0 and @@ -46035,9 +48280,14 @@ customisable and extensible. This means you can write your own domain-specific configuration tags that would better represent your application's domain; the process involved in doing so is covered in the appendix entitled <>. + + + [[xsd-config-body]] === XML Schema-based configuration + + [[xsd-config-body-referencing]] ==== Referencing the schemas To switch over from the DTD-style to the new XML Schema-style, you need to make the @@ -46091,6 +48341,8 @@ before and after style, with a __before__ snippet of XML showing the old (but st legal and supported) style, followed immediately by an __after__ example showing the equivalent in the new XML Schema-based style. + + [[xsd-config-body-schemas-util]] ==== the util schema @@ -46115,6 +48367,7 @@ __http://www.springframework.org/schema/util http://www.springframework.org/sche ---- + [[xsd-config-body-schemas-util-constant]] ===== @@ -46251,6 +48504,7 @@ This works for classic type-safe emulated enums (on JDK 1.4 and JDK 1.3) as well will automatically attempt to match the string property value to a constant on the enum class. + [[xsd-config-body-schemas-util-property-path]] ===== @@ -46376,6 +48630,7 @@ The result type may be specifically set in the actual definition. This is not ne for most use cases, but can be of use for some. Please see the Javadocs for more info on this feature. + [[xsd-config-body-schemas-util-properties]] ===== @@ -46403,6 +48658,7 @@ After... ---- + [[xsd-config-body-schemas-util-list]] ===== @@ -46461,6 +48717,7 @@ following configuration: If no `'list-class'` attribute is supplied, a `List` implementation will be chosen by the container. + [[xsd-config-body-schemas-util-map]] ===== @@ -46519,6 +48776,7 @@ following configuration: If no `'map-class'` attribute is supplied, a `Map` implementation will be chosen by the container. + [[xsd-config-body-schemas-util-set]] ===== @@ -46577,6 +48835,8 @@ following configuration: If no `'set-class'` attribute is supplied, a `Set` implementation will be chosen by the container. + + [[xsd-config-body-schemas-jee]] ==== the jee schema @@ -46600,6 +48860,7 @@ __http://www.springframework.org/schema/jee http://www.springframework.org/schem ---- + [[xsd-config-body-schemas-jee-jndi-lookup]] ===== (simple) @@ -46630,6 +48891,7 @@ After... ---- + [[xsd-config-body-schemas-jee-jndi-lookup-environment-single]] ===== (with single JNDI environment setting) @@ -46658,6 +48920,7 @@ After... ---- + [[xsd-config-body-schemas-jee-jndi-lookup-evironment-multiple]] ===== (with multiple JNDI environment settings) @@ -46691,6 +48954,7 @@ After... ---- + [[xsd-config-body-schemas-jee-jndi-lookup-complex]] ===== (complex) @@ -46723,6 +48987,7 @@ After... proxy-interface="com.myapp.Foo"/> ---- + [[xsd-config-body-schemas-jee-local-slsb]] ===== (simple) @@ -46749,6 +49014,7 @@ After... business-interface="com.foo.service.RentalService"/> ---- + [[xsd-config-body-schemas-jee-local-slsb-complex]] ===== (complex) @@ -46778,6 +49044,7 @@ After... resource-ref="true"> ---- + [[xsd-config-body-schemas-jee-remote-slsb]] ===== @@ -46816,6 +49083,8 @@ After... refresh-home-on-connect-failure="true"> ---- + + [[xsd-config-body-schemas-lang]] ==== the lang schema @@ -46844,6 +49113,8 @@ __http://www.springframework.org/schema/lang http://www.springframework.org/sche ---- + + [[xsd-config-body-schemas-jms]] ==== the jms schema @@ -46870,6 +49141,8 @@ __http://www.springframework.org/schema/jms http://www.springframework.org/schem ---- + + [[xsd-config-body-schemas-tx]] ==== the tx (transaction) schema @@ -46915,6 +49188,8 @@ using AOP). The above XML snippet contains the relevant lines needed to referenc `aop` schema so that the tags in the `aop` namespace are available to you. ==== + + [[xsd-config-body-schemas-aop]] ==== the aop schema @@ -46940,6 +49215,8 @@ __http://www.springframework.org/schema/aop http://www.springframework.org/schem ---- + + [[xsd-config-body-schemas-context]] ==== the context schema @@ -46967,6 +49244,7 @@ __http://www.springframework.org/schema/context http://www.springframework.org/s The `context` schema was only introduced in Spring 2.5. ==== + [[xsd-config-body-schemas-context-pphc]] ===== @@ -46976,6 +49254,7 @@ a convenience mechanism that sets up a<> for you; if you need more control over the `PropertyPlaceholderConfigurer`, just define one yourself explicitly. + [[xsd-config-body-schemas-context-ac]] ===== @@ -46993,26 +49272,32 @@ This element does __not__ activate processing of Spring's <`>> element for that purpose. ==== + [[xsd-config-body-schemas-context-component-scan]] ===== This element is detailed in <>. + [[xsd-config-body-schemas-context-ltw]] ===== This element is detailed in <>. + [[xsd-config-body-schemas-context-sc]] ===== This element is detailed in <>. + [[xsd-config-body-schemas-context-mbe]] ===== This element is detailed in <>. + + [[xsd-config-body-schemas-tool]] ==== the tool schema @@ -47028,6 +49313,8 @@ to this review process, then do mail the Spring mailing list. The currently supp `'src/org/springframework/beans/factory/xml'` directory of the Spring source distribution. + + [[xsd-config-body-schemas-jdbc]] ==== the jdbc schema @@ -47052,6 +49339,8 @@ __http://www.springframework.org/schema/jdbc http://www.springframework.org/sche ---- + + [[xsd-config-body-schemas-cache]] ==== the cache schema @@ -47076,6 +49365,8 @@ __http://www.springframework.org/schema/cache http://www.springframework.org/sch ---- + + [[xsd-config-body-schemas-beans]] ==== the beans schema @@ -47112,9 +49403,16 @@ In the case of the above example, you would assume that there is some logic that consume the bean definition and set up some caching infrastructure using the supplied metadata. + + + + [[extensible-xml]] == Extensible XML authoring + + + [[extensible-xml-introduction]] === Introduction Since version 2.0, Spring has featured a mechanism for schema-based extensions to the @@ -47155,6 +49453,9 @@ __(Don't worry about the fact that this example is very simple; much more detail examples follow afterwards. The intent in this first simple example is to walk you through the basic steps involved.)__ + + + [[extensible-xml-schema]] === Authoring the schema Creating an XML configuration extension for use with Spring's IoC container starts with @@ -47227,6 +49528,9 @@ can use autocompletion to have a user choose between several configuration optio defined in the enumeration. ==== + + + [[extensible-xml-namespacehandler]] === Coding a NamespaceHandler @@ -47282,6 +49586,9 @@ delegating to `BeanDefinitionParsers` to do the grunt work of the XML parsing; t means that each `BeanDefinitionParser` will contain just the logic for parsing a single custom element, as we can see in the next step + + + [[extensible-xml-parser]] === nDefinitionParser @@ -47328,6 +49635,9 @@ In this simple case, this is all that we need to do. The creation of our single `BeanDefinition` is handled by the `AbstractSingleBeanDefinitionParser` superclass, as is the extraction and setting of the bean definition's unique identifier. + + + [[extensible-xml-registration]] === Registering the handler and the schema The coding is finished! All that remains to be done is to somehow make the Spring XML @@ -47338,6 +49648,8 @@ can, for example, be distributed alongside your binary classes in a JAR file. Th XML parsing infrastructure will automatically pick up your new extension by consuming these special properties files, the formats of which are detailed below. + + [[extensible-xml-registration-spring-handlers]] ==== 'META-INF/spring.handlers' @@ -47357,6 +49669,8 @@ The first part (the key) of the key-value pair is the URI associated with your c namespace extension, and needs to __match exactly__ the value of the `'targetNamespace'` attribute as specified in your custom XSD schema. + + [[extensible-xml-registration-spring-schemas]] ==== 'META-INF/spring.schemas' @@ -47377,6 +49691,9 @@ http\://www.mycompany.com/schema/myns/myns.xsd=org/springframework/samples/xml/m The upshot of this is that you are encouraged to deploy your XSD file(s) right alongside the `NamespaceHandler` and `BeanDefinitionParser` classes on the classpath. + + + [[extensible-xml-using]] === Using a custom extension in your Spring XML configuration Using a custom extension that you yourself have implemented is no different from using @@ -47408,10 +49725,15 @@ http://www.mycompany.com/schema/myns http://www.mycompany.com/schema/myns/myns.x ---- + + + [[extensible-xml-meat]] === Meatier examples Find below some much meatier examples of custom XML extensions. + + [[extensible-xml-custom-nested]] ==== Nesting custom tags within custom tags This example illustrates how you might go about writing the various artifacts required @@ -47639,6 +49961,8 @@ http\://www.foo.com/schema/component=com.foo.ComponentNamespaceHandler http\://www.foo.com/schema/component/component.xsd=com/foo/component.xsd ---- + + [[extensible-xml-custom-just-attributes]] ==== Custom attributes on 'normal' elements Writing your own custom parser and the associated artifacts isn't hard, but sometimes it @@ -47795,6 +50119,9 @@ http\://www.foo.com/schema/jcache=com.foo.JCacheNamespaceHandler http\://www.foo.com/schema/jcache/jcache.xsd=com/foo/jcache.xsd ---- + + + [[extensible-xml-resources]] === Further Resources Find below links to further resources concerning XML Schema and the extensible XML @@ -47805,9 +50132,16 @@ support described in this chapter. * The http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/[XML Schema Part 2: Datatypes Second Edition] + + + + [[spring.tld]] == spring.tld + + + [[spring.tld-intro]] === Introduction One of the view technologies you can use with the Spring Framework is Java Server Pages @@ -47832,6 +50166,9 @@ This appendix describes the `spring.tld` tag library. * <> * <> + + + [[spring.tld.bind]] === the bind tag @@ -47864,6 +50201,9 @@ in a page-wide or application-wide setting (i.e. by HtmlEscapeTag or a exported to the page scope, specifically for this bean or bean property |=== + + + [[spring.tld.escapeBody]] === the escapeBody tag @@ -47889,6 +50229,9 @@ HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml). | Set JavaScript escaping for this tag, as boolean value. Default is false. |=== + + + [[spring.tld.hasBindErrors]] === the hasBindErrors tag @@ -47915,6 +50258,9 @@ context-param in web.xml). are available for this bean, they will be bound under the 'errors' key. |=== + + + [[spring.tld.htmlEscape]] === the htmlEscape tag @@ -47933,6 +50279,9 @@ context-param in web.xml, if any. | Set the default value for HTML escaping, to be put into the current PageContext. |=== + + + [[spring.tld.message]] === the message tag @@ -48005,6 +50354,9 @@ HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml). directly to the JSP). |=== + + + [[spring.tld.nestedPath]] === the nestedPath tag @@ -48023,6 +50375,9 @@ Sets a nested path to be used by the bind tag's path. 'address.street' rather than 'customer.address.street'. |=== + + + [[spring.tld.theme]] === the theme tag @@ -48091,6 +50446,9 @@ HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml). directly to the JSP). |=== + + + [[spring.tld.transform]] === the transform tag @@ -48132,6 +50490,9 @@ participates in a page-wide or application-wide setting (i.e. by HtmlEscapeTag o directly to the JSP). |=== + + + [[spring.tld.url]] === the url tag @@ -48182,6 +50543,9 @@ escaping. Modeled after the JSTL c:url tag with backwards compatibility in mind. | Set JavaScript escaping for this tag, as a boolean value. Default is false. |=== + + + [[spring.tld.eval]] === the eval tag @@ -48224,9 +50588,16 @@ variable. | Set JavaScript escaping for this tag, as a boolean value. Default is false. |=== + + + + [[spring-form.tld]] == spring-form.tld + + + [[spring-form.tld-intro]] === Introduction One of the view technologies you can use with the Spring Framework is Java Server Pages @@ -48255,6 +50626,9 @@ This appendix describes the `spring-form.tld` tag library. * <> * <> + + + [[spring-form.tld.checkbox]] === the checkbox tag @@ -48403,6 +50777,9 @@ Renders an HTML 'input' tag with type 'checkbox'. | HTML Optional Attribute |=== + + + [[spring-form.tld.checkboxes]] === the checkboxes tag @@ -48570,6 +50947,9 @@ Renders multiple HTML 'input' tags with type 'checkbox'. | HTML Standard Attribute |=== + + + [[spring-form.tld.errors]] === the errors tag @@ -48687,6 +51067,9 @@ Renders field errors in an HTML 'span' tag. | HTML Standard Attribute |=== + + + [[spring-form.tld.form]] === the form tag @@ -48839,6 +51222,9 @@ Renders an HTML 'form' tag and exposes a binding path to inner tags for binding. | HTML Standard Attribute |=== + + + [[spring-form.tld.hidden]] === the hidden tag @@ -48866,6 +51252,9 @@ Renders an HTML 'input' tag with type 'hidden' using the bound value. | Path to property for data binding |=== + + + [[spring-form.tld.input]] === the input tag @@ -49035,6 +51424,9 @@ Renders an HTML 'input' tag with type 'text' using the bound value. | HTML Standard Attribute |=== + + + [[spring-form.tld.label]] === the label tag @@ -49152,6 +51544,9 @@ Renders a form field label in an HTML 'label' tag. | HTML Standard Attribute |=== + + + [[spring-form.tld.option]] === the option tag @@ -49275,6 +51670,9 @@ Renders a single HTML 'option'. Sets 'selected' as appropriate based on bound va | HTML Optional Attribute |=== + + + [[spring-form.tld.options]] === the options tag @@ -49403,6 +51801,9 @@ Renders a list of HTML 'option' tags. Sets 'selected' as appropriate based on bo | HTML Standard Attribute |=== + + + [[spring-form.tld.password]] === the password tag @@ -49577,6 +51978,9 @@ Renders an HTML 'input' tag with type 'password' using the bound value. | HTML Standard Attribute |=== + + + [[spring-form.tld.radiobutton]] === the radiobutton tag @@ -49725,6 +52129,9 @@ Renders an HTML 'input' tag with type 'radio'. | HTML Optional Attribute |=== + + + [[spring-form.tld.radiobuttons]] === the radiobuttons tag @@ -49891,6 +52298,9 @@ Renders multiple HTML 'input' tags with type 'radio'. | HTML Standard Attribute |=== + + + [[spring-form.tld.select]] === the select tag @@ -50054,6 +52464,9 @@ Renders an HTML 'select' element. Supports databinding to the selected option. | HTML Standard Attribute |=== + + + [[spring-form.tld.textarea]] === the textarea tag