From a3eeda99e0a81c6fc51dbafe201f550a395c139b Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 18 Oct 2017 20:24:17 +0200 Subject: [PATCH] Consistent separation between chapters and after chapter titles --- src/docs/asciidoc/core/core-aop-api.adoc | 206 ++----- src/docs/asciidoc/core/core-aop.adoc | 83 ++- src/docs/asciidoc/core/core-appendix.adoc | 27 +- src/docs/asciidoc/core/core-beans.adoc | 31 +- src/docs/asciidoc/core/core-expressions.adoc | 53 +- src/docs/asciidoc/core/core-null-safety.adoc | 3 + src/docs/asciidoc/core/core-resources.adoc | 14 +- src/docs/asciidoc/core/core-validation.adoc | 28 +- src/docs/asciidoc/data-access-appendix.adoc | 3 + src/docs/asciidoc/data-access.adoc | 250 ++++----- src/docs/asciidoc/integration-appendix.adoc | 4 + src/docs/asciidoc/integration.adoc | 515 ++++++------------ src/docs/asciidoc/kotlin.adoc | 67 ++- src/docs/asciidoc/overview.adoc | 15 + src/docs/asciidoc/testing-webtestclient.adoc | 8 +- src/docs/asciidoc/testing.adoc | 89 ++- src/docs/asciidoc/web-reactive.adoc | 4 + src/docs/asciidoc/web/integration.adoc | 20 +- src/docs/asciidoc/web/webflux-functional.adoc | 10 +- src/docs/asciidoc/web/webflux-webclient.adoc | 9 +- src/docs/asciidoc/web/webflux.adoc | 31 +- src/docs/asciidoc/web/webmvc-client.adoc | 5 + src/docs/asciidoc/web/webmvc-cors.adoc | 18 +- src/docs/asciidoc/web/webmvc-test.adoc | 10 + src/docs/asciidoc/web/webmvc-view.adoc | 74 ++- src/docs/asciidoc/web/webmvc.adoc | 110 +++- src/docs/asciidoc/web/websocket.adoc | 47 +- 27 files changed, 995 insertions(+), 739 deletions(-) diff --git a/src/docs/asciidoc/core/core-aop-api.adoc b/src/docs/asciidoc/core/core-aop-api.adoc index 35c9e162dd1..ad5c5e1bd3f 100644 --- a/src/docs/asciidoc/core/core-aop-api.adoc +++ b/src/docs/asciidoc/core/core-aop-api.adoc @@ -2,28 +2,33 @@ = Spring AOP APIs + + [[aop-api-introduction]] == Introduction + The previous chapter described the Spring's support for AOP using @AspectJ and schema-based aspect definitions. In this chapter we discuss the lower-level -Spring AOP APIs and the AOP support used in Spring 1.2 applications. For new +Spring AOP APIs and the AOP support typically used in Spring 1.2 applications. For new applications, we recommend the use of the Spring 2.0 and later AOP support described in the previous chapter, but when working with existing applications, or when reading books -and articles, you may come across Spring 1.2 style examples. Spring 4.0 is backwards +and articles, you may come across Spring 1.2 style examples. Spring 5 remains backwards compatible with Spring 1.2 and everything described in this chapter is fully supported -in Spring 4.0. +in Spring 5. [[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 possible to target different advice using the same pointcut. @@ -88,7 +93,6 @@ In this case, the 3-argument matches method will never be invoked. [TIP] ==== - If possible, try to make pointcuts static, allowing the AOP framework to cache the results of pointcut evaluation when an AOP proxy is created. ==== @@ -97,6 +101,7 @@ 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__. * Union means the methods that either pointcut matches. @@ -111,6 +116,7 @@ Spring supports operations on pointcuts: notably, __union__ and __intersection__ [[aop-api-pointcuts-aspectj]] === AspectJ expression pointcuts + Since 2.0, the most important type of pointcut used by Spring is `org.springframework.aop.aspectj.AspectJExpressionPointcut`. This is a pointcut that uses an AspectJ supplied library to parse an AspectJ pointcut expression string. @@ -121,12 +127,14 @@ See the previous chapter for a discussion of supported AspectJ pointcut primitiv [[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 method's arguments. Static pointcuts are sufficient - __and best__ - for most usages. It's possible for Spring to evaluate a static pointcut only once, when a method is first @@ -137,10 +145,11 @@ Let's consider some static pointcut implementations included with Spring. [[aop-api-pointcuts-regex]] ===== Regular expression pointcuts + One obvious way to specify static pointcuts is regular expressions. Several AOP frameworks besides Spring make this possible. `org.springframework.aop.support.JdkRegexpMethodPointcut` is a generic regular -expression pointcut, using the regular expression support in JDK 1.4+. +expression pointcut, using the regular expression support in the JDK. Using the `JdkRegexpMethodPointcut` class, you can provide a list of pattern Strings. If any of these is a match, the pointcut will evaluate to true. (So the result is @@ -189,12 +198,14 @@ __RegexpMethodPointcutAdvisor__ can be used with any Advice type. [[aop-api-pointcuts-attribute-driven]] ===== Attribute-driven pointcuts + 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 method __arguments__, as well as static information. This means that they must be evaluated with every method invocation; the result cannot be cached, as arguments will @@ -204,12 +215,14 @@ The main example is the `control flow` pointcut. [[aop-api-pointcuts-cflow]] ===== Control flow pointcuts + Spring control flow pointcuts are conceptually similar to AspectJ __cflow__ pointcuts, although less powerful. (There is currently no way to specify that a pointcut executes below a join point matched by another pointcut.) A control flow pointcut matches the current call stack. For example, it might fire if the join point was invoked by a method in the `com.mycompany.web` package, or by the `SomeCaller` class. Control flow pointcuts are specified using the `org.springframework.aop.support.ControlFlowPointcut` class. + [NOTE] ==== Control flow pointcuts are significantly more expensive to evaluate at runtime than even @@ -221,6 +234,7 @@ pointcuts. [[aop-api-pointcuts-superclasses]] === Pointcut superclasses + Spring provides useful pointcut superclasses to help you to implement your own pointcuts. Because static pointcuts are most useful, you'll probably subclass @@ -246,6 +260,7 @@ 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 AspectJ) it's possible to declare custom pointcuts, whether static or dynamic. Custom pointcuts in Spring can be arbitrarily complex. However, using the AspectJ pointcut @@ -262,12 +277,14 @@ 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 objects, or unique to each advised object. This corresponds to __per-class__ or __per-instance__ advice. @@ -285,12 +302,14 @@ It's possible to use a mix of shared and per-instance advice in the same AOP pro [[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__. Spring is compliant with the AOP Alliance interface for around advice using method @@ -347,6 +366,7 @@ currently define pointcut interfaces. [[aop-api-advice-before]] ==== Before advice + A simpler advice type is a __before advice__. This does not need a `MethodInvocation` object, since it will only be called before entering the method. @@ -395,13 +415,13 @@ An example of a before advice in Spring, which counts all method invocations: [TIP] ==== - 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 an exception. Spring offers typed throws advice. Note that this means that the `org.springframework.aop.ThrowsAdvice` interface does not contain any methods: It is a @@ -478,13 +498,13 @@ exception that is incompatible with the target method's signature!__ [TIP] ==== - 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 __org.springframework.aop.AfterReturningAdvice__ interface, shown below: @@ -527,13 +547,13 @@ thrown up the interceptor chain instead of the return value. [TIP] ==== - 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. Introduction requires an `IntroductionAdvisor`, and an `IntroductionInterceptor`, @@ -696,6 +716,7 @@ 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 with a pointcut expression. @@ -714,6 +735,7 @@ chain. [[aop-pfb]] == Using the ProxyFactoryBean to create AOP proxies + If you're using the Spring IoC container (an ApplicationContext or BeanFactory) for your business objects - and you should be! - you will want to use one of Spring's AOP FactoryBeans. (Remember that a factory bean introduces a layer of indirection, enabling @@ -733,6 +755,7 @@ options that are preferable if you don't need such control. [[aop-pfb-1]] === Basics + The `ProxyFactoryBean`, like other Spring `FactoryBean` implementations, introduces a level of indirection. If you define a `ProxyFactoryBean` with name `foo`, what objects referencing `foo` see is not the `ProxyFactoryBean` instance itself, but an object @@ -750,6 +773,7 @@ framework), benefiting from all the pluggability provided by Dependency Injectio [[aop-pfb-2]] === JavaBean properties + In common with most `FactoryBean` implementations provided with Spring, the `ProxyFactoryBean` class is itself a JavaBean. Its properties are used to: @@ -803,6 +827,7 @@ to be applied. An example of using this feature can be found in < - - - - - - - - - - - - - - - ----- - -The `DefaultAdvisorAutoProxyCreator` bean definition (the name is not significant, hence -it can even be omitted) will pick up all eligible pointcuts in the current application -context. In this case, the "transactionAdvisor" bean definition, of type -`TransactionAttributeSourceAdvisor`, will apply to classes or methods carrying a -transaction attribute. The TransactionAttributeSourceAdvisor depends on a -TransactionInterceptor, via constructor dependency. The example resolves this via -autowiring. The `AttributesTransactionAttributeSource` depends on an implementation of -the `org.springframework.metadata.Attributes` interface. In this fragment, the -"attributes" bean satisfies this, using the Jakarta Commons Attributes API to obtain -attribute information. (The application code must have been compiled using the Commons -Attributes compilation task.) - -The `/annotation` directory of the JPetStore sample application contains an analogous -example for auto-proxying driven by JDK 1.5+ annotations. The following configuration -enables automatic detection of Spring's `Transactional` annotation, leading to implicit -proxies for beans containing that annotation: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - - - - - - - - - ----- - -The `TransactionInterceptor` defined here depends on a `PlatformTransactionManager` -definition, which is not included in this generic file (although it could be) because it -will be specific to the application's transaction requirements (typically JTA, as in -this example, or Hibernate or JDBC): - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - ----- - -[TIP] -==== - -If you require only declarative transaction management, using these generic XML -definitions will result in Spring automatically proxying all classes or methods with -transaction attributes. You won't need to work directly with AOP, and the programming -model is similar to that of .NET ServicedComponents. -==== - -This mechanism is extensible. It's possible to do auto-proxying based on custom -attributes. You need to: - -* Define your custom attribute. -* Specify an Advisor with the necessary advice, including a pointcut that is triggered - by the presence of the custom attribute on a class or method. You may be able to use - an existing advice, merely implementing a static pointcut that picks up the custom - attribute. - -It's possible for such advisors to be unique to each advised class (for example, mixins): -they simply need to be defined as prototype, rather than singleton, bean definitions. -For example, the `LockMixin` introduction interceptor from the Spring test suite, -shown above, could be used in conjunction with a generic `DefaultIntroductionAdvisor`: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - - ----- - -Note that both `lockMixin` and `lockableAdvisor` are defined as prototypes. - - [[aop-targetsource]] == Using TargetSources + Spring offers the concept of a __TargetSource__, expressed in the `org.springframework.aop.TargetSource` interface. This interface is responsible for returning the "target object" implementing the join point. The `TargetSource` @@ -1518,7 +1416,6 @@ Let's look at the standard target sources provided with Spring, and how you can [TIP] ==== - When using a custom target source, your target will usually need to be a prototype rather than a singleton bean definition. This allows Spring to create a new target instance when required. @@ -1528,6 +1425,7 @@ instance when required. [[aop-ts-swap]] === Hot swappable target sources + The `org.springframework.aop.target.HotSwappableTargetSource` exists to allow the target of an AOP proxy to be switched while allowing callers to keep their references to it. @@ -1571,6 +1469,7 @@ arbitrary advice. [[aop-ts-pool]] === Pooling target sources + Using a pooling target source provides a similar programming model to stateless session EJBs, in which a pool of identical instances is maintained, with method invocations going to free objects in the pool. @@ -1665,6 +1564,7 @@ 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 case, a new instance of the target will be created on every method invocation. Although the cost of creating a new object isn't high in a modern JVM, the cost of wiring up the @@ -1736,15 +1636,3 @@ The only constraint on a custom `Advice` type is that it must implement the Please refer to the `org.springframework.aop.framework.adapter` javadocs for further information. - - - - -[[aop-api-resources]] -== Further resources -Please refer to the Spring sample applications for further examples of Spring AOP: - -* The JPetStore's default configuration illustrates the use of the - `TransactionProxyFactoryBean` for declarative transaction management. -* The `/attributes` directory of the JPetStore illustrates the use of attribute-driven - declarative transaction management. \ No newline at end of file diff --git a/src/docs/asciidoc/core/core-aop.adoc b/src/docs/asciidoc/core/core-aop.adoc index 64341524b18..e37be11e098 100644 --- a/src/docs/asciidoc/core/core-aop.adoc +++ b/src/docs/asciidoc/core/core-aop.adoc @@ -2,8 +2,11 @@ = Aspect Oriented Programming with Spring + + [[aop-introduction]] == Introduction + __Aspect-Oriented Programming__ (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the __aspect__. Aspects @@ -15,17 +18,16 @@ One of the key components of Spring is the __AOP framework__. While the Spring I container does not depend on AOP, meaning you do not need to use AOP if you don't want to, AOP complements Spring IoC to provide a very capable middleware solution. -.Spring 2.0 AOP +.Spring 2.0+ AOP **** -Spring 2.0 introduces a simpler and more powerful way of writing custom aspects using +Spring 2.0 introduced a simpler and more powerful way of writing custom aspects using either a <> or the <>. Both of these styles offer fully typed advice and use of the AspectJ pointcut language, while still using Spring AOP for weaving. -The Spring 2.0 schema- and @AspectJ-based AOP support is discussed in this chapter. -Spring 2.0 AOP remains fully backwards compatible with Spring 1.2 AOP, and the -lower-level AOP support offered by the Spring 1.2 APIs is discussed in <>. +The Spring 2.0+ schema- and @AspectJ-based AOP support is discussed in this chapter. +The lower-level AOP support, as commonly exposed in Spring 1.2 applications, is +discussed in <>. **** AOP is used in the Spring Framework to... @@ -46,6 +48,7 @@ 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 Spring-specific... unfortunately, AOP terminology is not particularly intuitive; however, it would be even more confusing if Spring used its own terminology. @@ -123,6 +126,7 @@ 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 process. Spring AOP does not need to control the class loader hierarchy, and is thus suitable for use in a Servlet container or application server. @@ -182,6 +186,7 @@ style. [[aop-introduction-proxies]] === AOP Proxies + Spring AOP defaults to using standard JDK __dynamic proxies__ for AOP proxies. This enables any interface (or set of interfaces) to be proxied. @@ -202,6 +207,7 @@ implementation detail actually means. [[aop-ataspectj]] == @AspectJ support + @AspectJ refers to a style of declaring aspects as regular Java classes annotated with annotations. The @AspectJ style was introduced by the http://www.eclipse.org/aspectj[AspectJ project] as part of the AspectJ 5 release. Spring @@ -219,6 +225,7 @@ discussed in <>. [[aop-aspectj-support]] === Enabling @AspectJ Support + To use @AspectJ aspects in a Spring configuration you need to enable Spring support for configuring Spring AOP based on @AspectJ aspects, and __autoproxying__ beans based on whether or not they are advised by those aspects. By autoproxying we mean that if Spring @@ -234,6 +241,7 @@ classpath of your application (version 1.6.8 or later). This library is availabl [[aop-enable-aspectj-java]] ==== Enabling @AspectJ Support with Java configuration + To enable @AspectJ support with Java `@Configuration` add the `@EnableAspectJAutoProxy` annotation: @@ -250,6 +258,7 @@ annotation: [[aop-enable-aspectj-xml]] ==== Enabling @AspectJ Support with XML configuration + To enable @AspectJ support with XML based configuration use the `aop:aspectj-autoproxy` element: @@ -327,6 +336,7 @@ 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 when advice executes. __Spring AOP only supports method execution join points for Spring beans__, so you can think of a pointcut as matching the execution of methods on Spring @@ -359,6 +369,7 @@ et. al. or "AspectJ in Action" by Ramnivas Laddad. [[aop-pointcuts-designators]] ==== Supported Pointcut Designators + Spring AOP supports the following AspectJ pointcut designators (PCD) for use in pointcut expressions: @@ -456,6 +467,7 @@ 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 refer to pointcut expressions by name. The following example shows three pointcut expressions: `anyPublicOperation` (which matches if a method execution join point @@ -485,6 +497,7 @@ __matching__. [[aop-common-pointcuts]] ==== Sharing common pointcut definitions + When working with enterprise applications, you often want to refer to modules of the application and particular sets of operations from within several aspects. We recommend defining a "SystemArchitecture" aspect that captures common pointcut expressions for @@ -579,6 +592,7 @@ transaction elements are discussed in <` 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 your Spring application context. The state and behavior is captured in the fields and methods of the object, and the pointcut and advice information is captured in the XML. @@ -1605,6 +1637,7 @@ 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 definition to be shared across several aspects and advisors. @@ -1724,12 +1757,14 @@ 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 `` using the element. @@ -1777,6 +1812,7 @@ 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 declared inside an `` in the same way as before advice. For example: @@ -1826,6 +1862,7 @@ example, the method signature may be declared as: [[aop-schema-advice-after-throwing]] ==== After throwing advice + After throwing advice executes when a matched method execution exits by throwing an exception. It is declared inside an `` using the after-throwing element: @@ -1875,6 +1912,7 @@ example, the method signature may be declared as: [[aop-schema-advice-after-finally]] ==== After (finally) advice + After (finally) advice runs however a matched method execution exits. It is declared using the `after` element: @@ -1895,6 +1933,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 execution. It has the opportunity to do work both before and after the method executes, and to determine when, how, and even if, the method actually gets to execute at all. @@ -1941,6 +1980,7 @@ The implementation of the `doBasicProfiling` advice would be exactly the same as [[aop-schema-params]] ==== Advice parameters + The schema based declaration style supports fully typed advice in the same way as described for the @AspectJ support - by matching pointcut parameters by name against advice method parameters. See <> for details. If you wish @@ -2078,6 +2118,7 @@ ms % Task name [[aop-ordering]] ==== Advice ordering + When multiple advice needs to execute at the same join point (executing method) the ordering rules are as described in <>. The precedence between aspects is determined by either adding the `Order` annotation to the bean @@ -2087,6 +2128,7 @@ 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 that advised objects implement a given interface, and to provide an implementation of that interface on behalf of those objects. @@ -2143,6 +2185,7 @@ following: [[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. @@ -2150,7 +2193,8 @@ 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 + +The concept of "advisors" is brought forward from the AOP support defined in Spring and does not have a direct equivalent in AspectJ. An advisor is like a small self-contained aspect that has a single piece of advice. The advice itself is represented by a bean, and must implement one of the advice interfaces described in @@ -2192,6 +2236,7 @@ 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 <> looks when rewritten using the schema support. @@ -2318,6 +2363,7 @@ pointcut expression so that only `@Idempotent` operations match: [[aop-choosing]] == Choosing which AOP declaration style to use + Once you have decided that an aspect is the best approach for implementing a given requirement, how do you decide between using Spring AOP or AspectJ, and between the Aspect language (code) style, @AspectJ annotation style, or the Spring XML style? These @@ -2328,6 +2374,7 @@ 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 there is no requirement to introduce the AspectJ compiler / weaver into your development and build processes. If you only need to advise the execution of operations on Spring @@ -2351,6 +2398,7 @@ 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. There are various tradeoffs to consider. @@ -2413,6 +2461,7 @@ 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, schema-defined `` aspects, `` declared advisors and even proxies and interceptors defined using the Spring 1.2 style in the same configuration. @@ -2424,6 +2473,7 @@ 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 target object. (JDK dynamic proxies are preferred whenever you have a choice). @@ -2483,6 +2533,7 @@ 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 what that last statement actually means before you write your own aspects or use any of the Spring AOP-based aspects supplied with the Spring Framework. @@ -2617,6 +2668,7 @@ 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 ``, it is also possible programmatically to create proxies that advise target objects. For the full details of Spring's AOP API, see the next chapter. @@ -2650,6 +2702,7 @@ full information. [[aop-using-aspectj]] == Using AspectJ with Spring applications + Everything we've covered so far in this chapter is pure Spring AOP. In this section, we're going to look at how you can use the AspectJ compiler/weaver instead of, or in addition to, Spring AOP if your needs go beyond the facilities offered by Spring AOP @@ -2667,6 +2720,7 @@ using AspectJ. [[aop-atconfigurable]] === Using AspectJ to dependency inject domain objects with Spring + The Spring container instantiates and configures beans defined in your application context. It is also possible to ask a bean factory to configure a __pre-existing__ object given the name of a bean definition containing the configuration to be applied. @@ -2848,6 +2902,7 @@ 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 AspectJ singleton aspect. The scope of a singleton aspect is the same as the scope of `static` members, that is to say there is one aspect instance per classloader that @@ -2877,6 +2932,7 @@ not what you want. [[aop-ajlib-other]] === Other Spring aspects for AspectJ + In addition to the `@Configurable` aspect, `spring-aspects.jar` contains an AspectJ aspect that can be used to drive Spring's transaction management for types and methods annotated with the `@Transactional` annotation. This is primarily intended for users who @@ -2934,6 +2990,7 @@ fully-qualified class names: [[aop-aj-configure]] === Configuring AspectJ aspects using Spring IoC + When using AspectJ aspects with Spring applications, it is natural to both want and expect to be able to configure such aspects using Spring. The AspectJ runtime itself is responsible for aspect creation, and the means of configuring the AspectJ created @@ -2991,6 +3048,7 @@ 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 application's class files as they are being loaded into the Java virtual machine (JVM). The focus of this section is on configuring and using LTW in the specific context of the @@ -3026,6 +3084,7 @@ https://github.com/spring-projects/spring-petclinic[Petclinic sample application [[aop-aj-ltw-first-example]] ==== A first example + Let us assume that you are an application developer who has been tasked with diagnosing the cause of some performance problems in a system. Rather than break out a profiling tool, what we are going to do is switch on a simple profiling aspect that will enable us @@ -3234,6 +3293,7 @@ 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 either the AspectJ language itself or you can write your aspects in the @AspectJ-style. It means that your aspects are then both valid AspectJ __and__ Spring AOP aspects. @@ -3258,6 +3318,7 @@ 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 for AspectJ LTW: @@ -3272,6 +3333,7 @@ instrumentation>>, you will also need: [[aop-aj-ltw-spring]] ==== Spring configuration + The key component in Spring's LTW support is the `LoadTimeWeaver` interface (in the `org.springframework.instrument.classloading` package), and the numerous implementations of it that ship with the Spring distribution. A `LoadTimeWeaver` is responsible for @@ -3281,7 +3343,6 @@ happens to be the LTW of aspects. [TIP] ==== - If you are unfamiliar with the idea of runtime class file transformation, you are encouraged to read the javadoc API documentation for the `java.lang.instrument` package before continuing. This is not a huge chore because there is - rather annoyingly - @@ -3447,12 +3508,14 @@ It accepts one of three possible values, summarized below, with the default valu [[aop-aj-ltw-environments]] ==== Environment-specific configuration + This last section contains any additional settings and configuration that you will need when using Spring's LTW support in environments such as application servers and web containers. [[aop-aj-ltw-environment-tomcat]] ===== Tomcat + Historically, http://tomcat.apache.org/[Apache Tomcat]'s default class loader did not support class transformation which is why Spring provides an enhanced implementation that addresses this need. Named `TomcatInstrumentableClassLoader`, the loader works on @@ -3503,6 +3566,7 @@ deployed web applications, no matter what ClassLoader they happen to run on. [[aop-aj-ltw-environments-weblogic-oc4j-resin-glassfish-jboss]] ===== WebLogic, WebSphere, Resin, GlassFish, JBoss + Recent versions of WebLogic Server (version 10 and above), IBM WebSphere Application Server (version 7 and above), Resin (3.1 and above) and JBoss (6.x or above) provide a ClassLoader that is capable of local instrumentation. Spring's native LTW leverages such @@ -3526,6 +3590,7 @@ to your artifact a file named `WEB-INF/jboss-scanning.xml` with the following co [[aop-aj-ltw-environment-generic]] ===== Generic Java applications + When class instrumentation is required in environments that do not support or are not supported by the existing `LoadTimeWeaver` implementations, a JDK agent can be the only solution. For such cases, Spring provides `InstrumentationLoadTimeWeaver`, which @@ -3554,6 +3619,7 @@ support) a dedicated LTW. [[aop-resources]] == Further Resources + More information on AspectJ can be found on the http://www.eclipse.org/aspectj[AspectJ website]. @@ -3563,4 +3629,3 @@ comprehensive introduction and reference for the AspectJ language. The book __AspectJ in Action, Second Edition__ by Ramnivas Laddad (Manning, 2009) comes highly recommended; the focus of the book is on AspectJ, but a lot of general AOP themes are explored (in some depth). - diff --git a/src/docs/asciidoc/core/core-appendix.adoc b/src/docs/asciidoc/core/core-appendix.adoc index 83d1af085bb..714af013c59 100644 --- a/src/docs/asciidoc/core/core-appendix.adoc +++ b/src/docs/asciidoc/core/core-appendix.adoc @@ -4,6 +4,8 @@ = Appendix + + [[xsd-schemas]] == XML Schemas @@ -123,7 +125,7 @@ Injecting enum values into beans as either property or constructor arguments is easy to do in Spring, in that you don't actually have to __do__ anything or know anything about the Spring internals (or even about classes such as the `FieldRetrievingFactoryBean`). Let's look at an example to see how easy injecting an -enum value is; consider this JDK 5 enum: +enum value is; consider this enum: [source,java,indent=0] [subs="verbatim,quotes"] @@ -134,7 +136,6 @@ enum value is; consider this JDK 5 enum: TRANSACTION, EXTENDED - } ---- @@ -152,7 +153,6 @@ Now consider a setter of type `PersistenceContextType`: public void setPersistenceContextType(PersistenceContextType type) { this.persistenceContextType = type; } - } ---- @@ -162,14 +162,10 @@ Now consider a setter of type `PersistenceContextType`: [subs="verbatim,quotes"] ---- - + ---- -This works for classic type-safe emulated enums (on JDK 1.4 and JDK 1.3) as well; Spring -will automatically attempt to match the string property value to a constant on the enum -class. - [[xsd-schemas-util-property-path]] ==== @@ -786,14 +782,14 @@ The `NamespaceHandler` interface is pretty simple in that it features just three * `init()` - allows for initialization of the `NamespaceHandler` and will be called by Spring before the handler is used * `BeanDefinition parse(Element, ParserContext)` - called when Spring encounters a - top-level element (not nested inside a bean definition or a different namespace). This - method can register bean definitions itself and/or return a bean definition. + top-level element (not nested inside a bean definition or a different namespace). + This method can register bean definitions itself and/or return a bean definition. * `BeanDefinitionHolder decorate(Node, BeanDefinitionHolder, ParserContext)` - called - when Spring encounters an attribute or nested element of a different namespace. The - decoration of one or more bean definitions is used for example with - the<>. We'll start by - highlighting a simple example, without using decoration, after which we will show - decoration in a somewhat more advanced example. + when Spring encounters an attribute or nested element of a different namespace. + The decoration of one or more bean definitions is used for example with the + <>. + We'll start by highlighting a simple example, without using decoration, after which + we will show decoration in a somewhat more advanced example. Although it is perfectly possible to code your own `NamespaceHandler` for the entire namespace (and hence provide code that parses each and every element in the namespace), @@ -1373,4 +1369,3 @@ http\://www.foo.com/schema/jcache=com.foo.JCacheNamespaceHandler # in 'META-INF/spring.schemas' http\://www.foo.com/schema/jcache/jcache.xsd=com/foo/jcache.xsd ---- - diff --git a/src/docs/asciidoc/core/core-beans.adoc b/src/docs/asciidoc/core/core-beans.adoc index 6a95ee95e31..07410c41464 100644 --- a/src/docs/asciidoc/core/core-beans.adoc +++ b/src/docs/asciidoc/core/core-beans.adoc @@ -2,6 +2,8 @@ = The IoC container + + [[beans-introduction]] == Introduction to the Spring IoC container and beans @@ -400,6 +402,7 @@ a dependency on a specific bean through metadata (e.g. an autowiring annotation) [[beans-definition]] == Bean overview + A Spring IoC container manages one or more __beans__. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML `` definitions. @@ -778,6 +781,7 @@ Spring container that will create objects through an [[beans-dependencies]] == Dependencies + A typical enterprise application does not consist of a single object (or bean in the Spring parlance). Even the simplest application has a few objects that work together to present what the end-user sees as a coherent application. This next section explains how @@ -2380,6 +2384,7 @@ 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 of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you can create many object @@ -3602,6 +3607,7 @@ 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 arguments, property values, and container-specific information such as initialization method, static factory method name, and so on. A child bean definition inherits @@ -3687,6 +3693,7 @@ 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` implementation classes. Instead, the Spring IoC container can be extended by plugging in implementations of special integration interfaces. The next few sections describe these @@ -5173,6 +5180,7 @@ 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 produces each `BeanDefinition` within the Spring container. The previous section (<>) demonstrates how to provide a lot of the configuration @@ -5299,6 +5307,7 @@ https://github.com/spring-projects/spring-framework/wiki/Spring-Annotation-Progr wiki page. + [[beans-scanning-autodetection]] === Automatically detecting classes and registering bean definitions @@ -5839,6 +5848,7 @@ metadata is provided per-instance rather than per-class. [[beans-scanning-index]] === Generating an index of candidate components + While classpath scanning is very fast, it is possible to improve the startup performance of large applications by creating a static list of candidates at compilation time. In this mode, _all modules_ of the application must use this mechanism as, when the @@ -5893,8 +5903,10 @@ classpath. + [[beans-standard-annotations]] == Using JSR 330 Standard Annotations + Starting with Spring 3.0, Spring offers support for JSR-330 standard annotations (Dependency Injection). Those annotations are scanned in the same way as the Spring annotations. You just need to have the relevant jars in your classpath. @@ -6742,6 +6754,7 @@ annotation can be used: ---- + [[beans-java-configuration-annotation]] === Using the @Configuration annotation @@ -7979,7 +7992,7 @@ AspectJ load-time weaving, see <>. [[context-introduction]] -== Additional Capabilities of the ApplicationContext +== Additional capabilities of the ApplicationContext As was discussed in the chapter introduction, the `org.springframework.beans.factory` package provides basic functionality for managing and manipulating beans, including in a @@ -8211,7 +8224,7 @@ out the `ReloadableResourceBundleMessageSource` javadocs for details. [[context-functionality-events]] -=== Standard and Custom Events +=== Standard and custom events Event handling in the `ApplicationContext` is provided through the `ApplicationEvent` class and `ApplicationListener` interface. If a bean that implements the @@ -8400,8 +8413,9 @@ http://www.enterpriseintegrationpatterns.com[pattern-oriented], event-driven architectures that build upon the well-known Spring programming model. ==== + [[context-functionality-events-annotation]] -==== Annotation-based Event Listeners +==== Annotation-based event listeners As of Spring 4.2, an event listener can be registered on any public method of a managed bean via the `EventListener` annotation. The `BlackListNotifier` can be rewritten as @@ -8508,6 +8522,7 @@ This new method will publish a new `ListUpdateEvent` for every `BlackListEvent` by the method above. If you need to publish several events, just return a `Collection` of events instead. + [[context-functionality-events-async]] ==== Asynchronous Listeners @@ -8534,7 +8549,7 @@ Be aware of the following limitations when using asynchronous events: [[context-functionality-events-order]] -==== Ordering Listeners +==== Ordering listeners If you need the listener to be invoked before another one, just add the `@Order` annotation to the method declaration: @@ -8549,8 +8564,9 @@ annotation to the method declaration: } ---- + [[context-functionality-events-generics]] -==== Generic Events +==== Generic events You may also use generics to further define the structure of your event. Consider an `EntityCreatedEvent` where `T` is the type of the actual entity that got created. You @@ -8716,14 +8732,15 @@ 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 only used directly in integration with other third-party frameworks and is now largely historical in nature for most users of Spring. The `BeanFactory` and related interfaces, such as `BeanFactoryAware`, `InitializingBean`, `DisposableBean`, are still present in Spring for the purposes of backward compatibility with the large number of third-party frameworks that integrate with Spring. Often third-party components that can not use -more modern equivalents such as `@PostConstruct` or `@PreDestroy` in order to remain -compatible with JDK 1.4 or to avoid a dependency on JSR-250. +more modern equivalents such as `@PostConstruct` or `@PreDestroy` in order to avoid a +dependency on JSR-250. This section provides additional background into the differences between the `BeanFactory` and `ApplicationContext` and how one might access the IoC container diff --git a/src/docs/asciidoc/core/core-expressions.adoc b/src/docs/asciidoc/core/core-expressions.adoc index 9b498700fe0..b7de9c177ce 100644 --- a/src/docs/asciidoc/core/core-expressions.adoc +++ b/src/docs/asciidoc/core/core-expressions.adoc @@ -6,6 +6,7 @@ [[expressions-intro]] == Introduction + The Spring Expression Language (SpEL for short) is a powerful expression language that supports querying and manipulating an object graph at runtime. The language syntax is similar to Unified EL but offers additional features, most notably method invocation and @@ -39,7 +40,8 @@ populate them are listed at the end of the chapter. [[expressions-features]] -== Feature Overview +== Feature overview + The expression language supports the following functionality * Literal expressions @@ -66,7 +68,8 @@ The expression language supports the following functionality [[expressions-evaluation]] -== Expression Evaluation using Spring's Expression Interface +== Expression evaluation using Spring's Expression interface + This section introduces the simple use of SpEL interfaces and its expression language. The complete language reference can be found in the section <>. @@ -235,6 +238,7 @@ Inventor object in the previous example. [[expressions-evaluation-context]] === The EvaluationContext interface + The interface `EvaluationContext` is used when evaluating an expression to resolve properties, methods, fields, and to help perform type conversion. The out-of-the-box implementation, `StandardEvaluationContext`, uses reflection to manipulate the object, @@ -253,7 +257,8 @@ evaluates expressions. Please refer to the javadoc of these classes for more det [[expressions-type-conversion]] -==== Type Conversion +==== Type conversion + By default SpEL uses the conversion service available in Spring core ( `org.springframework.core.convert.ConversionService`). This conversion service comes with many converters built in for common conversions but is also fully extensible so @@ -288,9 +293,12 @@ being placed in it. A simple example: Boolean b = simple.booleanList.get(0); ---- + + [[expressions-parser-configuration]] === Parser configuration -It is possible to configure the SpEL expression parser using a parser configuration object + +It is possible to configure the SpEL expression parser using a parser configuration object (`org.springframework.expression.spel.SpelParserConfiguration`). The configuration object controls the behavior of some of the expression components. For example, if indexing into an array or collection and the element at the specified index is `null` @@ -325,6 +333,8 @@ list it is possible to automatically grow the array or list to accommodate that It is also possible to configure the behaviour of the SpEL expression compiler. + + [[expressions-spel-compilation]] === SpEL compilation @@ -356,6 +366,7 @@ gain can be very noticeable. In an example micro benchmark run of 50000 iteratio taking 75ms to evaluate using only the interpreter and just 3ms using the compiled version of the expression. + [[expressions-compiler-configuration]] ==== Compiler configuration @@ -415,6 +426,7 @@ In these cases it is possible to use a system property. The property `spring.expression.compiler.mode` can be set to one of the `SpelCompilerMode` enum values (`off`, `immediate`, or `mixed`). + [[expressions-compiler-limitations]] ==== Compiler limitations @@ -430,8 +442,12 @@ at the moment: More and more types of expression will be compilable in the future. + + + [[expressions-beandef]] == Expression support for defining bean definitions + SpEL expressions can be used with XML or annotation-based configuration metadata for defining ``BeanDefinition``s. In both cases the syntax to define the expression is of the form `#{ }`. @@ -440,6 +456,7 @@ form `#{ }`. [[expressions-beandef-xml-based]] === XML based configuration + A property or constructor-arg value can be set using expressions as shown below. [source,xml,indent=0] @@ -488,6 +505,7 @@ 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 parameters to specify a default value. @@ -584,6 +602,7 @@ Autowired methods and constructors can also use the `@Value` annotation. [[expressions-ref-literal]] === Literal expressions + The types of literal expressions supported are strings, numeric values (int, real, hex), boolean and null. Strings are delimited by single quotes. To put a single quote itself in a string, use two single quote characters. @@ -617,6 +636,7 @@ 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 property value. The instances of the `Inventor` class, pupin, and tesla, were populated with data listed in the section <>. @@ -685,6 +705,7 @@ string literals. [[expressions-inline-lists]] === Inline lists + Lists can be expressed directly in an expression using `{}` notation. [source,java,indent=0] @@ -700,8 +721,11 @@ Lists can be expressed directly in an expression using `{}` notation. 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-inline-maps]] === Inline Maps + Maps can also be expressed directly in an expression using `{key:value}` notation. [source,java,indent=0] @@ -717,8 +741,11 @@ of fixed literals or other nested constant structures (lists or maps) then a con to represent the expression, rather than building a new map on each evaluation. Quoting of the map keys is optional, the examples above are not using quoted keys. + + [[expressions-array-construction]] === Array construction + Arrays can be built using the familiar Java syntax, optionally supplying an initializer to have the array populated at construction time. @@ -741,6 +768,7 @@ multi-dimensional array. [[expressions-methods]] === Methods + Methods are invoked using typical Java programming syntax. You may also invoke methods on literals. Varargs are also supported. @@ -763,6 +791,7 @@ on literals. Varargs are also supported. [[expressions-operators-relational]] ==== Relational operators + The relational operators; equal, not equal, less than, less than or equal, greater than, and greater than or equal are supported using standard operator notation. @@ -825,6 +854,7 @@ shown here: `lt` (`<`), `gt` (`>`), `le` (`<=`), `ge` (`>=`), `eq` (`==`), [[expressions-operators-logical]] ==== Logical operators + The logical operators that are supported are and, or, and not. Their use is demonstrated below. @@ -862,6 +892,7 @@ below. [[expressions-operators-mathematical]] ==== Mathematical operators + The addition operator can be used on both numbers and strings. Subtraction, multiplication and division can be used only on numbers. Other mathematical operators supported are modulus (%) and exponential power (^). Standard operator precedence is enforced. These @@ -904,6 +935,7 @@ operators are demonstrated below. [[expressions-assignment]] === Assignment + Setting of a property is done by using the assignment operator. This would typically be done within a call to `setValue` but can also be done inside a call to `getValue`. @@ -925,6 +957,7 @@ done within a call to `setValue` but can also be done inside a call to `getValue [[expressions-types]] === Types + The special `T` operator can be used to specify an instance of java.lang.Class (the _type_). Static methods are invoked using this operator as well. The `StandardEvaluationContext` uses a `TypeLocator` to find types and the @@ -948,6 +981,7 @@ fully qualified, but all other type references must be. [[expressions-constructors]] === Constructors + Constructors can be invoked using the new operator. The fully qualified class name should be used for all but the primitive type and String (where int, float, etc, can be used). @@ -969,6 +1003,7 @@ used). [[expressions-ref-variables]] === Variables + Variables can be referenced in the expression using the syntax `#variableName`. Variables are set using the method setVariable on the `StandardEvaluationContext`. @@ -987,6 +1022,7 @@ are set using the method setVariable on the `StandardEvaluationContext`. [[expressions-this-root]] ==== The #this and #root variables + The variable #this is always defined and refers to the current evaluation object (against which unqualified references are resolved). The variable #root is always defined and refers to the root context object. Although #this may vary as components of @@ -1014,6 +1050,7 @@ an expression are evaluated, #root always refers to the root. [[expressions-ref-functions]] === Functions + You can extend SpEL by registering user defined functions that can be called within the expression string. The function is registered with the `StandardEvaluationContext` using the method. @@ -1062,6 +1099,7 @@ expression string. [[expressions-bean-references]] === Bean references + If the evaluation context has been configured with a bean resolver it is possible to lookup beans from an expression using the (@) symbol. @@ -1092,6 +1130,7 @@ To access a factory bean itself, the bean name should instead be prefixed with a [[expressions-operator-ternary]] === Ternary Operator (If-Then-Else) + You can use the ternary operator for performing if-then-else conditional logic inside the expression. A minimal example is: @@ -1126,6 +1165,7 @@ ternary operator. [[expressions-operator-elvis]] === The Elvis Operator + The Elvis operator is a shortening of the ternary operator syntax and is used in the http://www.groovy-lang.org/operators.html#_elvis_operator[Groovy] language. With the ternary operator syntax you usually have to repeat a variable twice, for @@ -1175,6 +1215,7 @@ Here is a more complex example. [[expressions-operator-safe-navigation]] === Safe Navigation operator + The Safe Navigation operator is used to avoid a `NullPointerException` and comes from the http://www.groovy-lang.org/operators.html#_safe_navigation_operator[Groovy] language. Typically when you have a reference to an object you might need to verify that @@ -1219,6 +1260,7 @@ 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 source collection into another by selecting from its entries. @@ -1256,6 +1298,7 @@ first or the last value. To obtain the first entry matching the selection the sy [[expressions-collection-projection]] === Collection Projection + Projection allows a collection to drive the evaluation of a sub-expression and the result is a new collection. The syntax for projection is `![projectionExpression]`. Most easily understood by example, suppose we have a list of inventors but want the list of @@ -1278,6 +1321,7 @@ expression against each map entry. [[expressions-templating]] === Expression templating + Expression templates allow a mixing of literal text with one or more evaluation blocks. Each evaluation block is delimited with prefix and suffix characters that you can define, a common choice is to use `#{ }` as the delimiters. For example, @@ -1323,6 +1367,7 @@ The definition of `TemplateParserContext` is shown below. [[expressions-example-classes]] == Classes used in the examples + Inventor.java [source,java,indent=0] diff --git a/src/docs/asciidoc/core/core-null-safety.adoc b/src/docs/asciidoc/core/core-null-safety.adoc index a2603a706ea..a32cc584a8a 100644 --- a/src/docs/asciidoc/core/core-null-safety.adoc +++ b/src/docs/asciidoc/core/core-null-safety.adoc @@ -28,6 +28,9 @@ scope of this feature. Libraries like Reactor or Spring Data provide null-safe APIs leveraging this feature. ==== + + + == Use cases In addition to providing an explicit declaration for Spring Framework API nullability, diff --git a/src/docs/asciidoc/core/core-resources.adoc b/src/docs/asciidoc/core/core-resources.adoc index 9c10c61fedb..c56eae53935 100644 --- a/src/docs/asciidoc/core/core-resources.adoc +++ b/src/docs/asciidoc/core/core-resources.adoc @@ -1,10 +1,12 @@ - [[resources]] = Resources + + [[resources-introduction]] == Introduction + Java's standard `java.net.URL` class and standard handlers for various URL prefixes unfortunately are not quite adequate enough for all access to low-level resources. For example, there is no standardized `URL` implementation that may be used to access a @@ -15,6 +17,8 @@ quite complicated, and the `URL` interface still lacks some desirable functional such as a method to check for the existence of the resource being pointed to. + + [[resources-resource]] == The Resource interface @@ -378,6 +382,7 @@ used. The following two examples show how to force a `ClassPathResource` and a [[resources-app-ctx-construction]] === Constructing application contexts + An application context constructor (for a specific application context type) generally takes a string or array of strings as the location path(s) of the resource(s) such as XML files that make up the definition of the context. @@ -461,6 +466,7 @@ on 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 shown above) which has a one-to-one mapping to a target Resource, or alternately may contain the special "classpath*:" prefix and/or internal Ant-style regular expressions @@ -481,6 +487,7 @@ 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: [literal] @@ -503,6 +510,7 @@ the wildcards. [[resources-app-ctx-portability]] ===== Implications on portability + If the specified path is already a file URL (either explicitly, or implicitly because the base `ResourceLoader` is a filesystem one, then wildcarding is guaranteed to work in a completely portable fashion. @@ -525,7 +533,7 @@ environment before you rely on it. [[resources-classpath-wildcards]] -==== The Classpath*: portability classpath*: prefix +==== The classpath*: prefix When constructing an XML-based application context, a location string may use the special `classpath*:` prefix: @@ -565,6 +573,7 @@ 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 reliably with at least one root directory before the pattern starts, unless the actual target files reside in the file system. This means that a pattern like @@ -681,4 +690,3 @@ just force the use of a `UrlResource`, by using the `file:` URL prefix. ApplicationContext ctx = new FileSystemXmlApplicationContext("file:///conf/context.xml"); ---- - diff --git a/src/docs/asciidoc/core/core-validation.adoc b/src/docs/asciidoc/core/core-validation.adoc index f181c6e8103..dd47b8c2d1d 100644 --- a/src/docs/asciidoc/core/core-validation.adoc +++ b/src/docs/asciidoc/core/core-validation.adoc @@ -2,6 +2,8 @@ = Validation, Data Binding, and Type Conversion + + [[validation-introduction]] == Introduction @@ -169,6 +171,7 @@ methods it offers can be found in the javadocs. [[validation-conversion]] == Resolving codes to error messages + We've talked about databinding and validation. Outputting messages corresponding to validation errors is the last thing we need to discuss. In the example we've shown above, we rejected the `name` and the `age` field. If we're going to output the error @@ -225,6 +228,7 @@ 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 `getPropertyValue(s)` methods that both come with a couple of overloaded variants. They're all described in more detail in the javadocs Spring comes with. What's important @@ -698,6 +702,7 @@ registration code to be encapsulated in a class and then shared amongst as many [[core-convert]] == Spring Type Conversion + Spring 3 introduces a `core.convert` package that provides a general type conversion system. The system defines an SPI to implement type conversion logic, as well as an API to execute type conversions at runtime. Within a Spring container, this system can be @@ -709,6 +714,7 @@ application where type conversion is needed. [[core-convert-Converter-API]] === Converter SPI + The SPI to implement type conversion logic is simple and strongly typed: [source,java,indent=0] @@ -756,6 +762,7 @@ Consider `StringToInteger` as an example for a typical `Converter` implementatio [[core-convert-ConverterFactory-SPI]] === ConverterFactory + When you need to centralize the conversion logic for an entire class hierarchy, for example, when converting from String to java.lang.Enum objects, implement `ConverterFactory`: @@ -808,6 +815,7 @@ Consider the `StringToEnum` ConverterFactory as an example: [[core-convert-GenericConverter-SPI]] === GenericConverter + When you require a sophisticated Converter implementation, consider the GenericConverter interface. With a more flexible but less strongly typed signature, a GenericConverter supports converting between multiple source and target types. In addition, a @@ -850,6 +858,7 @@ Favor Converter or ConverterFactory for basic type conversion needs. [[core-convert-ConditionalGenericConverter-SPI]] ==== ConditionalGenericConverter + Sometimes you only want a `Converter` to execute if a specific condition holds true. For example, you might only want to execute a `Converter` if a specific annotation is present on the target field. Or you might only want to execute a `Converter` if a specific method, @@ -882,6 +891,7 @@ might only match if the target entity type declares a static finder method e.g. [[core-convert-ConversionService-API]] === ConversionService API + The ConversionService defines a unified API for executing type conversion logic at runtime. Converters are often executed behind this facade interface: @@ -916,6 +926,7 @@ creating common ConversionService configurations. [[core-convert-Spring-config]] === Configuring a ConversionService + A ConversionService is a stateless object designed to be instantiated at application startup, then shared between multiple threads. In a Spring application, you typically configure a ConversionService instance per Spring container (or ApplicationContext). @@ -968,6 +979,7 @@ In certain situations you may wish to apply formatting during conversion. See [[core-convert-programmatic-usage]] === Using a ConversionService programmatically + To work with a ConversionService instance programmatically, simply inject a reference to it like you would for any other bean: @@ -1021,6 +1033,7 @@ no need to create a specific converter to convert from a `Collection` of `S` to [[format]] == Spring Field Formatting + As discussed in the previous section, <> is a general-purpose type conversion system. It provides a unified ConversionService API as well as a strongly-typed Converter SPI for implementing conversion logic from one type @@ -1048,6 +1061,7 @@ 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: [source,java,indent=0] @@ -1139,6 +1153,7 @@ https://jira.spring.io/browse/SPR[jira.spring.io] to contribute. [[format-CustomFormatAnnotations]] === Annotation-driven Formatting + As you will see, field formatting can be configured by field type or annotation. To bind an Annotation to a formatter, implement AnnotationFormatterFactory: @@ -1222,6 +1237,7 @@ To trigger formatting, simply annotate fields with @NumberFormat: [[format-annotations-api]] ==== Format Annotation API + A portable format annotation API exists in the `org.springframework.format.annotation` package. Use @NumberFormat to format java.lang.Number fields. Use @DateTimeFormat to format java.util.Date, java.util.Calendar, java.util.Long, or Joda Time fields. @@ -1244,6 +1260,7 @@ The example below uses @DateTimeFormat to format a java.util.Date as a ISO Date [[format-FormatterRegistry-SPI]] === FormatterRegistry SPI + The FormatterRegistry is an SPI for registering formatters and converters. `FormattingConversionService` is an implementation of FormatterRegistry suitable for most environments. This implementation may be configured programmatically or @@ -1283,6 +1300,7 @@ 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 FormatterRegistry: @@ -1317,6 +1335,7 @@ See <> in the Spring [[format-configuring-formatting-globaldatetimeformat]] == Configuring a global date & time format + By default, date and time fields that are not annotated with `@DateTimeFormat` are converted from strings using the `DateFormat.SHORT` style. If you prefer, you can change this by defining your own global format. @@ -1411,6 +1430,7 @@ See <> for details. [[validation-beanvalidation]] == Spring Validation + Spring 3 introduces several enhancements to its validation support. First, the JSR-303 Bean Validation API is now fully supported. Second, when used programmatically, Spring's DataBinder can now validate objects as well as bind to them. Third, Spring MVC now has @@ -1420,6 +1440,7 @@ 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 platform. Using this API, you annotate domain model properties with declarative validation constraints and the runtime enforces them. There are a number of built-in @@ -1466,6 +1487,7 @@ bean, keep reading. [[validation-beanvalidation-spring]] === Configuring a Bean Validation Provider + Spring provides full support for the Bean Validation API. This includes convenient support for bootstrapping a JSR-303/JSR-349 Bean Validation provider as a Spring bean. This allows for a `javax.validation.ValidatorFactory` or `javax.validation.Validator` to @@ -1487,6 +1509,7 @@ 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 `javax.validation.Validator`, as well as Spring's `org.springframework.validation.Validator`. You may inject a reference to either of @@ -1527,6 +1550,7 @@ the Spring Validation API: [[validation-beanvalidation-spring-constraints]] ==== Configuring Custom Constraints + Each Bean Validation constraint consists of two parts. First, a `@Constraint` annotation that declares the constraint and its configurable properties. Second, an implementation of the `javax.validation.ConstraintValidator` interface that implements the constraint's @@ -1572,6 +1596,7 @@ As you can see, a ConstraintValidator implementation may have its dependencies [[validation-beanvalidation-spring-method]] ==== Spring-driven Method Validation + The method validation feature supported by Bean Validation 1.1, and as a custom extension also by Hibernate Validator 4.3, can be integrated into a Spring context through a `MethodValidationPostProcessor` bean definition: @@ -1590,6 +1615,7 @@ for setup details with Hibernate Validator and Bean Validation 1.1 providers. [[validation-beanvalidation-spring-other]] ==== Additional Configuration Options + The default `LocalValidatorFactoryBean` configuration should prove sufficient for most cases. There are a number of configuration options for various Bean Validation constructs, from message interpolation to traversal resolution. See the @@ -1599,6 +1625,7 @@ constructs, from message interpolation to traversal resolution. See the [[validation-binder]] === Configuring a DataBinder + Since Spring 3, a DataBinder instance can be configured with a Validator. Once configured, the Validator may be invoked by calling `binder.validate()`. Any validation Errors are automatically added to the binder's BindingResult. @@ -1634,4 +1661,3 @@ locally on a DataBinder instance. See <>. === Spring MVC 3 Validation See <> in the Spring MVC chapter. - diff --git a/src/docs/asciidoc/data-access-appendix.adoc b/src/docs/asciidoc/data-access-appendix.adoc index 54bcd2a22db..e87b5c80805 100644 --- a/src/docs/asciidoc/data-access-appendix.adoc +++ b/src/docs/asciidoc/data-access-appendix.adoc @@ -1,11 +1,14 @@ = Appendix + + [[xsd-schemas]] == XML Schemas This part of the appendix lists XML schemas for data access. + [[xsd-schemas-tx]] === The `tx` schema diff --git a/src/docs/asciidoc/data-access.adoc b/src/docs/asciidoc/data-access.adoc index 075ba324d37..c190cd9324e 100644 --- a/src/docs/asciidoc/data-access.adoc +++ b/src/docs/asciidoc/data-access.adoc @@ -13,12 +13,17 @@ Spring's comprehensive transaction management support is covered in some detail, followed by thorough coverage of the various data access frameworks and technologies that the Spring Framework integrates with. + + + [[transaction]] == Transaction Management + [[transaction-intro]] === Introduction to Spring Framework transaction management + Comprehensive transaction support is among the most compelling reasons to use the Spring Framework. The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits: @@ -53,9 +58,9 @@ server integration, and solutions to common problems.) - [[transaction-motivation]] === Advantages of the Spring Framework's transaction support model + Traditionally, Java EE developers have had two choices for transaction management: __global__ or __local__ transactions, both of which have profound limitations. Global and local transaction management is reviewed in the next two sections, followed by a @@ -63,9 +68,9 @@ discussion of how the Spring Framework's transaction management support addresse limitations of the global and local transaction models. - [[transaction-global]] ==== Global transactions + Global transactions enable you to work with multiple transactional resources, typically relational databases and message queues. The application server manages global transactions through the JTA, which is a cumbersome API to use (partly due to its @@ -86,9 +91,9 @@ negatives of EJB in general are so great that this is not an attractive proposit 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 connection. Local transactions may be easier to use, but have significant disadvantages: they cannot work across multiple transactional resources. For example, code that manages @@ -99,7 +104,6 @@ single transaction resource.) Another downside is that local transactions are in to the programming model. - [[transaction-programming-model]] ==== Spring Framework's consistent programming model @@ -144,9 +148,9 @@ 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 strategy__. A transaction strategy is defined by the `org.springframework.transaction.PlatformTransactionManager` interface: @@ -370,9 +374,9 @@ 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 linked to related resources that need to be synchronized to transactions (for example `DataSourceTransactionManager` to a JDBC `DataSource`, `HibernateTransactionManager` to @@ -383,9 +387,9 @@ also discusses how transaction synchronization is triggered (optionally) through relevant `PlatformTransactionManager`. - [[tx-resource-synchronization-high]] ==== High-level synchronization approach + The preferred approach is to use Spring's highest level template based persistence integration APIs or to use native ORM APIs with transaction- aware factory beans or proxies for managing the native resource factories. These transaction-aware solutions @@ -397,9 +401,9 @@ for JDBC access by using the `JdbcTemplate`. These solutions are detailed in sub chapters of this reference documentation. - [[tx-resource-synchronization-low]] ==== Low-level synchronization approach + Classes such as `DataSourceUtils` (for JDBC), `EntityManagerFactoryUtils` (for JPA), `SessionFactoryUtils` (for Hibernate), and so on exist at a lower level. When you want the application code to deal directly with the resource types of the native persistence APIs, @@ -438,7 +442,6 @@ with the relevant APIs. For example, if you use the Spring `JdbcTemplate` or behind the scenes and you won't need to write any special code. - [[tx-resource-synchronization-tadsp]] ==== TransactionAwareDataSourceProxy @@ -455,9 +458,9 @@ abstractions mentioned above. - [[transaction-declarative]] === Declarative transaction management + [NOTE] ==== Most Spring Framework users choose declarative transaction management. This option has @@ -521,9 +524,9 @@ declarative transaction management follows EJB convention (roll back is automati 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 `@Transactional` annotation, add `@EnableTransactionManagement` to your configuration, and then expect you to understand how it all works. This section explains the inner @@ -548,9 +551,9 @@ 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 `Foo` and `Bar` classes as placeholders so that you can concentrate on the transaction usage without focusing on a particular domain model. For the purposes of this example, @@ -775,9 +778,9 @@ insertFoo(..) method of the DefaultFooService class have been truncated for clar ---- - [[transaction-declarative-rolling-back]] ==== Rolling back a declarative transaction + The previous section outlined the basics of how to specify transactional settings for classes, typically service layer classes, declaratively in your application. This section describes how you can control the rollback of transactions in a simple @@ -865,9 +868,9 @@ possible. Programmatic rollback is available should you absolutely need it, but 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 apply a __totally different__ transactional configuration to each of them. You do this by defining distinct `` elements with differing `pointcut` and @@ -981,7 +984,6 @@ transactional settings. ---- - [[transaction-declarative-txadvice-settings]] ==== settings @@ -1045,7 +1047,6 @@ that are nested within `` and `` tags are summarized |=== - [[transaction-declarative-annotations]] ==== Using @Transactional @@ -1267,7 +1268,6 @@ precedence over the transactional settings defined at the class level. } ---- - [[transaction-declarative-attransactional-settings]] ===== @Transactional settings @@ -1336,9 +1336,9 @@ 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 situations where you want multiple independent transaction managers in a single application. The value attribute of the `@Transactional` annotation can be used to @@ -1383,9 +1383,9 @@ 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 different methods, then <> allows you to define custom shortcut annotations for your specific use cases. For example, @@ -1426,9 +1426,9 @@ 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 that this section is not an introduction to transaction propagation proper; rather it details some of the semantics regarding transaction propagation in Spring. @@ -1436,9 +1436,9 @@ 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[] PROPAGATION_REQUIRED @@ -1462,9 +1462,9 @@ 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[] PROPAGATION_REQUIRES_NEW @@ -1475,9 +1475,9 @@ 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 that it can roll back to. Such partial rollbacks allow an inner transaction scope to trigger a rollback __for its scope__, with the outer transaction being able to continue @@ -1486,9 +1486,9 @@ 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. How do you effect this in the context of ``? @@ -1666,7 +1666,6 @@ order value. You configure additional aspects in similar fashion. - [[transaction-declarative-aspectj]] ==== Using @Transactional with AspectJ @@ -1721,9 +1720,9 @@ AspectJ in the Spring Framework>> for a discussion of load-time weaving with Asp - [[transaction-programmatic]] === Programmatic transaction management + The Spring Framework provides two means of programmatic transaction management: * Using the `TransactionTemplate`. @@ -1734,7 +1733,6 @@ 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 @@ -1818,9 +1816,9 @@ Code within the callback can roll the transaction back by calling the }); ---- - [[tx-prog-template-settings]] ===== Specifying transaction settings + You can specify transaction settings such as the propagation mode, the isolation level, the timeout, and so forth on the `TransactionTemplate` either programmatically or in configuration. `TransactionTemplate` instances by default have the @@ -1869,7 +1867,6 @@ different settings (for example, a different isolation level), then you need to two distinct `TransactionTemplate` instances. - [[transaction-programmatic-ptm]] ==== Using the PlatformTransactionManager @@ -1900,9 +1897,9 @@ transactions, roll back, and commit. - [[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 number of transactional operations. For example, if you have a web application that require transactions only for certain update operations, you may not want to set up @@ -1917,6 +1914,8 @@ 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-event]] === Transaction bound event @@ -1955,8 +1954,11 @@ If no transaction is running, the listener is not invoked at all since we can't semantics. It is however possible to override that behaviour by setting the `fallbackExecution` attribute of the annotation to `true`. + + [[transaction-application-server-integration]] === Application server-specific integration + Spring's transaction abstraction generally is application server agnostic. Additionally, Spring's `JtaTransactionManager` class, which can optionally perform a JNDI lookup for the JTA `UserTransaction` and `TransactionManager` objects, autodetects the location for @@ -1981,9 +1983,9 @@ 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 `WebSphereUowTransactionManager`. This special adapter leverages IBM's `UOWManager` API, which is available in WebSphere Application Server 6.1.0.9 and later. With this adapter, @@ -1991,9 +1993,9 @@ 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 `WebLogicJtaTransactionManager` instead of the stock `JtaTransactionManager` class. This special WebLogic-specific subclass of the normal `JtaTransactionManager` supports the @@ -2003,12 +2005,10 @@ per-transaction isolation levels, and proper resuming of transactions in all cas - [[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 @@ -2025,9 +2025,9 @@ treats them as errors. - [[transaction-resources]] === Further Resources + For more information about the Spring Framework's transaction support: * http://www.javaworld.com/javaworld/jw-01-2009/jw-01-spring-transactions.html[Distributed @@ -2041,12 +2041,15 @@ For more information about the Spring Framework's transaction support: + [[dao]] == DAO support + [[dao-introduction]] === Introduction + The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JPA in a consistent way. This allows one to switch between the aforementioned persistence technologies fairly easily @@ -2055,9 +2058,9 @@ specific to each technology. - [[dao-exceptions]] === Consistent exception hierarchy + Spring provides a convenient translation from technology-specific exceptions like `SQLException` to its own exception class hierarchy with the `DataAccessException` as the root exception. These exceptions wrap the original exception so there is never any @@ -2090,9 +2093,9 @@ image::images/DataAccessException.png[] - [[dao-annotations]] === Annotations used for configuring DAO or Repository classes + The best way to guarantee that your Data Access Objects (DAOs) or repositories provide exception translation is to use the `@Repository` annotation. This annotation also allows the component scanning support to find and configure your DAOs and repositories @@ -2179,12 +2182,15 @@ 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 the sequence of actions outlined in the table below. The table shows what actions Spring will take care of and which actions are the responsibility of you, the application @@ -2240,9 +2246,9 @@ The Spring Framework takes care of all the low-level details that can make JDBC 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. In addition to three flavors of the JdbcTemplate, a new SimpleJdbcInsert and SimplejdbcCall approach optimizes database metadata, and the RDBMS Object style takes a @@ -2269,9 +2275,9 @@ advanced features require a JDBC 3.0 driver. 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, namely `core`, `datasource`, `object`, and `support`. @@ -2306,12 +2312,10 @@ 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 @@ -2350,12 +2354,14 @@ corresponding to the fully qualified class name of the template instance (typica [[jdbc-JdbcTemplate-examples]] ===== Examples of JdbcTemplate class usage + This section provides some examples of `JdbcTemplate` class usage. These examples are not an exhaustive list of all of the functionality exposed by the `JdbcTemplate`; see the attendant javadocs for that. [[jdbc-JdbcTemplate-examples-query]] ====== Querying (SELECT) + Here is a simple query for getting the number of rows in a relation: [source,java,indent=0] @@ -2444,6 +2450,7 @@ last code snippet as follows: [[jdbc-JdbcTemplate-examples-update]] ====== Updating (INSERT/UPDATE/DELETE) with jdbcTemplate + You use the `update(..)` method to perform insert, update and delete operations. Parameter values are usually provided as var args or alternatively as an object array. @@ -2473,6 +2480,7 @@ Parameter values are usually provided as var args or alternatively as an object [[jdbc-JdbcTemplate-examples-other]] ====== Other jdbcTemplate operations + You can use the `execute(..)` method to execute any arbitrary SQL, and as such the method is often used for DDL statements. It is heavily overloaded with variants taking callback interfaces, binding variable arrays, and so on. @@ -2494,7 +2502,6 @@ procedure support is <>. Long.valueOf(unionId)); ---- - [[jdbc-JdbcTemplate-idioms]] ===== JdbcTemplate best practices @@ -2621,7 +2628,6 @@ databases, which requires multiple `DataSources`, and subsequently multiple diff configured `JdbcTemplates`. - [[jdbc-NamedParameterJdbcTemplate]] ==== NamedParameterJdbcTemplate @@ -2755,7 +2761,6 @@ See also <> for guidelines on using the `NamedParameterJdbcTemplate` class in the context of an application. - [[jdbc-SQLExceptionTranslator]] ==== SQLExceptionTranslator @@ -2849,9 +2854,9 @@ The custom translator is passed a data source in order to look up the error code `sql-error-codes.xml`. - [[jdbc-statements-executing]] ==== Executing statements + Executing an SQL statement requires very little code. You need a `DataSource` and a `JdbcTemplate`, including the convenience methods that are provided with the `JdbcTemplate`. The following example shows what you need to include for a minimal but @@ -2878,9 +2883,9 @@ fully functional class that creates a new table: ---- - [[jdbc-statements-querying]] ==== Running queries + Some query methods return a single value. To retrieve a count or a specific value from one row, use `queryForObject(..)`. The latter converts the returned JDBC `Type` to the Java class that is passed in as an argument. If the type conversion is invalid, then an @@ -2940,9 +2945,9 @@ The list returned would look something like this: ---- - [[jdbc-updates]] ==== Updating the database + The following example shows a column updated for a certain primary key. In this example, an SQL statement has placeholders for row parameters. The parameter values can be passed in as varargs or alternatively as an array of objects. Thus primitives should be wrapped @@ -2970,9 +2975,9 @@ in the primitive wrapper classes explicitly or using auto-boxing. ---- - [[jdbc-auto-genereted-keys]] ==== Retrieving auto-generated keys + An `update()` convenience method supports the retrieval of primary keys generated by the database. This support is part of the JDBC 3.0 standard; see Chapter 13.6 of the specification for details. The method takes a `PreparedStatementCreator` as its first @@ -3004,12 +3009,10 @@ following example works on Oracle but may not work on other platforms: - [[jdbc-connections]] === Controlling database connections - [[jdbc-datasource]] ==== DataSource @@ -3102,7 +3105,6 @@ C3P0 configuration: ---- - [[jdbc-DataSourceUtils]] ==== DataSourceUtils @@ -3111,7 +3113,6 @@ The `DataSourceUtils` class is a convenient and powerful helper class that provi supports thread-bound connections with, for example, `DataSourceTransactionManager`. - [[jdbc-SmartDataSource]] ==== SmartDataSource @@ -3121,7 +3122,6 @@ 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 @@ -3131,7 +3131,6 @@ You extend the `AbstractDataSource` class if you are writing your own `DataSourc implementation. - [[jdbc-SingleConnectionDataSource]] ==== SingleConnectionDataSource @@ -3150,7 +3149,6 @@ application server, in conjunction with a simple JNDI environment. In contrast t excessive creation of physical connections. - [[jdbc-DriverManagerDataSource]] ==== DriverManagerDataSource @@ -3167,7 +3165,6 @@ environment, that it is almost always preferable to use such a connection pool o `DriverManagerDataSource`. - [[jdbc-TransactionAwareDataSourceProxy]] ==== TransactionAwareDataSourceProxy @@ -3218,14 +3215,15 @@ pattern. JTA does not support custom isolation levels! [[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 interface, `BatchPreparedStatementSetter`, and passing that in as the second parameter in your `batchUpdate` method call. Use the `getBatchSize` method to provide the size of @@ -3272,9 +3270,9 @@ you to interrupt a batch once the input source is exhausted. The `isBatchExhaust 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 of providing the batch update. Instead of implementing a special batch interface, you provide all parameter values in the call as a list. The framework loops over these @@ -3351,9 +3349,9 @@ affected rows for each batch entry. This count is reported by the JDBC driver. I 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 break them up into several smaller batches. You can of course do this with the methods mentioned above by making multiple calls to the `batchUpdate` method, but there is now a @@ -3407,18 +3405,18 @@ 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 by taking advantage of database metadata that can be retrieved through the JDBC driver. 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 configuration options. You should instantiate the `SimpleJdbcInsert` in the data access layer's initialization method. For this example, the initializing method is the @@ -3459,9 +3457,9 @@ names of the table as defined in the database. This is because we read the metad 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 retrieves the auto-generated key and sets it on the new Actor object. When you create the `SimpleJdbcInsert`, in addition to specifying the table name, you specify the name @@ -3503,9 +3501,9 @@ multiple auto-generated columns, or the generated values are non-numeric, then y use a `KeyHolder` that is returned from the `executeAndReturnKeyHolder` 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 `usingColumns` method: @@ -3542,9 +3540,9 @@ The execution of the insert is the same as if you had relied on the metadata to 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 class to use. Spring provides a couple of implementations of the `SqlParameterSource` interface that can be used instead.The first one is `BeanPropertySqlParameterSource`, @@ -3613,9 +3611,9 @@ As you can see, the configuration is the same; only the executing code has to ch 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` and `out` parameters, so that you do not have to declare them explicitly. You can declare parameters if you prefer to do that, or if you have parameters such as `ARRAY` @@ -3726,9 +3724,9 @@ By taking this action, you avoid conflicts in the case used for the names of you 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 explicitly if you wish. You do this by creating and configuring `SimpleJdbcCall` with the `declareParameters` method, which takes a variable number of `SqlParameter` objects @@ -3784,9 +3782,9 @@ The execution and end results of the two examples are the same; this one specifi 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 classes, covered in <>, you use an `SqlParameter` or one of its subclasses. You typically specify the parameter name and SQL type in the constructor. The SQL type @@ -3823,9 +3821,9 @@ 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 that you provide a function name rather than a procedure name. You use the `withFunctionName` method as part of the configuration to indicate that we want to make @@ -3885,9 +3883,9 @@ The execute method used returns a `String` containing the return value from the 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 databases return result sets during the JDBC results processing while others require an explicitly registered `out` parameter of a specific type. Both approaches need @@ -3946,9 +3944,9 @@ The list of Actors is then retrieved from the results map and returned to the ca - [[jdbc-object]] === Modeling JDBC operations as Java objects + The `org.springframework.jdbc.object` package contains classes that allow you to access the database in a more object-oriented manner. As an example, you can execute queries and get the results back as a list containing business objects with the relational @@ -3968,7 +3966,6 @@ continue using these classes. ==== - [[jdbc-SqlQuery]] ==== SqlQuery @@ -3981,7 +3978,6 @@ mapping rows to Java classes. Other implementations that extend `SqlQuery` are `MappingSqlQueryWithParameters` and `UpdatableSqlQuery`. - [[jdbc-MappingSqlQuery]] ==== MappingSqlQuery @@ -4056,7 +4052,6 @@ methods that takes an array of parameter values passed in as varargs. ---- - [[jdbc-SqlUpdate]] ==== SqlUpdate @@ -4100,7 +4095,6 @@ class since it can easily be parameterized by setting SQL and declaring paramete ---- - [[jdbc-StoredProcedure]] ==== StoredProcedure @@ -4321,16 +4315,16 @@ delegate to the superclass' untyped `execute(Map parameters)` method (which has - [[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 passed in. It is possible to explicitly provide the SQL type to be used when setting parameter values. This is sometimes necessary to correctly set NULL values. @@ -4350,9 +4344,9 @@ You can provide SQL type information in several ways: 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 data, and large chunks of text in the database. These large objects are called BLOBs (Binary Large OBject) for binary data and CLOBs (Character Large OBject) for character data. In Spring you can handle these large objects by using @@ -4444,9 +4438,9 @@ with the same instance variable `lobHandler` and a reference to a `DefaultLobHan <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 variable list of values. A typical example would be `select * from T_ACTOR where id in (1, 2, 3)`. This variable list is not directly supported for prepared statements by the @@ -4472,9 +4466,9 @@ clause such as `select * from T_ACTOR where (id, last_name) in \((1, 'Johnson'), '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 database. To accommodate these types, Spring provides a `SqlReturnType` for handling them when they are returned from the stored procedure call and `SqlTypeValue` when they @@ -4555,9 +4549,9 @@ it with values from the Java `ARRAY`. - [[jdbc-embedded-database-support]] === Embedded database support + The `org.springframework.jdbc.datasource.embedded` package provides support for embedded Java database engines. Support for http://www.hsqldb.org[HSQL], http://www.h2database.com[H2], and http://db.apache.org/derby[Derby] is provided @@ -4565,15 +4559,14 @@ natively. You can also use an extensible API to plug in new embedded database ty `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 using Spring XML @@ -4596,7 +4589,6 @@ embedded database is made available to the Spring container as a bean of type `javax.sql.DataSource` which can then be injected into data access objects as needed. - [[jdbc-embedded-database-java]] ==== Creating an embedded database programmatically @@ -4647,12 +4639,13 @@ public class DataSourceConfig { } ---- + [[jdbc-embedded-database-types]] ==== Selecting the embedded database type - [[jdbc-embedded-database-using-HSQL]] ===== Using HSQL + Spring supports HSQL 1.8.0 and above. HSQL is the default embedded database if no type is specified explicitly. To specify HSQL explicitly, set the `type` attribute of the `embedded-database` tag to `HSQL`. If you are using the builder API, call the @@ -4661,6 +4654,7 @@ specified explicitly. To specify HSQL explicitly, set the `type` attribute of th [[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`. @@ -4668,12 +4662,12 @@ Spring supports the H2 database as well. To enable H2, set the `type` attribute [[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 you are 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 @@ -4749,7 +4743,6 @@ the following options. * `` - [[jdbc-embedded-database-extension]] ==== Extending the embedded database support @@ -4766,15 +4759,16 @@ https://jira.spring.io/browse/SPR[jira.spring.io]. [[jdbc-initializing-datasource]] === Initializing a DataSource + The `org.springframework.jdbc.datasource.init` package provides support for initializing an existing `DataSource`. The embedded database support provides one option for creating 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 using Spring XML + If you want to initialize a database and you can provide a reference to a `DataSource` bean, use the `initialize-database` tag in the `spring-jdbc` namespace: @@ -4856,11 +4850,9 @@ In this example, the two `test-data` scripts use `@@` as statement separator and the `db-schema.sql` uses `;`. This configuration specifies that the default separator is `@@` and override that default for the `db-schema` script. - 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 @@ -4916,8 +4908,10 @@ The second option can also be easy. Some suggestions on how to implement this in == Object Relational Mapping (ORM) Data Access + [[orm-introduction]] === Introduction to ORM with Spring + The Spring Framework supports integration with the Java Persistence API (JPA) as well as native Hibernate for resource management, data access object (DAO) implementations, and transaction strategies. For example, for Hibernate there is first-class support with @@ -4987,6 +4981,7 @@ Data with JPA] guide from https://spring.io provides a great introduction. [[orm-general]] === General ORM integration considerations + This section highlights considerations that apply to all ORM technologies. The <> section provides more details and also show these features and configurations in a concrete context. @@ -5005,9 +5000,9 @@ transaction managers, business services that use the data access objects and tra 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. Many projects try to invent their own solutions, sometimes sacrificing proper handling of failures for programming convenience. Spring advocates simple solutions for proper @@ -5030,9 +5025,9 @@ and JPA support through the Hibernate and JPA transaction managers as well as JT For details on transaction support, see the <> chapter. - [[orm-exception-translation]] ==== Exception translation + When you use Hibernate or JPA in a DAO, you must decide how to handle the persistence technology's native exception classes. The DAO throws a subclass of a `HibernateException` or `PersistenceException` depending on the technology. These exceptions are all runtime @@ -5081,9 +5076,9 @@ exception hierarchies. - [[orm-hibernate]] === Hibernate + We will start with a coverage of http://www.hibernate.org/[Hibernate 5] in a Spring environment, using it to demonstrate the approach that Spring takes towards integrating O/R mappers. This section will cover many issues in detail and show different variations @@ -5100,7 +5095,6 @@ is likely to focus on 5.2+ exclusively soon. ==== - [[orm-session-factory-setup]] ==== SessionFactory setup in a Spring container @@ -5159,9 +5153,9 @@ You can also access a JNDI-located `SessionFactory`, using Spring's is typically not common outside of an EJB context. - [[orm-hibernate-straight]] ==== Implementing DAOs based on plain Hibernate API + Hibernate has a feature called contextual sessions, wherein Hibernate itself manages one current `Session` per transaction. This is roughly equivalent to Spring's synchronization of one Hibernate `Session` per transaction. A corresponding DAO @@ -5235,9 +5229,9 @@ In summary: you can implement DAOs based on the plain Hibernate API, while still 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 replace explicit transaction demarcation API calls in your Java code with an AOP transaction interceptor. This transaction interceptor can be configured in a Spring @@ -5317,9 +5311,9 @@ opting into `@Transactional` processing at runtime. ---- - [[orm-hibernate-tx-programmatic]] ==== Programmatic transaction demarcation + You can demarcate transactions in a higher level of the application, on top of such lower-level data access services spanning any number of operations. Nor do restrictions exist on the implementation of the surrounding business service; it just needs a Spring @@ -5381,9 +5375,9 @@ application (via `TransactionStatus`). `TransactionInterceptor` behaves the same default but allows configurable rollback policies per method. - [[orm-hibernate-tx-strategies]] ==== Transaction management strategies + Both `TransactionTemplate` and `TransactionInterceptor` delegate the actual transaction handling to a `PlatformTransactionManager` instance, which can be a `HibernateTransactionManager` (for a single Hibernate `SessionFactory`, using a @@ -5419,9 +5413,9 @@ exposes the Hibernate transaction as a JDBC transaction if you have set up the p `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 one, without having to change a single line of application code. Whether to keep resource definitions in the container or locally within the application is mainly a @@ -5465,9 +5459,9 @@ Hibernate `SessionFactory` through the JCA connector only adds value when used i 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 only some WebLogic Server and WebSphere versions -- when Hibernate is configured without regard to the JTA `PlatformTransactionManager` object for that environment, it is @@ -5534,9 +5528,9 @@ following events occur when a JTA transaction commits: - [[orm-jpa]] === JPA + The Spring JPA, available under the `org.springframework.orm.jpa` package, offers comprehensive support for the http://www.oracle.com/technetwork/articles/javaee/jpa-137156.html[Java Persistence @@ -5544,13 +5538,12 @@ API] in a similar manner to the integration with Hibernate, 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 @@ -5583,7 +5576,6 @@ 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 @@ -5623,7 +5615,6 @@ 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]] ===== LocalContainerEntityManagerFactoryBean @@ -5758,7 +5749,6 @@ 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]] ===== Dealing with multiple persistence units For applications that rely on multiple persistence units locations, stored in various @@ -5803,9 +5793,9 @@ affect __all__ hosted units, or programmatically, through the `LocalContainerEntityManagerFactoryBean`. - [[orm-jpa-dao]] ==== Implementing DAOs based on JPA: EntityManagerFactory and EntityManager + [NOTE] ==== Although `EntityManagerFactory` instances are thread-safe, `EntityManager` instances are @@ -5942,7 +5932,6 @@ the injections are applied automatically by the Spring container. This is appeal a non-invasiveness perspective, and might feel more natural to JPA developers. - [[orm-jpa-tx]] ==== Spring-driven JPA transactions @@ -5964,7 +5953,6 @@ Spring provides dialects for the EclipseLink and Hibernate JPA implementations. See the next section for details on the `JpaDialect` mechanism. - [[orm-jpa-dialect]] ==== JpaDialect and JpaVendorAdapter @@ -5998,7 +5986,6 @@ See the `JpaDialect` and `JpaVendorAdapter` javadocs for more details of its ope and how they are used within Spring's JPA support. - [[orm-jpa-jta]] ==== Setting up JPA with JTA transaction management @@ -6040,6 +6027,7 @@ less portable, but will be set up for the server's JTA environment out of the bo == Marshalling XML using O/X Mappers + [[oxm-introduction]] === Introduction In this chapter, we will describe Spring's Object/XML Mapping support. Object/XML @@ -6055,8 +6043,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 as any other bean in your application context. Additionally, XML Schema-based @@ -6064,8 +6052,8 @@ configuration is available for a number of marshallers, making the configuration 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 with relative ease, with little or no changes required on the classes that do the @@ -6075,25 +6063,25 @@ other using Castor) 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 `org.springframework.oxm.Marshaller` interface, the main method of which is shown below. @@ -6138,9 +6126,9 @@ 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` interface. @@ -6181,9 +6169,9 @@ 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 hierarchy with the `XmlMappingException` as the root exception. As can be expected, these runtime exceptions wrap the original exception so no information will be lost. @@ -6200,9 +6188,9 @@ 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 will use it to marshal the settings of a Spring-managed application as an XML file. We will use a simple JavaBean to represent the settings: @@ -6325,9 +6313,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 make these tags available, the appropriate schema has to be referenced first in the preamble of the XML configuration file. Note the 'oxm' related text below: @@ -6358,9 +6346,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 `jaxb.properties` file, and possibly some resource files. JAXB also offers a way to generate a schema from annotated Java classes. @@ -6371,9 +6359,9 @@ The corresponding integration classes reside in the `org.springframework.oxm.jax package. - [[oxm-jaxb2]] ==== Jaxb2Marshaller + The `Jaxb2Marshaller` class implements both the Spring `Marshaller` and `Unmarshaller` interface. It requires a context path to operate, which you can set using the `contextPath` property. The context path is a list of colon (:) separated Java package @@ -6400,9 +6388,9 @@ 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`. Here is an example: @@ -6441,9 +6429,9 @@ Available attributes are: - [[oxm-castor]] === Castor + Castor XML mapping is an open source XML binding framework. It allows you to transform the data contained in a java object model into/from an XML document. By default, it does not require any further configuration, though a mapping file can be used to have more @@ -6454,9 +6442,9 @@ http://castor-data-binding.github.io/castor[__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` interface. It can be wired up as follows: @@ -6470,9 +6458,9 @@ 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 necessary to have more control over it. This can be accomplished using a Castor mapping file. For more information, refer to http://castor-data-binding.github.io/castor/reference-guides/1.3.3/html-single/index.html#xml.mapping[Castor @@ -6491,9 +6479,9 @@ with a classpath resource. ---- - [[oxm-castor-xsd]] ===== XML Schema-based Configuration + The `castor-marshaller` tag configures a `org.springframework.oxm.castor.CastorMarshaller`. Here is an example: @@ -6540,9 +6528,9 @@ Available attributes are: - [[oxm-jibx]] === JiBX + The JiBX framework offers a solution similar to that which Hibernate provides for ORM: a binding definition defines the rules for how your Java objects are converted to or from XML. After preparing the binding and compiling the classes, a JiBX binding compiler @@ -6554,9 +6542,9 @@ site__]. The Spring integration classes reside in the `org.springframework.oxm.j package. - [[oxm-jibx-marshaller]] ==== JibxMarshaller + The `JibxMarshaller` class implements both the `Marshaller` and `Unmarshaller` interface. To operate, it requires the name of the class to marshal in, which you can set using the `targetClass` property. Optionally, you can set the binding name using the @@ -6577,9 +6565,9 @@ 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`. Here is an example: @@ -6609,9 +6597,9 @@ Available attributes are: - [[oxm-xstream]] === XStream + XStream is a simple library to serialize objects to XML and back again. It does not require any mapping, and generates clean XML. @@ -6620,9 +6608,9 @@ 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 application context directly. To further customize the XML, you can set an__alias map__, which consists of string aliases mapped to classes: @@ -6677,4 +6665,6 @@ Therefore, it has limited namespace support. As such, it is rather unsuitable fo within Web services. + + include::data-access-appendix.adoc[leveloffset=+1] diff --git a/src/docs/asciidoc/integration-appendix.adoc b/src/docs/asciidoc/integration-appendix.adoc index 0563f54d59c..69518628825 100644 --- a/src/docs/asciidoc/integration-appendix.adoc +++ b/src/docs/asciidoc/integration-appendix.adoc @@ -1,11 +1,15 @@ = Appendix + + + [[xsd-schemas]] == XML Schemas This part of the appendix lists XML schemas related to integration technologies. + [[xsd-schemas-jee]] === The jee schema diff --git a/src/docs/asciidoc/integration.adoc b/src/docs/asciidoc/integration.adoc index c15b84abefb..80d87968719 100644 --- a/src/docs/asciidoc/integration.adoc +++ b/src/docs/asciidoc/integration.adoc @@ -12,12 +12,16 @@ This part of the reference documentation covers the Spring Framework's integrati 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 remoting support eases the development of remote-enabled services, implemented by your usual (Spring) POJOs. Currently, Spring supports the following remoting technologies: @@ -96,9 +100,9 @@ protocol. - [[remoting-rmi]] === Exposing services using RMI + Using Spring's support for RMI, you can transparently expose your services through the RMI infrastructure. After having this set up, you basically have a configuration similar to remote EJBs, except for the fact that there is no standard support for security @@ -107,7 +111,6 @@ such additional invocation context when using the RMI invoker, so you can for ex plug in security frameworks or custom security credentials here. - [[remoting-rmi-server]] ==== Exporting the service using the RmiServiceExporter @@ -154,9 +157,9 @@ 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: [source,java,indent=0] @@ -197,14 +200,13 @@ will transparently create an invoker and remotely enable the account service thr - [[remoting-caucho-protocols]] === Using Hessian 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. @@ -240,7 +242,6 @@ pointing to specific exporter beans. Each servlet name needs to match the bean n its target exporter in this case. - [[remoting-caucho-protocols-hessian-server]] ==== Exposing your beans by using the HessianServiceExporter @@ -298,9 +299,9 @@ 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 principles apply as with the RMI example. We'll create a separate bean factory or application context and mention the following beans where the `SimpleObject` is using @@ -320,9 +321,9 @@ the `AccountService` to manage accounts: ---- - [[remoting-caucho-protocols-security]] ==== Applying HTTP basic authentication to a service exposed through Hessian + One of the advantages of Hessian is that we can easily apply HTTP basic authentication, because both protocols are HTTP-based. Your normal HTTP server security mechanism can easily be applied through using the `web.xml` security features, for example. Usually, @@ -355,9 +356,9 @@ at http://projects.spring.io/spring-security/[]. - [[remoting-httpinvoker]] === Exposing services using HTTP invokers + As opposed to Hessian, which are both lightweight protocols using their own slim serialization mechanisms, Spring HTTP invokers use the standard Java serialization mechanism to expose services through HTTP. This has a huge advantage if your arguments @@ -387,9 +388,9 @@ http://openjdk.java.net/jeps/290 ==== - [[remoting-httpinvoker-server]] ==== Exposing the service object + Setting up the HTTP invoker infrastructure for a service object resembles closely the way you would do the same using Hessian. Just as Hessian support provides the `HessianServiceExporter`, Spring's HttpInvoker support provides the @@ -466,9 +467,9 @@ 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 when using Hessian. Using a proxy, Spring will be able to translate your calls to HTTP POST requests to the URL pointing to the exported service. @@ -496,9 +497,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: * Exposing web services using JAX-WS @@ -510,9 +511,9 @@ contract-first, document-driven web services - highly recommended for building m 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 - `SpringBeanAutowiringSupport`. To expose our `AccountService` we extend Spring's `SpringBeanAutowiringSupport` class and implement our business logic here, usually @@ -565,13 +566,13 @@ EE 5 environments, using the standard contract for JAX-WS servlet endpoint deplo 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 Oracle's JDK 1.6 supports exposure of web -services using the built-in HTTP server that's included in JDK 1.6 as well. Spring's + +The built-in JAX-WS provider that comes with Oracle's JDK supports exposure of web +services using the built-in HTTP server that's included in the JDK as well. Spring's `SimpleJaxWsServiceExporter` detects all `@WebService` annotated beans in the Spring -application context, exporting them through the default JAX-WS server (the JDK 1.6 HTTP +application context, exporting them through the default JAX-WS server (the JDK HTTP server). In this scenario, the endpoint instances are defined and managed as Spring beans @@ -622,9 +623,9 @@ and Spring's `@Autowired` configuration annotation still being honored: ---- - [[remoting-web-services-jaxws-export-ri]] ==== Exporting web services using the JAX-WS RI's Spring support + Oracle's JAX-WS RI, developed as part of the GlassFish project, ships Spring support as part of its JAX-WS Commons project. This allows for defining JAX-WS endpoints as Spring-managed beans, similar to the standalone mode discussed in the previous section - @@ -643,9 +644,9 @@ Check out https://jax-ws-commons.java.net/spring/[https://jax-ws-commons.java.ne for 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 `LocalJaxWsServiceFactoryBean` and `JaxWsPortProxyFactoryBean`. The former can only return a JAX-WS service class for us to work with. The latter is the full-fledged @@ -712,9 +713,9 @@ accordingly first. Check the JAX-WS documentation for details on those requireme - [[remoting-jms]] === JMS + It is also possible to expose services transparently using JMS as the underlying communication protocol. The JMS remoting support in the Spring Framework is pretty basic - it sends and receives on the `same thread` and in the __same non-transactional__ @@ -777,9 +778,9 @@ the client and server. ---- - [[remoting-jms-server]] ==== Server-side configuration + On the server, you just need to expose the service object using the `JmsInvokerServiceExporter`. @@ -827,9 +828,9 @@ On the server, you just need to expose the service object using the ---- - [[remoting-jms-client]] ==== Client-side configuration + The client merely needs to create a client-side proxy that will implement the agreed upon interface ( `CheckingAccountService`). The resulting object created off the back of the following bean definition can be injected into other client side objects, and the @@ -876,7 +877,6 @@ proxy will take care of forwarding the call to the server-side object via JMS. - [[remoting-amqp]] === AMQP Refer to the {doc-spring-amqp}/html/_reference.html#remoting[Spring AMQP Reference Document @@ -884,9 +884,9 @@ Refer to the {doc-spring-amqp}/html/_reference.html#remoting[Spring AMQP Referen - [[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 interfaces is to avoid opening too many doors to remote callers. The target object might implement internal callback interfaces like `InitializingBean` or `DisposableBean` which @@ -905,9 +905,9 @@ effort, and puts you on the safe side regarding controlled exposure of specific - [[remoting-considerations]] === Considerations when choosing a technology + Each and every technology presented here has its drawbacks. You should carefully consider your needs, the services you are exposing and the objects you'll be sending over the wire when choosing a technology. @@ -944,7 +944,6 @@ plugging in third-party or custom solutions here. - [[rest-client-access]] === Accessing REST endpoints @@ -1136,9 +1135,9 @@ 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 a String URI or `java.net.URI` as the first argument. @@ -1186,9 +1185,9 @@ Or specify each URI component individually: URI uri = uriComponents.toUri(); ---- - [[rest-template-headers]] ===== Dealing with request and response headers + Besides the methods described above, the `RestTemplate` also has the `exchange()` method, which can be used for arbitrary HTTP method execution based on the `HttpEntity` class. @@ -1233,6 +1232,7 @@ to serialize only a subset of the object properties. For example: [[rest-message-conversion]] ==== HTTP Message Conversion + Objects passed to and returned from the methods `getForObject()`, `postForLocation()`, and `put()` are converted to HTTP requests and from HTTP responses by `HttpMessageConverters`. The `HttpMessageConverter` interface is shown below to give you @@ -1269,41 +1269,41 @@ The implementations of ``HttpMessageConverter``s are described in the following 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/{asterisk}`), 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 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 HTTP request and response. By default, this converter supports all media types ( `{asterisk}/{asterisk}`), 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 `Marshaller` and `Unmarshaller` abstractions from the `org.springframework.oxm` package. This converter requires a `Marshaller` and `Unmarshaller` before it can be used. These can be injected via constructor or bean properties. By default this converter supports ( `text/xml`) and ( `application/xml`). - [[rest-mapping-json-converter]] ===== MappingJackson2HttpMessageConverter + An `HttpMessageConverter` implementation that can read and write JSON using Jackson's `ObjectMapper`. JSON mapping can be customized as needed through the use of Jackson's provided annotations. When further control is needed, a custom `ObjectMapper` can be @@ -1311,9 +1311,9 @@ 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-mapping-xml-converter]] ===== MappingJackson2XmlHttpMessageConverter + An `HttpMessageConverter` implementation that can read and write XML using https://github.com/FasterXML/jackson-dataformat-xml[Jackson XML] extension's `XmlMapper`. XML mapping can be customized as needed through the use of JAXB @@ -1322,21 +1322,22 @@ can be injected through the `ObjectMapper` property for cases where custom XML serializers/deserializers need to be provided for specific types. By default this converter supports ( `application/xml`). - [[rest-source-converter]] ===== SourceHttpMessageConverter + An `HttpMessageConverter` implementation that can read and write `javax.xml.transform.Source` from the HTTP request and response. Only `DOMSource`, `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. + [[rest-async-resttemplate]] ==== Async RestTemplate @@ -1345,12 +1346,12 @@ Please use the <> instead. + [[ejb]] == Enterprise JavaBeans (EJB) integration - [[ejb-introduction]] === Introduction As a lightweight container, Spring is often considered an EJB replacement. We do believe @@ -1372,14 +1373,13 @@ 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 normally perform a JNDI lookup to obtain the (local or remote) EJB Home object, then use a 'create' method call on that object to obtain the actual (local or remote) EJB object. @@ -1405,9 +1405,9 @@ not need to write another Service Locator, another JNDI lookup, or duplicate met 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 practice and use the EJB Business Methods Interface pattern, so that the EJB's local interface extends a non EJB-specific business methods interface. Let's call this @@ -1513,9 +1513,9 @@ Although this will not be of interest to the majority of Spring users, those doi 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 `SimpleRemoteStatelessSessionProxyFactoryBean` or `` configuration element is used. Of course, with or without Spring, remote invocation semantics apply; a @@ -1543,9 +1543,9 @@ 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 transparent. Spring's EJB accessors, including the `` and `` facilities, transparently adapt to the actual component at runtime. @@ -1567,6 +1567,7 @@ lookups simply provides consistent and more explicit EJB access configuration. [[jms-introduction]] === Introduction + Spring provides a JMS integration framework that simplifies the use of the JMS API much like Spring's integration does for the JDBC API. @@ -1615,12 +1616,10 @@ resource into Spring's transaction management mechanisms. - [[jms-using]] === Using Spring JMS - [[jms-jmstemplate]] ==== JmsTemplate @@ -1671,6 +1670,7 @@ send in generic manner. [[jms-connections]] ==== Connections + The `JmsTemplate` requires a reference to a `ConnectionFactory`. The `ConnectionFactory` is part of the JMS specification and serves as the entry point for working with JMS. It is used by the client application as a factory to create connections with the JMS @@ -1685,9 +1685,9 @@ 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 following 'API' walk is performed @@ -1701,9 +1701,9 @@ 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 `ConnectionFactory` are provided. - [[jms-connection-factory]] ===== SingleConnectionFactory + Spring provides an implementation of the `ConnectionFactory` interface, `SingleConnectionFactory`, that will return the same `Connection` on all `createConnection()` calls and ignore calls to `close()`. This is useful for testing and @@ -1711,9 +1711,9 @@ 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` and adds the caching of Sessions, MessageProducers, and MessageConsumers. The initial cache size is set to 1, use the property `sessionCacheSize` to increase the number of @@ -1727,9 +1727,9 @@ 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 and retrieved in JNDI. When configuring a Spring application context you can use the JNDI factory class `JndiObjectFactoryBean` / `` to perform dependency @@ -1772,9 +1772,9 @@ You can also configure the `JmsTemplate` with a default destination via the prop 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 beans (MDBs). Spring offers a solution to create message-driven POJOs (MDPs) in a way that does not tie a user to an EJB container. (See <> @@ -1795,9 +1795,9 @@ 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 fixed number of JMS sessions and consumers at startup, registers the listener using the standard JMS `MessageConsumer.setMessageListener()` method, and leaves it up the JMS @@ -1818,9 +1818,9 @@ Sessions and therefore does not include any other Session operations (such as se response messages) in the transaction protocol. ==== - [[jms-mdp-default]] ===== DefaultMessageListenerContainer + This message listener container is the one used in most cases. In contrast to `SimpleMessageListenerContainer`, this container variant allows for dynamic adaptation to runtime demands and is able to participate in externally managed transactions. Each @@ -1858,6 +1858,7 @@ message listener (including database operations etc). [[jms-tx]] ==== Transaction management + Spring provides a `JmsTransactionManager` that manages transactions for a single JMS `ConnectionFactory`. This allows JMS applications to leverage the managed transaction features of Spring as described in <>. @@ -1891,7 +1892,6 @@ transactional JMS `Session`. - [[jms-sending]] === Sending a Message @@ -1952,9 +1952,9 @@ 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 various send methods that take a Java object as an argument for a message's data content. The overloaded methods `convertAndSend()` and `receiveAndConvert()` in @@ -2015,7 +2015,6 @@ MapMessage={ ---- - [[jms-callbacks]] ==== SessionCallback and ProducerCallback @@ -2027,14 +2026,13 @@ 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 consume messages synchronously. The overloaded `receive(..)` methods provide this functionality. During a synchronous receive, the calling thread blocks until a message @@ -2043,7 +2041,6 @@ potentially be blocked indefinitely. The property `receiveTimeout` specifies how the receiver should wait before giving up waiting for a message. - [[jms-asynchronousMessageReception]] ==== Asynchronous Reception - Message-Driven POJOs @@ -2115,7 +2112,6 @@ Please refer to the Spring javadocs of the various message listener containers f description of the features supported by each implementation. - [[jms-receiving-async-session-aware-message-listener]] ==== the SessionAwareMessageListener interface @@ -2151,7 +2147,6 @@ 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 @@ -2289,9 +2284,9 @@ please note that this exception __will not__ be swallowed and __will__ propagate call stack). - [[jms-tx-participation]] ==== Processing messages within transactions + Invoking a message listener within a transaction only requires reconfiguration of the listener container. @@ -2349,9 +2344,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 `MessageListener` container. The `JmsMessageEndpointManager` will attempt to automatically determine the `ActivationSpec` class name from the provider's @@ -2443,6 +2438,7 @@ contract. [[jms-annotated]] === Annotation-driven listener endpoints + The easiest way to receive a message asynchronously is to use the annotated listener endpoint infrastructure. In a nutshell, it allows you to expose a method of a managed bean as a JMS listener endpoint. @@ -2473,9 +2469,10 @@ located for management purposes using the `JmsListenerEndpointRegistry` bean. ==== `@JmsListener` is a _repeatable_ annotation on Java 8, so it is possible to associate several JMS destinations to the same method by adding additional `@JmsListener` -declarations to it. On Java 6 and 7, you can use the `@JmsListeners` annotation. +declarations to it. ==== + [[jms-annotated-support]] ==== Enable listener endpoint annotations @@ -2527,6 +2524,7 @@ element. ---- + [[jms-annotated-programmatic-registration]] ==== Programmatic endpoints registration @@ -2561,6 +2559,7 @@ describing a custom invocation mechanism. It should be noted that you could just as well skip the use of `@JmsListener` altogether and only register your endpoints programmatically through `JmsListenerConfigurer`. + [[jms-annotated-method-signature]] ==== Annotated endpoint method signature @@ -2638,6 +2637,7 @@ annotate the payload with `@Valid` and configure the necessary validator as foll } ---- + [[jms-annotated-response]] ==== Response management @@ -2728,8 +2728,10 @@ the time to live, you can configure the `JmsListenerContainerFactory` accordingl ---- + [[jms-namespace]] === JMS namespace support + Spring provides an XML namespace for simplifying JMS configuration. To use the JMS namespace elements you will need to reference the JMS schema: @@ -3030,14 +3032,15 @@ table: + [[jmx]] == JMX - [[jmx-introduction]] === Introduction + The JMX support in Spring provides you with the features to easily and transparently integrate your Spring application into a JMX infrastructure. @@ -3062,9 +3065,9 @@ Spring JMX features. - [[jmx-exporting]] === Exporting your beans to JMX + The core class in Spring's JMX framework is the `MBeanExporter`. This class is responsible for taking your Spring beans and registering them with a JMX `MBeanServer`. For example, consider the following class: @@ -3201,7 +3204,6 @@ supplied to the `MBeanExporter` via the server property. When you supply your ow correctly, you must (of course) have a JMX implementation on your classpath. - [[jmx-mbean-server]] ==== Reusing an existing MBeanServer @@ -3249,9 +3251,9 @@ 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 initialization, then the `MBeanExporter` will __not__ break this contract and will avoid instantiating the bean. Instead, it will register a proxy with the `MBeanServer` and @@ -3259,9 +3261,9 @@ will defer obtaining the bean from the container until the first invocation on t occurs. - [[jmx-exporting-auto]] ==== Automatic registration of MBeans + Any beans that are exported through the `MBeanExporter` and are already valid MBeans are registered as-is with the `MBeanServer` without further intervention from Spring. MBeans can be automatically detected by the `MBeanExporter` by setting the `autodetect` @@ -3283,9 +3285,9 @@ 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` with an `MBeanServer` using the `ObjectName` `'bean:name=testBean1'`. If an `MBean` instance has already been registered under that same `ObjectName`, the default behavior @@ -3355,9 +3357,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 bean; __all__ of the __public__ properties and methods of each exported bean was exposed as JMX attributes and operations respectively. To exercise finer-grained control over @@ -3366,7 +3368,6 @@ attributes and operations, Spring JMX provides a comprehensive and extensible me for controlling the management interfaces of your beans. - [[jmx-interface-assembler]] ==== the MBeanInfoAssembler Interface @@ -3381,9 +3382,9 @@ saw in the previous examples). Spring provides two additional implementations of interface using either source-level metadata or any arbitrary interface. - [[jmx-interface-metadata]] ==== Using Source-Level Metadata (Java annotations) + Using the `MetadataMBeanInfoAssembler` you can define the management interfaces for your beans using source level metadata. The reading of metadata is encapsulated by the `org.springframework.jmx.export.metadata.JmxAttributeSource` interface. Spring JMX @@ -3524,9 +3525,9 @@ through the assembler property. This is all that is required to take advantage o 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: [[jmx-metadata-types]] @@ -3610,7 +3611,6 @@ metadata types: |=== - [[jmx-interface-autodetect]] ==== the AutodetectCapableMBeanInfoAssembler interface @@ -3658,9 +3658,9 @@ meaning. You can address this issue by changing the default behavior for `Object creation as defined in <>. - [[jmx-interface-java]] ==== Defining management interfaces using Java interfaces + In addition to the `MetadataMBeanInfoAssembler`, Spring also includes the `InterfaceBasedMBeanInfoAssembler` which allows you to constrain the methods and properties that are exposed based on the set of methods defined in a collection of @@ -3745,7 +3745,6 @@ on the bean and use all of the interfaces implemented by that bean to create the management interface. - [[jmx-interface-methodnames]] ==== Using MethodNameBasedMBeanInfoAssembler @@ -3781,7 +3780,6 @@ lists of method names. - [[jmx-naming]] === Controlling the ObjectNames for your beans @@ -3796,7 +3794,6 @@ of the `beans` `Map` to an entry in a `Properties` file (or files) to resolve th uses source level metadata to obtain the `ObjectName`. - [[jmx-naming-properties]] ==== Reading ObjectNames from Properties @@ -3852,7 +3849,6 @@ If no entry in the `Properties` instance can be found then the bean key name is the `ObjectName`. - [[jmx-naming-metadata]] ==== Using the MetadataNamingStrategy @@ -3902,9 +3898,9 @@ __com.foo:type=MyClass,name=myBean__. ---- - [[jmx-context-mbeanexport]] ==== Configuring annotation based MBean export + If you prefer using <> to define your management interfaces, then a convenience subclass of `MBeanExporter` is available: `AnnotationMBeanExporter`. When defining an instance of this subclass, the @@ -3966,17 +3962,17 @@ 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 following configuration: @@ -4045,9 +4041,9 @@ snippet of configuration: ---- - [[jmx-jsr160-client]] ==== Client-side Connectors + To create an `MBeanServerConnection` to a remote JSR-160 enabled `MBeanServer` use the `MBeanServerConnectionFactoryBean` as shown below: @@ -4060,9 +4056,9 @@ To create an `MBeanServerConnection` to a remote JSR-160 enabled `MBeanServer` u ---- - [[jmx-jsr160-protocols]] ==== JMX over Hessian or SOAP + JSR-160 permits extensions to the way in which communication is done between the client and the server. The examples above are using the mandatory RMI-based implementation required by the JSR-160 specification (IIOP and JRMP) and the (optional) JMXMP. By using @@ -4083,9 +4079,9 @@ 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 local or remote `MBeanServer`. These proxies provide you with a standard Java interface through which you can interact with your MBeans. The code below shows how to configure a @@ -4134,15 +4130,15 @@ created will forward all invocations to the `MBeanServer` via this - [[jmx-notifications]] === Notifications -Spring's JMX offering includes comprehensive support for JMX 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 `NotificationListeners` with any number of MBeans (this includes MBeans exported by Spring's `MBeanExporter` and MBeans registered via some other mechanism). By way of an @@ -4361,9 +4357,9 @@ 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 for publishing `Notifications`. @@ -4445,9 +4441,9 @@ 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. * The http://www.oracle.com/technetwork/java/javase/tech/javamanagement-140525.html[JMX @@ -4461,14 +4457,15 @@ homepage] at Oracle + [[cci]] == JCA CCI - [[cci-introduction]] === Introduction + Java EE provides a specification to standardize access to enterprise information systems (EIS): the JCA (Java EE Connector Architecture). This specification is divided into several different parts: @@ -4498,14 +4495,13 @@ 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 used must provide an implementation of this interface. @@ -4536,7 +4532,6 @@ might be running. ==== - [[cci-config-connectionfactory]] ==== ConnectionFactory configuration in Spring @@ -4580,9 +4575,9 @@ 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 `ConnectionSpec` implementation of your connector. In order to configure its properties, you need to wrap the target connection factory with a dedicated adapter, @@ -4637,9 +4632,9 @@ 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 `ConnectionFactory` adapter to manage this. The `SingleConnectionFactory` adapter class will open a single connection lazily and close it when this bean is destroyed at @@ -4677,14 +4672,13 @@ Use an intermediary `ConnectionSpecConnectionFactoryAdapter` that the - [[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 manipulating CCI records. The developer can specify the strategy to create records and extract datas from records, for use with Spring's `CciTemplate`. The following @@ -4757,9 +4751,8 @@ The following sample shows how to use the `RecordExtractor` interface. ---- - [[cci-using-template]] -==== the CciTemplate +==== CciTemplate The `CciTemplate` is the central class of the core CCI support package ( `org.springframework.jca.cci.core`). It simplifies the use of CCI since it handles the @@ -4865,9 +4858,9 @@ output `Record` as return value. ---- - [[cci-using-dao]] ==== DAO support + Spring's CCI support provides a abstract class for DAOs, supporting injection of a `ConnectionFactory` or a `CciTemplate` instances. The name of the class is `CciDaoSupport`: It provides simple `setConnectionFactory` and `setCciTemplate` methods. @@ -4899,9 +4892,9 @@ Internally, this class will create a `CciTemplate` instance for a passed-in ---- - [[automatic-output-generation]] ==== Automatic output record generation + If the connector used only supports the `Interaction.execute(..)` method with input and output records as parameters (that is, it requires the desired output record to be passed in instead of returning an appropriate output record), you can set the @@ -4941,9 +4934,9 @@ instance. ==== - [[template-summary]] ==== Summary + The following table summarizes the mechanisms of the `CciTemplate` class and the corresponding methods called on the CCI `Interaction` interface: @@ -4995,7 +4988,6 @@ corresponding methods called on the CCI `Interaction` interface: |=== - [[cci-straight]] ==== Using a CCI Connection and Interaction directly @@ -5041,7 +5033,6 @@ created inside every callback method. This is completely up to the DAO implement ==== - [[cci-template-example]] ==== Example for CciTemplate usage @@ -5186,9 +5177,9 @@ follows: - [[cci-object]] === Modeling CCI access as operation objects + The `org.springframework.jca.cci.object` package contains support classes that allow you to access the EIS in a different style: through reusable operation objects, analogous to Spring's JDBC operation objects (see JDBC chapter). This will usually encapsulate the @@ -5204,7 +5195,6 @@ CCI support. ==== - [[cci-object-mapping-record]] ==== MappingRecordOperation @@ -5273,7 +5263,6 @@ with a specific `InteractionSpec`: ---- - [[cci-object-mapping-comm-area]] ==== MappingCommAreaOperation @@ -5304,18 +5293,18 @@ input COMMAREA and the output COMMAREA into an output object. ---- - [[cci-automatic-record-gen]] ==== Automatic output record generation + As every `MappingRecordOperation` subclass is based on CciTemplate internally, the same way to automatically generate output records as with `CciTemplate` is available. Every 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. [[cci-interaction-methods]] @@ -5334,7 +5323,6 @@ The operation object approach uses records in the same manner as the `CciTemplat |=== - [[cci-objects-mappring-record-example]] ==== Example for MappingRecordOperation usage @@ -5461,7 +5449,6 @@ follows: ---- - [[cci-objects-mapping-comm-area-example]] ==== Example for MappingCommAreaOperation usage @@ -5562,9 +5549,9 @@ follows: - [[cci-tx]] === Transactions + JCA specifies several levels of transaction support for resource adapters. The kind of transactions that your resource adapter supports is specified in its `ra.xml` file. There are essentially three options: none (for example with CICS EPI connector), local @@ -5616,10 +5603,12 @@ For more information on Spring's transaction facilities, see the chapter entitle + [[mail]] == Email + [[mail-introduction]] === Introduction @@ -5655,9 +5644,9 @@ of JavaMail MIME messages, called - [[mail-usage]] === Usage + Let's assume there is a business interface called `OrderManager`: [source,java,indent=0] @@ -5674,7 +5663,6 @@ Let us also assume that there is a requirement stating that an email message wit order number needs to be generated and sent to a customer placing the relevant order. - [[mail-usage-simple]] ==== Basic MailSender and SimpleMailMessage usage @@ -5746,7 +5734,6 @@ Find below the bean definitions for the above code: ---- - [[mail-usage-mime]] ==== Using the JavaMailSender and the MimeMessagePreparator @@ -5820,7 +5807,6 @@ Please refer to the relevant javadocs for more information. - [[mail-javamail-mime]] === Using the JavaMail MimeMessageHelper @@ -5845,16 +5831,16 @@ to create a `MimeMessage`: ---- - [[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 along with a single JPEG image attachment. @@ -5879,9 +5865,9 @@ along with a single JPEG image attachment. sender.send(message); ---- - [[mail-javamail-mime-attachments-inline]] ===== Inline resources + The following example shows you how to use the `MimeMessageHelper` to send an email along with an inline image. @@ -5916,9 +5902,9 @@ 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, using methods calls such as `message.setText(..)`. This is fine for simple cases, and it is okay in the context of the aforementioned examples, where the intent was to show you @@ -5941,14 +5927,15 @@ FreeMarker becomes quite easy to do. + [[scheduling]] == Task Execution and Scheduling - [[scheduling-introduction]] === Introduction + The Spring Framework provides abstractions for asynchronous execution and scheduling of tasks with the `TaskExecutor` and `TaskScheduler` interfaces, respectively. Spring also features implementations of those interfaces that support thread pools or delegation to @@ -5966,21 +5953,19 @@ operation). - [[scheduling-task-executor]] === The Spring TaskExecutor abstraction -Spring 2.0 introduces a new abstraction for dealing with executors. Executors are the -Java 5 name for the concept of thread pools. The "executor" naming is due to the fact -that there is no guarantee that the underlying implementation is actually a pool; an -executor may be single-threaded or even synchronous. Spring's abstraction hides -implementation details between Java SE 1.4, Java SE 5 and Java EE environments. +Executors are the JDK name for the concept of thread pools. The "executor" naming is +due to the fact that there is no guarantee that the underlying implementation is +actually a pool; an executor may be single-threaded or even synchronous. Spring's +abstraction hides implementation details between Java SE and Java EE environments. Spring's `TaskExecutor` interface is identical to the `java.util.concurrent.Executor` -interface. In fact, its primary reason for existence was to abstract away the need for -Java 5 when using thread pools. The interface has a single method `execute(Runnable -task)` that accepts a task for execution based on the semantics and configuration of the -thread pool. +interface. In fact, originally, its primary reason for existence was to abstract away +the need for Java 5 when using thread pools. The interface has a single method +`execute(Runnable task)` that accepts a task for execution based on the semantics +and configuration of the thread pool. The `TaskExecutor` was originally created to give other Spring components an abstraction for thread pooling where needed. Components such as the `ApplicationEventMulticaster`, @@ -5989,7 +5974,6 @@ JMS's `AbstractMessageListenerContainer`, and Quartz integration all use the behavior, it is possible to use this abstraction for your own needs. - [[scheduling-task-executor-types]] ==== TaskExecutor types @@ -6039,7 +6023,6 @@ context. Similar to the `SimpleThreadPoolTaskExecutor`, this class implements th `WorkManager` interface and therefore can be used directly as a `WorkManager` as well. - [[scheduling-task-executor-usage]] ==== Using a TaskExecutor @@ -6106,7 +6089,6 @@ been exposed. - [[scheduling-task-scheduler]] === The Spring TaskScheduler abstraction @@ -6140,7 +6122,6 @@ methods are for simple, periodic execution, but the method that accepts a Trigge much more flexible. - [[scheduling-trigger-interface]] ==== the Trigger interface @@ -6181,7 +6162,6 @@ default). Here you can see what methods are available for `Trigger` implementati ---- - [[scheduling-trigger-implementations]] ==== Trigger implementations @@ -6208,7 +6188,6 @@ Such a component could take advantage of dependency injection so that such `Trig could be configured externally and therefore easily modified or extended. - [[scheduling-task-scheduler-implementations]] ==== TaskScheduler implementations @@ -6229,16 +6208,16 @@ 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 `@EnableAsync` to one of your `@Configuration` classes: @@ -6272,9 +6251,9 @@ 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 example, the following method would be invoked every 5 seconds with a fixed delay, meaning that the period will be measured from the completion time of each preceding @@ -6350,9 +6329,9 @@ container and once through the `@Configurable` aspect, with the consequence of e ==== - [[scheduling-annotation-support-async]] ==== The @Async annotation + The `@Async` annotation can be provided on a method so that invocation of that method will occur asynchronously. In other words, the caller will return immediately upon invocation and the actual execution of the method will occur in a task that has been @@ -6446,9 +6425,9 @@ in combination with a custom pointcut. ==== - [[scheduling-annotation-support-qualification]] ==== Executor qualification with @Async + By default when specifying `@Async` on a method, the executor that will be used is the one supplied to the 'annotation-driven' element as described above. However, the `value` attribute of the `@Async` annotation can be used when needing to indicate that an @@ -6468,9 +6447,9 @@ container, or may be the name of a __qualifier__ associated with any `Executor`, specified with the `` element or Spring's `@Qualifier` annotation. - [[scheduling-annotation-support-exception]] ==== Exception management with @Async + When an `@Async` method has a `Future` typed return value, it is easy to manage an exception that was thrown during the method execution as this exception will be thrown when calling `get` on the `Future` result. With a void return type @@ -6494,17 +6473,17 @@ be defined _via_ `AsyncConfigurer` or the `task:annotation-driven` XML element. - [[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 specified thread pool size. @@ -6520,9 +6499,9 @@ provide a 'pool-size' attribute, the default thread pool will only have a single There are no other configuration options for the scheduler. - [[scheduling-task-namespace-executor]] ==== The 'executor' element + The following will create a `ThreadPoolTaskExecutor` instance: [source,xml,indent=0] @@ -6614,9 +6593,9 @@ immediately after executing a task without remaining follow-up work in the task ---- - [[scheduling-task-namespace-scheduled-tasks]] ==== The 'scheduled-tasks' element + The most powerful feature of Spring's task namespace is the support for configuring tasks to be scheduled within a Spring Application Context. This follows an approach similar to other "method-invokers" in Spring, such as that provided by the JMS namespace @@ -6658,18 +6637,18 @@ 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 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 JobDetailFactoryBean + Quartz `JobDetail` objects contain all information needed to run a job. Spring provides a `JobDetailFactoryBean` which provides bean-style properties for XML configuration purposes. Let's have a look at an example: @@ -6728,7 +6707,6 @@ of the `JobDetailFactoryBean` (in the example above, this is `exampleJob`). ==== - [[scheduling-quartz-method-invoking-job]] ==== Using the MethodInvokingJobDetailFactoryBean @@ -6794,7 +6772,6 @@ By default, jobs will run in a concurrent fashion. ==== - [[scheduling-quartz-cron]] ==== Wiring up jobs using triggers and the SchedulerFactoryBean @@ -6855,14 +6832,15 @@ javadocs] for more information. + [[dynamic-language]] == Dynamic language support - [[dynamic-language-introduction]] === Introduction + Spring 2.0 introduces comprehensive support for using classes and objects that have been defined using a dynamic language (such as JRuby) with Spring. This support allows you to write any number of classes in a supported dynamic language, and have the Spring @@ -6888,9 +6866,9 @@ are described in <>. - [[dynamic-language-a-first-example]] === A first example + This bulk of this chapter is concerned with describing the dynamic language support in detail. Before diving into all of the ins and outs of the dynamic language support, let's look at a quick example of a bean defined in a dynamic language. The dynamic @@ -7007,9 +6985,9 @@ 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 supported dynamic languages. @@ -7020,9 +6998,9 @@ 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: * Write the test for the dynamic language source code (naturally) @@ -7042,9 +7020,9 @@ 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 + The final step involves defining dynamic-language-backed bean definitions, one for each bean that you want to configure (this is no different from normal JavaBean configuration). However, instead of specifying the fully qualified classname of the @@ -7053,17 +7031,17 @@ class that is to be instantiated and configured by the container, you use the Each of the supported languages has a corresponding `` element: -* `` (JRuby) * `` (Groovy) * `` (BeanShell) +* `` (JSR-223) The exact attributes and child elements that are available for configuration depends on 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 in Spring is the__'refreshable bean'__ feature. @@ -7195,9 +7173,9 @@ 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 embedded directly in Spring bean definitions. More specifically, the `` element allows you to define dynamic language source immediately @@ -7230,41 +7208,9 @@ Spring `Validator` implementation to a Spring MVC `Controller`. This is but a mo work using inline source. (See <> for such an example.) -Find below an example of defining the source for a JRuby-based bean directly in a Spring -XML configuration file using the `inline:` notation. (Notice the use of the < -characters to denote a `'<'` character. In such a case surrounding the inline source in -a `` region might be better.) - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - require 'java' - - include_class 'org.springframework.scripting.Messenger' - - class RubyMessenger < Messenger - - def setMessage(message) - @@message = message - end - - def getMessage - @@message - end - - 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 language support. Namely, it is not (currently) possible to supply constructor arguments to dynamic-language-backed beans (and hence constructor-injection is not available for @@ -7316,136 +7262,6 @@ injection is the injection style favored by the overwhelming majority of develop anyway (let's leave the discussion as to whether that is a good thing to another day). - -[[dynamic-language-beans-jruby]] -==== JRuby beans - -.The JRuby library dependencies -**** -The JRuby scripting support in Spring requires the following libraries to be on the -classpath of your application. - -* `jruby.jar` -**** - -From the JRuby homepage... - -"__JRuby is an 100% pure-Java implementation of the Ruby programming language.__" - -In keeping with the Spring philosophy of offering choice, Spring's dynamic language -support also supports beans defined in the JRuby language. The JRuby language is based -on the quite intuitive Ruby language, and has support for inline regular expressions, -blocks (closures), and a whole host of other features that do make solutions for some -domain problems a whole lot easier to develop. - -The implementation of the JRuby dynamic language support in Spring is interesting in -that what happens is this: Spring creates a JDK dynamic proxy implementing all of the -interfaces that are specified in the `'script-interfaces'` attribute value of the -`` element (this is why you __must__ supply at least one interface in the -value of the attribute, and (accordingly) program to interfaces when using JRuby-backed -beans). - -Let us look at a fully working example of using a JRuby-based bean. Here is the JRuby -implementation of the `Messenger` interface that was defined earlier in this chapter -(for your convenience it is repeated below). - -[source,ruby,indent=0] -[subs="verbatim,quotes"] ----- - package org.springframework.scripting; - - public interface Messenger { - - String getMessage(); - - } ----- - -[source,ruby,indent=0] -[subs="verbatim,quotes"] ----- - require 'java' - - class RubyMessenger - include org.springframework.scripting.Messenger - - def setMessage(message) - @@message = message - end - - def getMessage - @@message - end - end - - # this last line is not essential (but see below) - RubyMessenger.new ----- - -And here is the Spring XML that defines an instance of the `RubyMessenger` JRuby bean. - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - - ----- - -Take note of the last line of that JRuby source ( `'RubyMessenger.new'`). When using -JRuby in the context of Spring's dynamic language support, you are encouraged to -instantiate and return a new instance of the JRuby class that you want to use as a -dynamic-language-backed bean as the result of the execution of your JRuby source. You -can achieve this by simply instantiating a new instance of your JRuby class on the last -line of the source file like so: - -[source,ruby,indent=0] -[subs="verbatim,quotes"] ----- - require 'java' - - include_class 'org.springframework.scripting.Messenger' - - # class definition same as above... - - # instantiate and return a new instance of the RubyMessenger class - RubyMessenger.new ----- - -If you forget to do this, it is not the end of the world; this will however result in -Spring having to trawl (reflectively) through the type representation of your JRuby -class looking for a class to instantiate. In the grand scheme of things this will be so -fast that you'll never notice it, but it is something that can be avoided by simply -having a line such as the one above as the last line of your JRuby script. If you don't -supply such a line, or if Spring cannot find a JRuby class in your script to instantiate -then an opaque `ScriptCompilationException` will be thrown immediately after the source -is executed by the JRuby interpreter. The key text that identifies this as the root -cause of an exception can be found immediately below (so if your Spring container throws -the following exception when creating your dynamic-language-backed bean and the -following text is there in the corresponding stacktrace, this will hopefully allow you -to identify and then easily rectify the issue): - -[literal] -[subs="verbatim,quotes"] ----- -org.springframework.scripting.ScriptCompilationException: Compilation of JRuby script returned '' ----- - -To rectify this, simply instantiate a new instance of whichever class you want to expose -as a JRuby-dynamic-language-backed bean (as shown above). Please also note that you can -actually define as many classes and objects as you want in your JRuby script; what is -important is that the source file as a whole must return an object (for Spring to -configure). - -See <> for some scenarios where you might want to use -JRuby-based beans. - - - [[dynamic-language-beans-groovy]] ==== Groovy beans @@ -7538,9 +7354,9 @@ 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]] ===== Customizing Groovy objects via a callback + The `GroovyObjectCustomizer` interface is a callback that allows you to hook additional creation logic into the process of creating a Groovy-backed bean. For example, implementations of this interface could invoke any required initialization method(s), or @@ -7623,7 +7439,6 @@ in the same place as Spring's `GroovyObjectCustomizer`. ==== - [[dynamic-language-beans-bsh]] ==== BeanShell beans @@ -7703,17 +7518,17 @@ 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 of Spring MVC controllers. In pure Spring MVC applications, the navigational flow through a web application is to a large extent determined by code encapsulated within @@ -7778,9 +7593,9 @@ using the Groovy dynamic language. ---- - [[dynamic-language-scenarios-validators]] ==== Scripted Validators + Another area of application development with Spring that may benefit from the flexibility afforded by dynamic-language-backed beans is that of validation. It __may__ be easier to express complex validation logic using a loosely typed dynamic language @@ -7829,15 +7644,15 @@ Validation using Spring’s Validator interface>> for a discussion of the - [[dynamic-language-final-notes]] === Bits and bobs -This last section contains some bits and bobs related to the dynamic language support. +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 framework actually is unaware that a bean that is being advised might be a scripted bean, so all of the AOP use cases and functionality that you may be using or aim to use @@ -7851,9 +7666,9 @@ Spring beans. This really would be an advanced use of the dynamic language suppo though. - [[dynamic-language-final-notes-scopes]] ==== Scoping + In case it is not immediately obvious, scripted beans can of course be scoped just like any other bean. The `scope` attribute on the various `` elements allows you to control the scope of the underlying scripted bean, just as it does with a regular @@ -7889,9 +7704,9 @@ 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 this chapter. @@ -7900,6 +7715,8 @@ this chapter. * The http://www.beanshell.org/[BeanShell] homepage + + [[cache]] == Cache Abstraction @@ -7907,6 +7724,7 @@ this chapter. [[cache-introduction]] === Introduction + Since version 3.1, Spring Framework provides support for transparently adding caching into an existing Spring application. Similar to the <> support, the caching abstraction allows consistent use of various caching solutions with minimal @@ -7919,6 +7737,7 @@ support of <> and more customization options. [[cache-strategies]] === Understanding the cache abstraction + .Cache vs Buffer **** @@ -7999,8 +7818,10 @@ To use the cache abstraction, the developer needs to take care of two aspects: * cache configuration - the backing cache where the data is stored and read from + [[cache-annotations]] === Declarative annotation-based caching + For caching declaration, the abstraction provides a set of Java annotations: * `@Cacheable` triggers cache population @@ -8011,6 +7832,7 @@ For caching declaration, the abstraction provides a set of Java annotations: Let us take a closer look at each annotation: + [[cache-annotations-cacheable]] ==== @Cacheable annotation @@ -8048,9 +7870,9 @@ 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 to be translated into a suitable key for cache access. Out of the box, the caching abstraction uses a simple `KeyGenerator` based on the following algorithm: @@ -8080,9 +7902,9 @@ If you want to keep using the previous key strategy, you can configure the depre hash-based 'KeyGenerator' implementation. ==== - [[cache-annotations-cacheable-key]] ===== Custom Key Generation Declaration + Since caching is generic, it is quite likely the target methods have various signatures that cannot be simply mapped on top of the cache structure. This tends to become obvious when the target method has multiple arguments out of which only some are suitable for @@ -8138,7 +7960,6 @@ this, specify the name of the `KeyGenerator` bean implementation to use: public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed) ---- - [NOTE] ==== The `key` and `keyGenerator` parameters are mutually exclusive and an operation @@ -8155,7 +7976,6 @@ retrieves the cache(s) defined at the operation level using the configured To provide a different __default__ cache resolver, one needs to implement the `org.springframework.cache.interceptor.CacheResolver` interface. - [[cache-annotations-cacheable-cache-resolver]] ===== Custom cache resolution @@ -8199,6 +8019,7 @@ result in an exception as a custom `CacheManager` will be ignored by the [[cache-annotations-cacheable-synchronized]] ===== Synchronized caching + In a multi-threaded environment, certain operations might be concurrently invoked for the same argument (typically on startup). By default, the cache abstraction does not lock anything and the same value may be computed several times, defeating the purpose @@ -8223,9 +8044,9 @@ This is an optional feature and your favorite cache library may not support it. documentation of your cache provider for more details. ==== - [[cache-annotations-cacheable-condition]] ===== Conditional caching + Sometimes, a method might not be suitable for caching all the time (for example, it might depend on the given arguments). The cache annotations support such functionality through the `condition` parameter which takes a `SpEL` expression that is evaluated to @@ -8344,7 +8165,6 @@ than method flow optimization: public Book updateBook(ISBN isbn, BookDescriptor descriptor) ---- - [IMPORTANT] ==== Note that using `@CachePut` and `@Cacheable` annotations on the same method is generally @@ -8399,7 +8219,6 @@ cache) - this is not the case with `@Cacheable` which adds/updates data into the and thus requires a result. - [[cache-annotations-caching]] ==== @Caching annotation @@ -8448,8 +8267,10 @@ gives therefore three levels of customizations per cache operation: * At class level, using `@CacheConfig` * At the operation level + [[cache-annotation-enable]] ==== Enable caching annotations + It is important to note that even though declaring the cache annotations does not automatically trigger their actions - like many things in Spring, the feature has to be declaratively enabled (which means if you ever suspect caching is to blame, you can @@ -8603,7 +8424,6 @@ code, i.e. `@PostConstruct`. ==== - [[cache-annotation-stereotype]] ==== Using custom annotations @@ -8661,6 +8481,7 @@ up its declaration at runtime and understands its meaning. Note that as mentione <>, the annotation-driven behavior needs to be enabled. + [[cache-jsr-107]] === JCache (JSR-107) annotations @@ -8674,8 +8495,9 @@ compliant with the specification. In other words, if you are already using Sprin caching abstraction, you can switch to these standard annotations without changing your cache storage (or configuration, for that matter). + [[cache-jsr-107-summary]] -==== Features summary +==== Feature summary For those who are familiar with Spring's caching annotations, the following table describes the main differences between the Spring annotations and the JSR-107 @@ -8790,8 +8612,10 @@ caches, a consistent and identical key generation implementation should be used. ==== + [[cache-declarative-xml]] === Declarative XML-based caching + If annotations are not an option (no access to the sources or no external code), one can use XML for declarative caching. So instead of annotating the methods for caching, one specifies the target method and the caching directives externally (similar to the @@ -8845,9 +8669,9 @@ we did in the example above by defining the target cache through the `cache:defi - [[cache-store-configuration]] === Configuring the cache storage + Out of the box, the cache abstraction provides several storage integration. To use 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. @@ -8884,7 +8708,6 @@ very fast but it does not provide any management or persistence capabilities nor eviction contracts. - [[cache-store-configuration-ehcache]] ==== Ehcache-based Cache @@ -8908,6 +8731,7 @@ This setup bootstraps the ehcache library inside Spring IoC (through the `ehcach is then wired into the dedicated `CacheManager` implementation. Note the entire ehcache-specific configuration is read from `ehcache.xml`. + [[cache-store-configuration-caffeine]] ==== Caffeine Cache @@ -8944,6 +8768,7 @@ The Caffeine `CacheManager` also supports customs `Caffeine` and `CacheLoader`. the https://github.com/ben-manes/caffeine/wiki[Caffeine documentation] for more information about those. + [[cache-store-configuration-gemfire]] ==== GemFire-based Cache @@ -8953,6 +8778,7 @@ database and provides fully-featured edge caching. For further information on ho GemFire as a CacheManager (and more), please refer to the {doc-spring-gemfire}/html/[Spring Data GemFire reference documentation]. + [[cache-store-configuration-jsr107]] ==== JSR-107 Cache @@ -8975,6 +8801,7 @@ Again, to use it, one simply needs to declare the appropriate `CacheManager`: [[cache-store-configuration-noop]] ==== Dealing with caches without a backing store + Sometimes when switching environments or doing testing, one might have cache declarations without an actual backing cache configured. As this is an invalid configuration, at runtime an exception will be thrown since the caching infrastructure @@ -9005,9 +8832,9 @@ 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 store. To plug them in, one needs to provide a `CacheManager` and `Cache` implementation since unfortunately there is no available standard that we can use instead. This may @@ -9021,9 +8848,9 @@ 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 not a cache implementation. The solution you are using might support various data policies and different topologies which other solutions do not (take for example the JDK @@ -9032,4 +8859,6 @@ because there would no backing support. Such functionality should be controlled through the backing cache, when configuring it or through its native API. + + include::integration-appendix.adoc[leveloffset=+1] diff --git a/src/docs/asciidoc/kotlin.adoc b/src/docs/asciidoc/kotlin.adoc index dabdd239e3c..34761c40d0e 100644 --- a/src/docs/asciidoc/kotlin.adoc +++ b/src/docs/asciidoc/kotlin.adoc @@ -6,6 +6,9 @@ :toclevels: 4 :docinfo1: + + + [[introduction]] == Introduction @@ -17,8 +20,11 @@ existing libraries written in Java. Spring Framework 5 introduces first-class support for Kotlin and allows developers to write Spring + Kotlin applications almost as if the Spring Framework was a native Kotlin framework. + + + [[requirements]] -== Requirements == +== Requirements Spring Framework supports Kotlin 1.1+ and requires https://bintray.com/bintray/jcenter/org.jetbrains.kotlin%3Akotlin-stdlib[`kotlin-stdlib`] @@ -28,6 +34,9 @@ and https://bintray.com/bintray/jcenter/org.jetbrains.kotlin%3Akotlin-reflect[`k to be present on the classpath. They are provided by default if one bootstraps a Kotlin project on https://start.spring.io/#!language=kotlin[start.spring.io]. + + + [[extensions]] == Extensions @@ -77,6 +86,9 @@ val users : Flux = client.get().retrieve().bodyToFlux() As in Java, `users` in Kotlin is strongly typed, but Kotlin's clever type inference allows for shorter syntax. + + + [[null-safety]] == Null-safety @@ -117,6 +129,9 @@ but should be in an upcoming release, see https://github.com/Kotlin/KEEP/issues/ for up-to-date information. ==== + + + [[classes-interfaces]] == Classes & Interfaces @@ -138,6 +153,9 @@ detected without the Jackson Kotlin module present. As of Spring Boot 2.0, Jackson Kotlin module is automatically provided via the JSON starter. ==== + + + [[annotations]] == Annotations @@ -152,6 +170,9 @@ to determine if a bean is required or not. `@Autowired lateinit var foo: Foo` im of type `Foo` must be registered in the application context while `@Autowired lateinit var foo: Foo?` won’t raise an error if such bean does not exist. + + + [[bean-definition-dsl]] == Bean definition DSL @@ -251,9 +272,14 @@ see https://stackoverflow.com/questions/45935931/how-to-use-functional-bean-defi for more details and up-to-date information. ==== + + + [[web]] == Web + + === WebFlux Functional DSL Spring Framework now comes with a @@ -291,6 +317,8 @@ depending on dynamic data (for example, from a database). See https://github.com/mixitconf/mixit/tree/bad6b92bce6193f9b3f696af9d416c276501dbf1/src/main/kotlin/mixit/web/routes[MiXiT project routes] for a concrete example. + + === Kotlin Script templates As of version 4.3, Spring Framework provides a @@ -326,12 +354,17 @@ ${include("footer")} See https://github.com/sdeleuze/kotlin-script-templating[kotlin-script-templating] example project for more details. + + + [[spring-projects-in-kotlin]] == Spring projects in Kotlin This section provides focus on some specific hints and recommendations worth knowing when developing Spring projects in Kotlin. + + === Final by default By default, https://discuss.kotlinlang.org/t/classes-final-by-default/166[all classes in Kotlin are `final`]. @@ -365,6 +398,8 @@ annotations are meta-annotated with `@Component`. http://start.spring.io/#!language=kotlin[start.spring.io] enables it by default, so in practice you will be able to write your Kotlin beans without any additional `open` keyword, like in Java. + + === Using immutable class instances for persistence In Kotlin, it is very convenient and considered best practice to declare @@ -414,6 +449,8 @@ and should not require `kotlin-noarg` plugin if the module leverages Spring Data mapping (like with MongoDB, Redis, Cassandra, etc.). ==== + + === Injecting dependencies Our recommendation is to try and favor constructor injection with `val` read-only (and non-nullable when possible) @@ -451,6 +488,8 @@ class YourBean { } ---- + + === Injecting configuration properties In Java, one can inject configuration properties using annotations like `@Value("${property}")`, @@ -498,6 +537,8 @@ and https://github.com/spring-projects/spring-boot/issues/1254[`@ConfigurationPr for more details. ==== + + === Annotation array attributes Kotlin annotations are mostly similar to Java ones, but array attributes - which are @@ -548,8 +589,11 @@ not only the `GET` methods. Improving the syntax and consistency of Kotlin annotation array attributes is discussed in https://youtrack.jetbrains.com/issue/KT-11235[this Kotlin language design issue]. + + === Testing + ==== Per class lifecycle Kotlin allows one to specify meaningful test function names between backticks, @@ -591,6 +635,7 @@ class IntegrationTests { } ---- + ==== Specification-like tests It is possible to create specification-like tests with JUnit 5 and Kotlin. @@ -620,9 +665,13 @@ class SpecificationLikeTests { ---- + + [[getting-started]] == Getting started + + === start.spring.io The easiest way to start a new Spring Framework 5 project in Kotlin is to create a new Spring @@ -631,6 +680,8 @@ Boot 2 project on https://start.spring.io/#!language=kotlin[start.spring.io]. It is also possible to create a standalone WebFlux project as described in https://spring.io/blog/2017/08/01/spring-framework-5-kotlin-apis-the-functional-way[this blog post]. + + === Choosing the web flavor Spring Framework now comes with 2 different web stacks: <> and @@ -643,6 +694,9 @@ Kotlin DSL. For other use cases, especially if you are using blocking technologies like JPA, Spring MVC and its annotation-based programming model is a perfectly valid and fully supported choice. + + + [[resources-started]] == Resources @@ -652,6 +706,8 @@ MVC and its annotation-based programming model is a perfectly valid and fully su * https://blog.jetbrains.com/kotlin/[Kotlin blog] * https://kotlin.link/[Awesome Kotlin] + + === Blog posts * https://spring.io/blog/2016/02/15/developing-spring-boot-applications-with-kotlin[Developing Spring Boot applications with Kotlin] @@ -659,6 +715,8 @@ MVC and its annotation-based programming model is a perfectly valid and fully su * https://spring.io/blog/2017/01/04/introducing-kotlin-support-in-spring-framework-5-0[Introducing Kotlin support in Spring Framework 5.0] * https://spring.io/blog/2017/08/01/spring-framework-5-kotlin-apis-the-functional-way[Spring Framework 5 Kotlin APIs, the functional way] + + === Examples * https://github.com/sdeleuze/spring-boot-kotlin-demo[spring-boot-kotlin-demo]: regular Spring Boot + Spring Data JPA project @@ -667,18 +725,24 @@ MVC and its annotation-based programming model is a perfectly valid and fully su * https://github.com/sdeleuze/spring-kotlin-fullstack[spring-kotlin-fullstack]: WebFlux Kotlin fullstack example with Kotlin2js for frontend instead of JavaScript or TypeScript * https://github.com/spring-petclinic/spring-petclinic-kotlin[spring-petclinic-kotlin]: Kotlin version of the Spring PetClinic Sample Application + + === Tutorials * https://kotlinlang.org/docs/tutorials/spring-boot-restful.html[Creating a RESTful Web Service with Spring Boot] + + === Issues Here is a list of pending issues related to Spring + Kotlin support. + ==== Spring Framework * https://jira.spring.io/browse/SPR-15413[Add support for Kotlin coroutines] + ==== Spring Boot * https://github.com/spring-projects/spring-boot/issues/5537[Improve Kotlin support] @@ -687,6 +751,7 @@ Here is a list of pending issues related to Spring + Kotlin support. * https://github.com/spring-projects/spring-boot/issues/8511[Provide support for Kotlin KClass parameter in `SpringApplication.run()`] * https://github.com/spring-projects/spring-boot/issues/8115[Expose the functional bean registration API via `SpringApplication`] + ==== Kotlin * https://github.com/Kotlin/KEEP/issues/79[Better generics null-safety support] diff --git a/src/docs/asciidoc/overview.adoc b/src/docs/asciidoc/overview.adoc index aac243a31e1..002b8906100 100644 --- a/src/docs/asciidoc/overview.adoc +++ b/src/docs/asciidoc/overview.adoc @@ -21,6 +21,9 @@ Spring is open source. It has a large and active community that provides continu based on a diverse range of real-world use cases. This has helped Spring to successfully evolve over a very long time. + + + [[overview-spring]] == What We Mean by "Spring" @@ -44,6 +47,9 @@ A note about modules: Spring's framework jars allow for deployment to JDK 9's mo the same naming pattern with "-" instead of ".", e.g. "spring-core" and "spring-context"). Of course, Spring's framework jars keep working fine on the classpath on both JDK 8 and 9. + + + [[overview-history]] == History of Spring and the Spring Framework @@ -85,6 +91,9 @@ among others. It’s important to remember that each project has its own source issue tracker, and release cadence. See https://spring.io/projects[spring.io/projects] for the complete list of Spring projects. + + + [[overview-philosophy]] == Design Philosophy @@ -108,6 +117,9 @@ that are intuitive and that hold up across many versions and many years. meaningful, current, and accurate Javadoc. It is one of very few projects that can claim clean code structure with no circular dependencies between packages. + + + [[overview-feedback]] == Feedback and Contributions @@ -128,6 +140,9 @@ information that is not specific to any one version. For example, it has migrati notes from earlier versions, comprehensive information on what's new across multiple versions, contributor guidelines, the Spring Framework code style, and other information. + + + [[overview-getting-started]] == Getting Started diff --git a/src/docs/asciidoc/testing-webtestclient.adoc b/src/docs/asciidoc/testing-webtestclient.adoc index dd332d668f6..31740d49d22 100644 --- a/src/docs/asciidoc/testing-webtestclient.adoc +++ b/src/docs/asciidoc/testing-webtestclient.adoc @@ -10,6 +10,7 @@ without the need for an HTTP server. + [[webtestclient-setup]] == Setup @@ -18,6 +19,7 @@ Effectively you either configure a WebFlux application to bind to, or use absolu to connect to a running server. + [[webtestclient-controller-config]] === Bind to controller @@ -35,6 +37,7 @@ without an HTTP server using mock request and response objects. There are more m on the builder to customize the default WebFlux Java config. + [[webtestclient-fn-config]] === Bind to RouterFunction @@ -53,6 +56,7 @@ The resulting WebFlux application will be tested without an HTTP server using mo request and response objects. + [[webtestclient-context-config]] === Bind to ApplicationContext @@ -90,6 +94,7 @@ resulting WebFlux application will be tested without an HTTP server using mock r and response objects. + [[webtestclient-server-config]] === Bind to server @@ -284,6 +289,3 @@ from the `reactor-test` module to do that, for example: .thenCancel() .verify(); ---- - - - diff --git a/src/docs/asciidoc/testing.adoc b/src/docs/asciidoc/testing.adoc index d98ec82289f..183d156cf14 100644 --- a/src/docs/asciidoc/testing.adoc +++ b/src/docs/asciidoc/testing.adoc @@ -17,8 +17,11 @@ set up service locator registries and suchlike)... the chapter dedicated solely testing will hopefully convince you of this as well. + + [[testing-introduction]] == Introduction to Spring Testing + Testing is an integral part of enterprise software development. This chapter focuses on the value-add of the IoC principle to <> and on the benefits of the Spring Framework's support for <>. __(A @@ -26,8 +29,11 @@ thorough treatment of testing in the enterprise is beyond the scope of this refe manual.)__ + + [[unit-testing]] == Unit Testing + Dependency Injection should make your code less dependent on the container than it would be with traditional Java EE development. The POJOs that make up your application should be testable in JUnit or TestNG tests, with objects simply instantiated using the `new` @@ -54,6 +60,7 @@ support classes. [[mock-objects-env]] ==== Environment + The `org.springframework.mock.env` package contains mock implementations of the `Environment` and `PropertySource` abstractions (see <> @@ -64,6 +71,7 @@ __out-of-container__ tests for code that depends on environment-specific propert [[mock-objects-jndi]] ==== JNDI + The `org.springframework.mock.jndi` package contains an implementation of the JNDI SPI, which you can use to set up a simple JNDI environment for test suites or stand-alone applications. If, for example, JDBC ``DataSource``s get bound to the same JNDI names in @@ -73,6 +81,7 @@ configuration in testing scenarios without modification. [[mock-objects-servlet]] ==== Servlet API + The `org.springframework.mock.web` package contains a comprehensive set of Servlet API mock objects that are useful for testing web contexts, controllers, and filters. These mock objects are targeted at usage with Spring's Web MVC framework and are generally more @@ -92,6 +101,7 @@ integration testing framework for Spring MVC. See [[mock-objects-web-reactive]] ==== Spring Web Reactive + The package `org.springframework.mock.http.server.reactive` contains mock implementations of `ServerHttpRequest` and `ServerHttpResponse` for use in WebFlux applications. The package `org.springframework.mock.web.server` @@ -114,12 +124,14 @@ testing WebFlux applications without an HTTP server. The client can also be used end-to-end tests with a running server. + [[unit-testing-support-classes]] === Unit Testing support Classes [[unit-testing-utilities]] ==== General testing utilities + The `org.springframework.test.util` package contains several general purpose utilities for use in unit and integration testing. @@ -145,9 +157,9 @@ access to the underlying mock in order to configure expectations on it and perfo verifications. For Spring's core AOP utilities, see `AopUtils` and `AopProxyUtils`. - [[unit-testing-spring-mvc]] ==== Spring MVC + The `org.springframework.test.web` package contains `ModelAndViewAssert`, which you can use in combination with JUnit, TestNG, or any other testing framework for unit tests dealing with Spring MVC `ModelAndView` objects. @@ -173,6 +185,7 @@ Framework_>> instead. [[integration-testing-overview]] === Overview + It is important to be able to perform some integration testing without requiring deployment to your application server or connecting to other enterprise infrastructure. This will enable you to test things such as: @@ -200,6 +213,7 @@ instrumentation of tests in various environments including JUnit, TestNG, and so [[integration-testing-goals]] === Goals of Integration Testing + Spring's integration testing support has the following primary goals: * To manage <> between test @@ -215,6 +229,7 @@ configuration details. [[testing-ctx-management]] ==== Context management and caching + The Spring TestContext Framework provides consistent loading of Spring ``ApplicationContext``s and ``WebApplicationContext``s as well as caching of those contexts. Support for the caching of loaded contexts is important, because startup time @@ -245,6 +260,7 @@ TestContext framework. [[testing-fixture-di]] ==== Dependency Injection of test fixtures + When the TestContext framework loads your application context, it can optionally configure instances of your test classes via Dependency Injection. This provides a convenient mechanism for setting up test fixtures using preconfigured beans from your @@ -270,6 +286,7 @@ framework>>. [[testing-tx]] ==== Transaction management + One common issue in tests that access a real database is their effect on the state of the persistence store. Even when you're using a development database, changes to the state may affect future tests. Also, many operations -- such as inserting or modifying @@ -295,6 +312,7 @@ See transaction management with the <>. [[testing-support-classes]] ==== Support classes for integration testing + The Spring TestContext Framework provides several `abstract` support classes that simplify the writing of integration tests. These base test classes provide well-defined hooks into the testing framework as well as convenient instance variables and methods, @@ -317,6 +335,7 @@ See support classes for the < [[integration-testing-support-jdbc]] === JDBC Testing Support + The `org.springframework.test.jdbc` package contains `JdbcTestUtils`, which is a collection of JDBC related utility functions intended to simplify standard database testing scenarios. Specifically, `JdbcTestUtils` provides the following static utility @@ -348,20 +367,24 @@ with an embedded database>>. === Annotations + [[integration-testing-annotations-spring]] ==== Spring Testing Annotations + The Spring Framework provides the following set of __Spring-specific__ annotations that you can use in your unit and integration tests in conjunction with the TestContext framework. Refer to the corresponding javadocs for further information, including default attribute values, attribute aliases, and so on. ===== @BootstrapWith + `@BootstrapWith` is a class-level annotation that is used to configure how the _Spring TestContext Framework_ is bootstrapped. Specifically, `@BootstrapWith` is used to specify a custom `TestContextBootstrapper`. Consult the <> section for further details. ===== @ContextConfiguration + `@ContextConfiguration` defines class-level metadata that is used to determine how to load and configure an `ApplicationContext` for integration tests. Specifically, `@ContextConfiguration` declares the application context resource `locations` or the @@ -427,6 +450,7 @@ See <> and the `@ContextConfiguration` javadocs for further details. ===== @WebAppConfiguration + `@WebAppConfiguration` is a class-level annotation that is used to declare that the `ApplicationContext` loaded for an integration test should be a `WebApplicationContext`. The mere presence of `@WebAppConfiguration` on a test class ensures that a @@ -465,6 +489,7 @@ Note that `@WebAppConfiguration` must be used in conjunction with hierarchy. See the `@WebAppConfiguration` javadocs for further details. ===== @ContextHierarchy + `@ContextHierarchy` is a class-level annotation that is used to define a hierarchy of ``ApplicationContext``s for integration tests. `@ContextHierarchy` should be declared with a list of one or more `@ContextConfiguration` instances, each of which defines a @@ -505,6 +530,7 @@ corresponding level in the class hierarchy. See for further examples. ===== @ActiveProfiles + `@ActiveProfiles` is a class-level annotation that is used to declare which __bean definition profiles__ should be active when loading an `ApplicationContext` for an integration test. @@ -542,6 +568,7 @@ See <> and the `@ActiveProfiles` javado for examples and further details. ===== @TestPropertySource + `@TestPropertySource` is a class-level annotation that is used to configure the locations of properties files and inlined properties to be added to the set of `PropertySources` in the `Environment` for an `ApplicationContext` loaded for an integration test. @@ -578,6 +605,7 @@ The following example demonstrates how to declare _inlined_ properties. ---- ===== @DirtiesContext + `@DirtiesContext` indicates that the underlying Spring `ApplicationContext` has been __dirtied__ during the execution of a test (i.e., modified or corrupted in some manner -- for example, by changing the state of a singleton bean) and should be closed. When an @@ -724,6 +752,7 @@ For further details regarding the `EXHAUSTIVE` and `CURRENT_LEVEL` algorithms se `DirtiesContext.HierarchyMode` javadocs. ===== @TestExecutionListeners + `@TestExecutionListeners` defines class-level metadata for configuring the `TestExecutionListener` implementations that should be registered with the `TestContextManager`. Typically, `@TestExecutionListeners` is used in conjunction with @@ -743,6 +772,7 @@ For further details regarding the `EXHAUSTIVE` and `CURRENT_LEVEL` algorithms se for an example and further details. ===== @Commit + `@Commit` indicates that the transaction for a transactional test method should be __committed__ after the test method has completed. `@Commit` can be used as a direct replacement for `@Rollback(false)` in order to more explicitly convey the intent of the @@ -760,6 +790,7 @@ method-level annotation. ---- ===== @Rollback + `@Rollback` indicates whether the transaction for a transactional test method should be __rolled back__ after the test method has completed. If `true`, the transaction is rolled back; otherwise, the transaction is committed (see also `@Commit`). Rollback semantics @@ -782,6 +813,7 @@ method, potentially overriding class-level `@Rollback` or `@Commit` semantics. ---- ===== @BeforeTransaction + `@BeforeTransaction` indicates that the annotated `void` method should be executed __before__ a transaction is started for test methods configured to run within a transaction via Spring's `@Transactional` annotation. As of Spring Framework 4.3, @@ -798,6 +830,7 @@ transaction via Spring's `@Transactional` annotation. As of Spring Framework 4.3 ---- ===== @AfterTransaction + `@AfterTransaction` indicates that the annotated `void` method should be executed __after__ a transaction is ended for test methods configured to run within a transaction via Spring's `@Transactional` annotation. As of Spring Framework 4.3, `@AfterTransaction` @@ -814,6 +847,7 @@ default methods. ---- ===== @Sql + `@Sql` is used to annotate a test class or test method to configure SQL scripts to be executed against a given database during integration tests. @@ -830,6 +864,7 @@ executed against a given database during integration tests. See <> for further details. ===== @SqlConfig + `@SqlConfig` defines metadata that is used to determine how to parse and execute SQL scripts configured via the `@Sql` annotation. @@ -847,6 +882,7 @@ scripts configured via the `@Sql` annotation. ---- ===== @SqlGroup + `@SqlGroup` is a container annotation that aggregates several `@Sql` annotations. `@SqlGroup` can be used natively, declaring several nested `@Sql` annotations, or it can be used in conjunction with Java 8's support for repeatable annotations, where `@Sql` can @@ -869,6 +905,7 @@ container annotation. [[integration-testing-annotations-standard]] ==== Standard Annotation Support + The following annotations are supported with standard semantics for all configurations of the Spring TestContext Framework. Note that these annotations are not specific to tests and can be used anywhere in the Spring Framework. @@ -909,6 +946,7 @@ The following annotations are __only__ supported when used in conjunction with t 4 rules>>, or <>. ===== @IfProfileValue + `@IfProfileValue` indicates that the annotated test is enabled for a specific testing environment. If the configured `ProfileValueSource` returns a matching `value` for the provided `name`, the test is enabled. Otherwise, the test will be disabled and @@ -947,6 +985,7 @@ Consider the following example: ---- ===== @ProfileValueSourceConfiguration + `@ProfileValueSourceConfiguration` is a class-level annotation that specifies what type of `ProfileValueSource` to use when retrieving __profile values__ configured through the `@IfProfileValue` annotation. If `@ProfileValueSourceConfiguration` is not declared for a @@ -962,6 +1001,7 @@ test, `SystemProfileValueSource` is used by default. ---- ===== @Timed + `@Timed` indicates that the annotated test method must finish execution in a specified time period (in milliseconds). If the text execution time exceeds the specified time period, the test fails. @@ -986,6 +1026,7 @@ hand, does not preemptively fail the test but rather waits for the test to compl before failing. ===== @Repeat + `@Repeat` indicates that the annotated test method must be executed repeatedly. The number of times that the test method is to be executed is specified in the annotation. @@ -1002,6 +1043,7 @@ well as any __set up__ or __tear down__ of the test fixture. } ---- + [[integration-testing-annotations-junit-jupiter]] ==== Spring JUnit Jupiter Testing Annotations @@ -1149,6 +1191,7 @@ public @interface DisabledOnMac {} [[integration-testing-annotations-meta]] ==== Meta-Annotation Support for Testing + It is possible to use most test-related annotations as <> in order to create custom _composed annotations_ and reduce configuration duplication across a test suite. @@ -1313,8 +1356,10 @@ For further details, consult the <>. + [[testcontext-framework]] === Spring TestContext Framework + The __Spring TestContext Framework__ (located in the `org.springframework.test.context` package) provides generic, annotation-driven unit and integration testing support that is agnostic of the testing framework in use. The @@ -1341,6 +1386,7 @@ management>>), <>, and [[testcontext-key-abstractions]] ==== Key abstractions + The core of the framework consists of the `TestContextManager` class and the `TestContext`, `TestExecutionListener`, and `SmartContextLoader` interfaces. A `TestContextManager` is created per test class (e.g., for the execution of all test @@ -1354,12 +1400,14 @@ class. Consult the javadocs and the Spring test suite for further information an examples of various implementations. ===== TestContext + `TestContext` encapsulates the context in which a test is executed, agnostic of the actual testing framework in use, and provides context management and caching support for the test instance for which it is responsible. The `TestContext` also delegates to a `SmartContextLoader` to load an `ApplicationContext` if requested. ===== TestContextManager + `TestContextManager` is the main entry point into the __Spring TestContext Framework__ and is responsible for managing a single `TestContext` and signaling events to each registered `TestExecutionListener` at well-defined test execution points: @@ -1373,11 +1421,13 @@ registered `TestExecutionListener` at well-defined test execution points: * after any __after class__ or __after all__ methods of a particular testing framework ===== TestExecutionListener + `TestExecutionListener` defines the API for reacting to test execution events published by the `TestContextManager` with which the listener is registered. See <>. ===== Context Loaders + `ContextLoader` is a strategy interface that was introduced in Spring 2.5 for loading an `ApplicationContext` for an integration test managed by the Spring TestContext Framework. Implement `SmartContextLoader` instead of this interface in order to provide support for @@ -1419,6 +1469,7 @@ locations__. * `GenericPropertiesContextLoader`: loads a standard `ApplicationContext` from Java Properties files. + [[testcontext-bootstrapping]] ==== Bootstrapping the TestContext framework @@ -1444,6 +1495,7 @@ accommodate new requirements, implementers are strongly encouraged not to implem interface directly but rather to extend `AbstractTestContextBootstrapper` or one of its concrete subclasses instead. + [[testcontext-tel-config]] ==== TestExecutionListener configuration @@ -1883,6 +1935,7 @@ from, but you still have the freedom to include or import the other type of conf [[testcontext-ctx-management-initializers]] ===== Context configuration with context initializers + To configure an `ApplicationContext` for your tests using context initializers, annotate your test class with `@ContextConfiguration` and configure the `initializers` attribute with an array that contains references to classes that implement @@ -1929,6 +1982,7 @@ files or configuration classes. [[testcontext-ctx-management-inheritance]] ===== Context configuration inheritance + `@ContextConfiguration` supports boolean `inheritLocations` and `inheritInitializers` attributes that denote whether resource locations or annotated classes and context initializers declared by superclasses should be __inherited__. The default value for @@ -2017,6 +2071,7 @@ with Spring's `@Order` annotation or the standard `@Priority` annotation. [[testcontext-ctx-management-env-profiles]] ===== Context configuration with environment profiles + Spring 3.1 introduced first-class support in the framework for the notion of environments and profiles (a.k.a., __bean definition profiles__), and integration tests can be configured to activate particular bean definition profiles for various testing @@ -2511,6 +2566,7 @@ loaded using the _inlined_ `key1` and `key2` properties. [[testcontext-ctx-management-web]] ===== Loading a WebApplicationContext + Spring 3.2 introduced support for loading a `WebApplicationContext` in integration tests. To instruct the TestContext framework to load a `WebApplicationContext` instead of a standard `ApplicationContext`, simply annotate the respective test class with @@ -2904,6 +2960,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 default -- the dependencies of your test instances are __injected__ from beans in the application context that you configured with `@ContextConfiguration`. You may use setter @@ -3191,6 +3248,7 @@ configured theme. } ---- + [[testcontext-tx]] ==== Transaction management @@ -3293,6 +3351,7 @@ via the `@Commit` and `@Rollback` annotations. See the corresponding entries in [[testcontext-tx-programmatic-tx-mgt]] ===== Programmatic transaction management + Since Spring Framework 4.1, it is possible to interact with test-managed transactions _programmatically_ via the static methods in `TestTransaction`. For example, `TestTransaction` may be used within _test_ methods, _before_ methods, and _after_ @@ -3557,7 +3616,6 @@ and executing SQL scripts. Similarly, the `executeSqlScript(..)` methods in internally use a `ResourceDatabasePopulator` for executing SQL scripts. Consult the javadocs for the various `executeSqlScript(..)` methods for further details. - [[testcontext-executing-sql-declaratively]] ===== Executing SQL scripts declaratively with @Sql @@ -3817,10 +3875,10 @@ constructor; however, if you use a third-party library that provides a custom execution. ==== + [[testcontext-support-classes]] ==== TestContext Framework support classes - [[testcontext-junit4-runner]] ===== Spring JUnit 4 Runner @@ -3854,7 +3912,6 @@ public class SimpleTest { } ---- - [[testcontext-junit4-rules]] ===== Spring JUnit 4 Rules @@ -3898,7 +3955,6 @@ public class IntegrationTest { } ---- - [[testcontext-support-classes-junit4]] ===== JUnit 4 support classes @@ -3938,7 +3994,6 @@ by using `@RunWith(SpringRunner.class)` or <>. ==== - [[testcontext-junit-jupiter-extension]] ===== SpringExtension for JUnit Jupiter @@ -4027,7 +4082,6 @@ class SimpleWebTests { See the documentation for `@SpringJUnitConfig` and `@SpringJUnitWebConfig` in <> for further details. - [[testcontext-junit-jupiter-di]] ===== Dependency Injection with the SpringExtension @@ -4130,7 +4184,6 @@ class OrderServiceIntegrationTests { } ---- - [[testcontext-support-classes-testng]] ===== TestNG support classes @@ -4200,9 +4253,9 @@ integration tests, see <>. ==== - [[spring-mvc-test-server]] ==== Server-Side Tests + It's easy to write a plain unit test for a Spring MVC controller using JUnit or TestNG: simply instantiate the controller, inject it with mocked or stubbed dependencies, and call its methods passing `MockHttpServletRequest`, `MockHttpServletResponse`, etc., as necessary. @@ -4262,6 +4315,7 @@ request that will be discussed below. [[spring-mvc-test-server-static-imports]] ===== Static Imports + The fluent API in the example above requires a few static imports such as `MockMvcRequestBuilders.{asterisk}`, `MockMvcResultMatchers.{asterisk}`, and `MockMvcBuilders.{asterisk}`. An easy way to find these classes is to search for @@ -4274,6 +4328,7 @@ completion on static members. [[spring-mvc-test-server-setup-options]] ===== Setup Choices + There are two main options for creating an instance of `MockMvc`. The first is to load Spring MVC configuration through the __TestContext framework__, which loads the Spring configuration and injects a `WebApplicationContext` @@ -4418,10 +4473,9 @@ MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new TestController()) See `ConfigurableMockMvcBuilder` for a list of all MockMvc builder features or use the IDE to explore the available options. - - [[spring-mvc-test-server-performing-requests]] ===== Performing Requests + It's easy to perform requests using any HTTP method: [source,java,indent=0] @@ -4498,6 +4552,7 @@ specified on every request. [[spring-mvc-test-server-defining-expectations]] ===== Defining Expectations + Expectations can be defined by appending one or more `.andExpect(..)` calls after performing a request: @@ -4604,6 +4659,7 @@ be verified using XPath expressions: [[spring-mvc-test-server-filters]] ===== Filter Registrations + When setting up a `MockMvc` instance, you can register one or more Servlet `Filter` instances: [source,java,indent=0] @@ -4662,9 +4718,9 @@ integration tests. At the same time it's important not to lose sight of the fact the response is the most important thing to check. In short, there is room here for multiple styles and strategies of testing even within the same project. - [[spring-mvc-test-server-resources]] ===== Further Server-Side Test Examples + The framework's own tests include https://github.com/spring-projects/spring-framework/tree/master/spring-test/src/test/java/org/springframework/test/web/servlet/samples[many sample tests] intended to demonstrate how to use Spring MVC Test. Browse these examples @@ -5336,7 +5392,6 @@ For additional information on creating a `MockMvc` instance refer to In the previous section, we saw how to use `MockMvc` with `WebDriver`. In this section, we will use http://www.gebish.org/[Geb] to make our tests even Groovy-er. - [[spring-mvc-test-server-htmlunit-geb-why]] ====== Why Geb and MockMvc? @@ -5467,6 +5522,7 @@ http://www.gebish.org/manual/current/[The Book of Geb] user's manual. [[spring-mvc-test-client]] ==== Client-Side REST Tests + Client-side tests can be used to test code that internally uses the `RestTemplate`. The idea is to declare expected requests and to provide "stub" responses so that you can focus on testing the code in isolation, i.e. without running a server. @@ -5546,10 +5602,9 @@ server-side logic but without running a server. Here is an example: mockServer.verify(); ---- - - [[spring-mvc-test-client-static-imports]] ===== Static Imports + Just like with server-side tests, the fluent API for client-side tests requires a few static imports. Those are easy to find by searching __"MockRest*"__. Eclipse users should add `"MockRestRequestMatchers.{asterisk}"` and `"MockRestResponseCreators.{asterisk}"` @@ -5561,14 +5616,17 @@ configuration. Just check the support for code completion on static members. [[spring-mvc-test-client-resources]] ===== Further Examples of Client-side REST Tests + Spring MVC Test's own tests include https://github.com/spring-projects/spring-framework/tree/master/spring-test/src/test/java/org/springframework/test/web/client/samples[example tests] of client-side REST tests. + include::testing-webtestclient.adoc[leveloffset=+2] + [[testing-examples-petclinic]] === PetClinic Example @@ -5696,4 +5754,3 @@ Consult the following resources for more information about testing: Maven) targeted for database-driven projects that, among other things, puts your database into a known state between test runs. * http://grinder.sourceforge.net/[The Grinder]: Java load testing framework. - diff --git a/src/docs/asciidoc/web-reactive.adoc b/src/docs/asciidoc/web-reactive.adoc index 88de041887b..258a0b0c1e1 100644 --- a/src/docs/asciidoc/web-reactive.adoc +++ b/src/docs/asciidoc/web-reactive.adoc @@ -19,6 +19,8 @@ include::web/webflux.adoc[leveloffset=+1] include::web/webflux-webclient.adoc[leveloffset=+1] + + [[webflux-test]] == Testing @@ -31,6 +33,8 @@ response objects to provide support for testing WebFlux applications without and server. The `WebTestClient` can be used for end-to-end integration tests too. + + [[webflux-reactive-libraries]] == Reactive Libraries diff --git a/src/docs/asciidoc/web/integration.adoc b/src/docs/asciidoc/web/integration.adoc index 6452a246aea..42fc3505669 100644 --- a/src/docs/asciidoc/web/integration.adoc +++ b/src/docs/asciidoc/web/integration.adoc @@ -1,8 +1,9 @@ - [[web-integration]] = Other Web Frameworks + + [[intro]] == Introduction @@ -18,6 +19,8 @@ arguably most evident in the web area, where Spring provides its own web framewo popular third party web frameworks. + + [[web-integration-common]] == Common config Before diving into the integration specifics of each supported web framework, let us @@ -103,7 +106,7 @@ has more detail on its specific integration strategies. [[jsf]] -== JSF 1.2 +== JSF JavaServer Faces (JSF) is the JCP's standard component-based, event-driven web user interface framework. As of Java EE 5, it is an official part of the Java EE umbrella. @@ -122,15 +125,17 @@ http://projects.spring.io/spring-webflow[Spring Web Flow website] for details! The key element in Spring's JSF integration is the JSF `ELResolver` mechanism. + + [[jsf-springbeanfaceselresolver]] === Spring Bean Resolver -`SpringBeanFacesELResolver` is a JSF 1.2 compliant `ELResolver` implementation, +`SpringBeanFacesELResolver` is a JSF 1.2+ compliant `ELResolver` implementation, integrating with the standard Unified EL as used by JSF 1.2 and JSP 2.1. Like - `SpringBeanVariableResolver`, it delegates to the Spring's 'business context' +`SpringBeanVariableResolver`, it delegates to the Spring's 'business context' `WebApplicationContext` __first__, then to the default resolver of the underlying JSF implementation. -Configuration-wise, simply define `SpringBeanFacesELResolver` in your JSF 1.2 +Configuration-wise, simply define `SpringBeanFacesELResolver` in your JSF __faces-context.xml__ file: [source,xml,indent=0] @@ -145,6 +150,7 @@ __faces-context.xml__ file: ---- + [[jsf-facescontextutils]] === FacesContextUtils A custom `VariableResolver` works well when mapping one's properties to beans @@ -161,6 +167,7 @@ takes a `FacesContext` parameter rather than a `ServletContext` parameter. + [[struts]] == Apache Struts 2.x Invented by Craig McClanahan, http://struts.apache.org[Struts] is an open source project @@ -176,6 +183,7 @@ built-in Spring integration shipped with Struts. + [[tapestry]] == Tapestry 5.x From the http://tapestry.apache.org/[Tapestry homepage]: @@ -193,6 +201,7 @@ Spring]. + [[web-integration-resources]] == Further Resources Find below links to further resources about the various web frameworks described in this @@ -201,4 +210,3 @@ chapter. * The http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html[JSF] homepage * The http://struts.apache.org/[Struts] homepage * The http://tapestry.apache.org/[Tapestry] homepage - diff --git a/src/docs/asciidoc/web/webflux-functional.adoc b/src/docs/asciidoc/web/webflux-functional.adoc index cfe80c6cc9d..63d6cf94daf 100644 --- a/src/docs/asciidoc/web/webflux-functional.adoc +++ b/src/docs/asciidoc/web/webflux-functional.adoc @@ -7,6 +7,8 @@ It is an alternative to the annotated-based programming model but runs on the sa <> foundation + + [[webflux-fn-handler-functions]] == HandlerFunction @@ -119,6 +121,9 @@ when the `Person` has been saved. variable `id`. We retrieve that `Person` via the repository, and create a JSON response if it is found. If it is not found, we use `switchIfEmpty(Mono)` to return a 404 Not Found response. + + + [[webflux-fn-router-functions]] == RouterFunction @@ -182,6 +187,8 @@ For instance, `RequestPredicates.GET(String)` is a composition of `RequestPredicates.method(HttpMethod)` and `RequestPredicates.path(String)`. + + [[webflux-fn-running]] == Running a server @@ -199,6 +206,7 @@ handle requests with router and handler functions. + [[webflux-fn-handler-filter-function]] == HandlerFilterFunction @@ -232,4 +240,4 @@ RouterFunction filteredRoute = ---- You can see in this example that invoking the `next.handle(ServerRequest)` is optional: we only -allow the handler function to be executed when access is allowed. \ No newline at end of file +allow the handler function to be executed when access is allowed. diff --git a/src/docs/asciidoc/web/webflux-webclient.adoc b/src/docs/asciidoc/web/webflux-webclient.adoc index b0592a31338..88553e757a2 100644 --- a/src/docs/asciidoc/web/webflux-webclient.adoc +++ b/src/docs/asciidoc/web/webflux-webclient.adoc @@ -22,6 +22,8 @@ non-blocking I/O. ==== + + [[webflux-client-retrieve]] == Retrieve @@ -65,6 +67,7 @@ By default, responses with 4xx or 5xx status codes result in an error of type + [[webflux-client-exchange]] == Exchange @@ -103,6 +106,8 @@ to complete. ==== + + [[webflux-client-body]] == Request body @@ -152,6 +157,8 @@ Or if you have the actual value, use the `syncBody` shortcut method: ---- + + [[webflux-client-builder]] == Builder options @@ -211,7 +218,6 @@ build a new `WebClient`, based on, but without affecting the current instance: - [[webflux-client-filter]] == Filters @@ -254,4 +260,3 @@ You can also mutate an existing `WebClient` instance without affecting the origi .filter(basicAuthentication("user", "pwd") .build(); ---- - diff --git a/src/docs/asciidoc/web/webflux.adoc b/src/docs/asciidoc/web/webflux.adoc index e2519befa26..0a138c8012f 100644 --- a/src/docs/asciidoc/web/webflux.adoc +++ b/src/docs/asciidoc/web/webflux.adoc @@ -1,6 +1,9 @@ [[webflux]] = Spring WebFlux + + + [[webflux-introduction]] == Introduction The original web framework included in the Spring Framework, Spring Web MVC, was purpose @@ -17,6 +20,7 @@ Applications may use one or the other module, or in some cases both -- e.g. Spring MVC controllers with the reactive `WebClient`. + [[webflux-new-framework]] === Why a new web framework? @@ -37,6 +41,7 @@ composition of asynchronous logic. At the programming model level Java 8 enabled WebFlux to offer functional web endpoints alongside with annotated controllers. + [[webflux-why-reactive]] === Reactive: what and why? @@ -72,6 +77,7 @@ If a publisher can't slow down then it has to decide whether to buffer, drop, or ==== + [[webflux-reactive-api]] === Reactive API @@ -100,6 +106,7 @@ Whenever feasible -- e.g. annotated controllers, WebFlux adapts transparently to of RxJava or other reactive library. See <> for more details. + [[webflux-programming-models]] === Programming models @@ -120,6 +127,7 @@ is in charge of request handling from start to finish vs declaring intent throug annotations and being called back. + [[webflux-framework-choice]] === Choosing a web framework @@ -170,6 +178,7 @@ https://medium.com/netflix-techblog/zuul-2-the-netflix-journey-to-asynchronous-n is a good resource. + [[webflux-server-choice]] === Choosing a server @@ -198,6 +207,7 @@ optimized for performance, fully non-blocking, and adapted to Reactive Streams b pressure. In Spring Boot it is trivial to make the switch. + [[webflux-performance]] === Performance vs scale @@ -215,6 +225,7 @@ dramatic. + [[webflux-reactive-spring-web]] == Reactive Spring Web @@ -230,6 +241,7 @@ for HTTP request handling with Reactive Streams back pressure. purpose server web API with filter chain style processing. + [[webflux-httphandler]] === HttpHandler @@ -411,6 +423,7 @@ to have the following detected: |=== + [[webflux-codecs]] === Codecs @@ -439,6 +452,7 @@ of defaults along with the ability to override or replace those defaults. + [[webflux-dispatcher-handler]] == DispatcherHandler [.small]#<># @@ -603,6 +617,7 @@ your Java configuration: rendering). + [[webflux-ann-requestmapping]] === Request Mapping [.small]#<># @@ -859,6 +874,7 @@ is not necessary in the common case. `@RequestMapping` handler methods have a flexible signature and can choose from a range of supported controller method arguments and return values. + [[webflux-ann-arguments]] ==== Method arguments [.small]#<># @@ -969,6 +985,7 @@ as a result of a class-level `@SessionAttributes` declaration. |For access to request attributes. |=== + [[webflux-ann-return-types]] ==== Return values [.small]#<># @@ -1029,10 +1046,12 @@ class name of the return type. + include::webflux-functional.adoc[leveloffset=+1] + [[webflux-config]] == WebFlux Java Config [.small]#<># @@ -1046,6 +1065,7 @@ easy to seem them in `WebFluxConfigurationSupport`, and if you want to learn mor <>. + [[webflux-config-enable]] === Enable WebFlux config [.small]#<># @@ -1066,6 +1086,7 @@ The above registers a number of Spring WebFlux available on the classpath -- for JSON, XML, etc. + [[webflux-config-customize]] === WebFlux config API [.small]#<># @@ -1118,6 +1139,7 @@ and the `FormattingConversionServiceFactoryBean` for more information on when to ==== + [[webflux-config-validation]] === Validation [.small]#<># @@ -1167,6 +1189,7 @@ mark it with `@Primary` in order to avoid conflict with the one declared in the ==== + [[webflux-config-content-negotiation]] === Content type resolvers [.small]#<># @@ -1191,6 +1214,8 @@ To customize the requested content type resolution: } ---- + + [[webflux-config-message-codecs]] === HTTP message codecs [.small]#<># @@ -1229,6 +1254,7 @@ It also automatically registers the following well-known modules if they are det . https://github.com/FasterXML/jackson-datatype-jdk8[jackson-datatype-jdk8]: support for other Java 8 types like `Optional`. + [[webflux-config-view-resolvers]] === View resolvers [.small]#<># @@ -1271,6 +1297,7 @@ Note that FreeMarker also requires configuration of the underlying view technolo ---- + [[webflux-config-static-resources]] === Static resources [.small]#<># @@ -1351,6 +1378,7 @@ match to incoming URLs without versions -- e.g. `"/jquery/jquery.min.js"` to `"/jquery/1.2.0/jquery.min.js"`. + [[webflux-config-path-matching]] === Path Matching [.small]#<># @@ -1382,6 +1410,7 @@ To customize those options: ---- + [[webflux-config-advanced-java]] === Advanced config mode [.small]#<># @@ -1407,5 +1436,3 @@ For advanced mode, remove `@EnableWebFlux` and extend directly from You can keep existing methods in `WebConfig` but you can now also override bean declarations from the base class and you can still have any number of other ``WebMvcConfigurer``'s on the classpath. - - diff --git a/src/docs/asciidoc/web/webmvc-client.adoc b/src/docs/asciidoc/web/webmvc-client.adoc index b8abc5814b4..92ced6c4a9e 100644 --- a/src/docs/asciidoc/web/webmvc-client.adoc +++ b/src/docs/asciidoc/web/webmvc-client.adoc @@ -3,6 +3,9 @@ This section describes options for client-side access to REST endpoints. + + + [[webmvc-resttemplate]] == RestTemplate @@ -19,6 +22,8 @@ See <> for more details on usi `RestTemplate`. + + [[webmvc-webclient]] == WebClient diff --git a/src/docs/asciidoc/web/webmvc-cors.adoc b/src/docs/asciidoc/web/webmvc-cors.adoc index c7dba3bb54d..1b25ef4eadc 100644 --- a/src/docs/asciidoc/web/webmvc-cors.adoc +++ b/src/docs/asciidoc/web/webmvc-cors.adoc @@ -1,6 +1,9 @@ [[mvc-cors]] = CORS + + + == Introduction For security reasons, browsers prohibit AJAX calls to resources residing outside the @@ -31,6 +34,9 @@ Since CORS requests are automatically dispatched, you *do not need* to change th (`false`) is the recommended approach. ==== + + + [[mvc-cors-controller]] == @Controller CORS @@ -110,6 +116,9 @@ public class AccountController { } ---- + + + [[mvc-cors-global]] == Global CORS @@ -119,6 +128,7 @@ be declared within Spring MVC and combined with fine-grained `@CrossOrigin` conf By default all origins and `GET`, `HEAD`, and `POST` methods are allowed. + [[mvc-cors-global-java]] === Java Config @@ -161,6 +171,7 @@ public class WebConfig implements WebMvcConfigurer { ---- + [[mvc-cors-global-xml]] === XML Config @@ -195,6 +206,9 @@ It is also possible to declare several CORS mappings with customized properties: ---- + + + [[mvc-cors-customizations]] == Advanced Customization @@ -213,6 +227,8 @@ It can be provided in various ways: instance for each request. + + [[mvc-cors-filter]] == CORS Filter @@ -238,4 +254,4 @@ CorsFilter filter = new CorsFilter(source); Also the information on https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#cors[CORS] -in the Spring Security reference. \ No newline at end of file +in the Spring Security reference. diff --git a/src/docs/asciidoc/web/webmvc-test.adoc b/src/docs/asciidoc/web/webmvc-test.adoc index 451ef36eb5a..79921f10df7 100644 --- a/src/docs/asciidoc/web/webmvc-test.adoc +++ b/src/docs/asciidoc/web/webmvc-test.adoc @@ -1,13 +1,19 @@ [[testing]] = Testing + + + [[testing-servlet-mocks]] == Servlet API Mocks + `spring-test` provides mock implementations of Servlet API contracts for unit testing controllers, filters, and other web components. See <> mock objects for more details. + + [[testing-testcontext]] == TestContext Framework @@ -17,6 +23,8 @@ loading a `WebApplicationContext` with a `MockServletContext`. See <> for more details. + + [[testing-mockmvc]] == Spring MVC Tests @@ -25,6 +33,8 @@ through the `DispatcherServlet`, complete with Spring MVC infrastructure, but wi HTTP server. See <> for more details. + + [[testing-resttemplate]] == Client-side REST diff --git a/src/docs/asciidoc/web/webmvc-view.adoc b/src/docs/asciidoc/web/webmvc-view.adoc index 1aeac60e877..a15e8c3a061 100644 --- a/src/docs/asciidoc/web/webmvc-view.adoc +++ b/src/docs/asciidoc/web/webmvc-view.adoc @@ -2,8 +2,11 @@ = View Technologies + + [[mvc-view-introduction]] == Introduction + One of the areas in which Spring excels is in the separation of view technologies from the rest of the MVC framework. For example, deciding to use Groovy Markup Templates or Thymeleaf in place of an existing JSP is primarily a matter of configuration. @@ -13,6 +16,8 @@ briefly on how to add new ones. This chapter assumes you are already familiar wi to the MVC framework. + + [[mvc-view-thymeleaf]] == Thymeleaf @@ -26,6 +31,8 @@ Please refer to the http://www.thymeleaf.org/documentation.html[Thymeleaf+Spring documentation section for more details. + + [[mvc-view-groovymarkup]] == Groovy Markup @@ -37,6 +44,7 @@ text based content. This requires Groovy 2.3.1+ on the classpath. + [[mvc-view-groovymarkup-configuration]] === Configuration @@ -78,6 +86,7 @@ The XML counterpart using the MVC namespace is: ---- + [[mvc-view-groovymarkup-example]] === Example @@ -100,15 +109,20 @@ Here is a sample template for an HTML page: ---- + + [[mvc-view-freemarker]] == FreeMarker + http://www.freemarker.org[FreeMarker] is a templating language that can be used as a view technology within Spring MVC applications. For details on the template language, see the http://www.freemarker.org[FreeMarker] web site. + [[mvc-view-freemarker-dependencies]] === Dependencies + Your web application will need to include `freemarker-2.x.jar` in order to work with FreeMarker. Typically this is included in the `WEB-INF/lib` folder where the jars are guaranteed to be found by a Java EE server and added to the classpath for your @@ -116,8 +130,10 @@ application. It is of course assumed that you already have the `spring-webmvc.ja your `'WEB-INF/lib'` directory too! + [[mvc-view-freemarker-contextconfig]] === Context configuration + A suitable configuration is initialized by adding the relevant configurer bean definition to your `'{asterisk}-servlet.xml'` as shown below: @@ -147,8 +163,10 @@ definition file. ==== + [[mvc-view-freemarker-createtemplates]] === Creating templates + Your templates need to be stored in the directory specified by the `FreeMarkerConfigurer` shown above. If you use the view resolvers highlighted, then the logical view names relate to the template file names in similar fashion to `InternalResourceViewResolver` @@ -158,6 +176,7 @@ for JSP's. So if your controller returns a ModelAndView object containing a view [[mvc-views-freemarker]] === Advanced config + FreeMarker 'Settings' and 'SharedVariables' can be passed directly to the FreeMarker `Configuration` object managed by Spring by setting the appropriate bean properties on the `FreeMarkerConfigurer` bean. The `freemarkerSettings` property requires a @@ -186,6 +205,7 @@ the `Configuration` object. [[mvc-view-freemarker-forms]] === Form handling + Spring provides a tag library for use in JSP's that contains (amongst other things) a `` tag. This tag primarily enables forms to display values from form backing objects and to show the results of failed validations from a `Validator` in the @@ -195,6 +215,7 @@ with additional convenience macros for generating form input elements themselves [[mvc-view-bind-macros]] ==== The bind macros + A standard set of macros are maintained within the `spring-webmvc.jar` file for both languages, so they are always available to a suitably configured application. @@ -208,6 +229,7 @@ directly, the file is called `spring.ftl` in the package [[mvc-view-simple-binding]] ==== Simple binding + In your HTML forms (vm / ftl templates) which act as a form view for a Spring MVC controller, you can use code similar to the following to bind to field values and display error messages for each input field in similar fashion to the JSP equivalent. @@ -252,6 +274,7 @@ They are explained in the next section. [[mvc-views-form-macros]] ==== Input macros + Additional convenience macros for both languages simplify both binding and form generation (including validation error display). It is never necessary to use these macros to generate form input fields, and they can be mixed and matched with simple HTML @@ -342,6 +365,7 @@ differences exist between the two languages, they are explained in the notes. [[mvc-views-form-macros-input]] ===== Input Fields + The formInput macro takes the path parameter (command.name) and an additional attributes parameter which is empty in the example above. The macro, along with all other form generation macros, performs an implicit spring bind on the path parameter. The binding @@ -383,6 +407,7 @@ information or rows and cols attributes for the textarea. [[mvc-views-form-macros-select]] ===== Selection Fields + Four selection field macros can be used to generate common UI value selection inputs in your HTML forms. @@ -457,6 +482,7 @@ user still sees the more user friendly city names. [[mvc-views-form-macros-html-escaping]] ==== HTML escaping + Default usage of the form macros above will result in HTML tags that are HTML 4.01 compliant and that use the default value for HTML escaping defined in your web.xml as used by Spring's bind support. In order to make the tags XHTML compliant or to override @@ -498,6 +524,7 @@ In similar fashion, HTML escaping can be specified per field: [[mvc-view-jsp]] == JSP & JSTL + Spring provides a couple of out-of-the-box solutions for JSP and JSTL views. Using JSP or JSTL is done using a normal view resolver defined in the `WebApplicationContext`. Furthermore, of course you need to write some JSPs that will actually render the view. @@ -518,6 +545,7 @@ somewhat. [[mvc-view-jsp-resolver]] === View resolvers + Just as with any other view technology you're integrating with Spring, for JSPs you'll need a view resolver that will resolve your views. The most commonly used view resolvers when developing with JSPs are the `InternalResourceViewResolver` and the @@ -561,6 +589,7 @@ under the `'WEB-INF'` directory, so there can be no direct access by clients. [[mvc-view-jsp-jstl]] === 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. @@ -569,6 +598,7 @@ work. [[mvc-view-jsp-tags]] === Spring tags + Spring provides data binding of request parameters to command objects as described in earlier chapters. To facilitate the development of JSP pages in combination with those data binding features, Spring provides a few tags that make things even easier. All @@ -582,6 +612,7 @@ or see the tag library description. [[mvc-view-jsp-formtaglib]] === Spring form tags + As of version 2.0, Spring provides a comprehensive set of data binding-aware tags for handling form elements when using JSP and Spring Web MVC. Each tag provides support for the set of attributes of its corresponding HTML tag counterpart, making the tags @@ -598,6 +629,7 @@ included generated HTML snippets where certain tags require further commentary. [[mvc-view-jsp-formtaglib-configuration]] ==== Configuration + The form tag library comes bundled in `spring-webmvc.jar`. The library descriptor is called `spring-form.tld`. @@ -1267,6 +1299,7 @@ or see the tag library description. [[mvc-rest-method-conversion]] ==== HTTP Method Conversion + A key principle of REST is the use of the Uniform Interface. This means that all resources (URLs) can be manipulated using the same four HTTP methods: GET, PUT, POST, and DELETE. For each method, the HTTP specification defines the exact semantics. For @@ -1327,6 +1360,7 @@ The corresponding `@Controller` method is shown below: [[mvc-view-jsp-formtaglib-html5]] ==== HTML5 Tags + Starting with Spring 3, the Spring form tag library allows entering dynamic attributes, which means you can enter any HTML5 specific attributes. @@ -1337,6 +1371,7 @@ is the default type. + [[mvc-view-script]] == Script views @@ -1354,6 +1389,8 @@ It has been tested with: * http://www.stuartellis.eu/articles/erb/[ERB] running on http://jruby.org[JRuby] * https://docs.python.org/2/library/string.html#template-strings[String templates] running on http://www.jython.org/[Jython] + + [[mvc-view-script-dependencies]] === Requirements @@ -1374,6 +1411,7 @@ for Javascript you can use http://www.webjars.org/[WebJars] to add Maven/Gradle in order to make your javascript libraries available in the classpath. + [[mvc-view-script-integrate]] === Script templates @@ -1536,6 +1574,7 @@ for more configuration examples. [[mvc-view-xml-marshalling]] == XML Marshalling + The `MarshallingView` uses an XML `Marshaller` defined in the `org.springframework.oxm` package to render the response content as XML. The object to be marshalled can be set explicitly using ``MarhsallingView``'s `modelKey` bean property. Alternatively, the view @@ -1547,13 +1586,12 @@ Mappers>>. - [[mvc-view-tiles]] == Tiles + It is possible to integrate Tiles - just as any other view technology - in web applications using Spring. The following describes in a broad way how to do this. - [NOTE] ==== This section focuses on Spring's support for Tiles v3 in the @@ -1561,15 +1599,19 @@ This section focuses on Spring's support for Tiles v3 in the ==== + [[mvc-view-tiles-dependencies]] === Dependencies + To be able to use Tiles, you have to add a dependency on Tiles version 3.0.1 or higher and http://tiles.apache.org/framework/dependency-management.html[its transitive dependencies] to your project. + [[mvc-view-tiles-integrate]] === Configuration + To be able to use Tiles, you have to configure it using files containing definitions (for basic information on definitions and other Tiles concepts, please have a look at http://tiles.apache.org[]). In Spring this is done using the `TilesConfigurer`. Have a @@ -1720,8 +1762,10 @@ per preparer name (as used in your Tiles definitions). + [[mvc-view-xslt]] == XSLT + XSLT is a transformation language for XML and is popular as a view technology within web applications. XSLT can be a good choice as a view technology if your application naturally deals with XML, or if your model can easily be converted to XML. The following @@ -1735,8 +1779,10 @@ name of our XSLT view. See <> for details of Spring Web MVC's document ready for transformation. + [[mvc-view-xslt-beandefs]] === Beans + Configuration is standard for a simple Spring application. The MVC configuration has to define a `XsltViewResolver` bean and regular MVC annotation configuration. @@ -1763,6 +1809,7 @@ public class WebConfig implements WebMvcConfigurer { And we need a Controller that encapsulates our word generation logic. + [[mvc-view-xslt-controllercode]] === Controller @@ -1809,6 +1856,7 @@ Next, `XsltViewResolver` will resolve the "home" XSLT template file and merge th DOM document into it to generate our view. + [[mvc-view-xslt-transforming]] === Transformation @@ -1817,7 +1865,6 @@ DOM document into it to generate our view. As shown in the `XsltViewResolver` configuration, XSLT templates live in the war file in the `'WEB-INF/xsl'` directory and end with a `"xslt"` file extension. - [source,xml,indent=0] [subs="verbatim,quotes"] ---- @@ -1866,6 +1913,9 @@ This is rendered as: ---- + + + [[mvc-view-document]] == PDF, Excel @@ -1873,6 +1923,7 @@ This is rendered as: [[mvc-view-document-intro]] === Introduction + Returning an HTML page isn't always the best way for the user to view the model output, and Spring makes it simple to generate a PDF document or an Excel spreadsheet dynamically from the model data. The document is the view and will be streamed from the @@ -1886,6 +1937,7 @@ for PDF generation, the iText library. [[mvc-view-document-config]] === Configuration + Document based views are handled in an almost identical fashion to XSLT views, and the following sections build upon the previous one by demonstrating how the same controller used in the XSLT example is invoked to render the same model as both a PDF document and @@ -1894,6 +1946,7 @@ an Excel spreadsheet (which can also be viewed or manipulated in Open Office). [[mvc-view-document-configviews]] === View definition + First, let's amend the views.properties file (or xml equivalent) and add a simple view definition for both document types. The entire file now looks like this with the XSLT view shown from earlier: @@ -1914,16 +1967,20 @@ __If you want to start with a template spreadsheet or a fillable PDF form to add model data to, specify the location as the 'url' property in the view definition__ + [[mvc-view-document-configcontroller]] === Controller + The controller code we'll use remains exactly the same from the XSLT example earlier other than to change the name of the view to use. Of course, you could be clever and 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! + [[mvc-view-document-configsubclasses]] === Excel views + Exactly as we did for the XSLT example, we'll subclass suitable abstract classes in order to implement custom behavior in generating our output documents. For Excel, this involves writing a subclass of @@ -2006,8 +2063,10 @@ that the Excel spreadsheet is created and downloaded automatically when you requ same page as before. + [[mvc-view-document-configsubclasspdf]] === PDF views + The PDF version of the word list is even simpler. This time, the class extends `org.springframework.web.servlet.view.document.AbstractPdfView` and implements the `buildPdfDocument()` method as follows: @@ -2041,6 +2100,7 @@ document should appear listing each of the words in the model map. [[mvc-view-feeds]] == RSS Feeds + Both `AbstractAtomFeedView` and `AbstractRssFeedView` inherit from the base class `AbstractFeedView` and are used to provide Atom and RSS Feed views respectfully. They are based on java.net's https://rome.dev.java.net[ROME] project and are located in the @@ -2101,11 +2161,16 @@ For an example of creating an Atom view please refer to Alef Arendsen's Spring T https://spring.io/blog/2009/03/16/adding-an-atom-view-to-an-application-using-spring-s-rest-support[entry]. + + [[mvc-view-jackson]] == Jackson + + [[mvc-view-json-mapping]] === JSON + The `MappingJackson2JsonView` uses the Jackson library's `ObjectMapper` to render the response content as JSON. By default, the entire contents of the model map (with the exception of framework-specific classes) will be encoded as JSON. For cases where the contents of the @@ -2125,9 +2190,9 @@ name(s) could be customized through the `jsonpParameterNames` property. - [[mvc-view-xml-mapping]] === XML + The `MappingJackson2XmlView` uses the https://github.com/FasterXML/jackson-dataformat-xml[Jackson XML extension]'s `XmlMapper` to render the response content as XML. If the model contains multiples entries, the @@ -2138,4 +2203,3 @@ XML mapping can be customized as needed through the use of JAXB or Jackson's pro annotations. When further control is needed, a custom `XmlMapper` can be injected through the `ObjectMapper` property for cases where custom XML serializers/deserializers need to be provided for specific types. - diff --git a/src/docs/asciidoc/web/webmvc.adoc b/src/docs/asciidoc/web/webmvc.adoc index 28afae68059..8bad1c59fd2 100644 --- a/src/docs/asciidoc/web/webmvc.adoc +++ b/src/docs/asciidoc/web/webmvc.adoc @@ -2,8 +2,12 @@ = Spring Web MVC :doc-spring-security: {doc-root}/spring-security/site/docs/current/reference + + + [[mvc-introduction]] == Introduction + Spring Web MVC is the original web framework built on the Servlet API and included in the Spring Framework from the very beginning. The formal name "Spring Web MVC" comes from the name of its source module @@ -18,6 +22,7 @@ covers Spring WebFlux. + [[mvc-servlet]] == DispatcherServlet [.small]#<># @@ -114,6 +119,7 @@ https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-featu ==== + [[mvc-servlet-context-hierarchy]] === Context Hierarchy @@ -287,6 +293,7 @@ provides many extra convenient options on top. ==== + [[mvc-container-config]] === Container Config @@ -467,6 +474,7 @@ initialization parameters ( `init-param` elements) to the Servlet declaration in |=== + [[mvc-handlermapping-interceptor]] === Interception @@ -499,8 +507,10 @@ declare it as an <> bean or configure it directly on `RequestMappingHandlerAdapter`. + [[mvc-viewresolver]] === View Resolution + Spring MVC defines the `ViewResolver` and `View` interfaces that enable you to render models in a browser without tying you to a specific view technology. `ViewResolver` provides a mapping between view names and actual views. `View` addresses the preparation @@ -553,7 +563,6 @@ This table below provides more details on the `ViewResolver` hierarchy: request file name or `Accept` header. See <>. |=== - You chain view resolvers by configuring more than one resolver and, if necessary, by setting the `order` property to specify ordering. Remember, the higher the order property, the later the view resolver is positioned in the chain. @@ -569,7 +578,6 @@ how to configure view resolution. Also see<> for more details on suppo view technologies. - [[mvc-redirecting-redirect-prefix]] ==== Redirect @@ -622,8 +630,10 @@ Content-Type was `text/xml` is a compatible match. See <> under <> for configuration details. + [[mvc-localeresolver]] -=== Locales +=== Locale + Most parts of Spring's architecture support internationalization, just as the Spring web MVC framework does. `DispatcherServlet` enables you to automatically resolve messages using the client's locale. This is done with `LocaleResolver` objects. @@ -643,9 +653,9 @@ context in the normal way. Here is a selection of the locale resolvers included Spring. - [[mvc-timezone]] ==== TimeZone + In addition to obtaining the client's locale, it is often useful to know their time zone. The `LocaleContextResolver` interface offers an extension to `LocaleResolver` that allows resolvers to provide a richer `LocaleContext`, which may include time zone information. @@ -656,16 +666,15 @@ by Date/Time `Converter` and `Formatter` objects registered with Spring's `ConversionService`. - [[mvc-localeresolver-acceptheader]] ==== Header resolver + This locale resolver inspects the `accept-language` header in the request that was sent by the client (e.g., a web browser). Usually this header field contains the locale of the client's operating system. __Note that this resolver does not support time zone information.__ - [[mvc-localeresolver-cookie]] ==== Cookie resolver @@ -710,7 +719,6 @@ maximum age. Find below an example of defining a `CookieLocaleResolver`. |=== - [[mvc-localeresolver-session]] ==== Session resolver @@ -725,7 +733,6 @@ such as the Spring Session project. This `SessionLocaleResolver` will simply eva modify corresponding `HttpSession` attributes against the current `HttpServletRequest`. - [[mvc-localeresolver-interceptor]] ==== Locale interceptor @@ -763,7 +770,6 @@ change the site language to Dutch. - [[mvc-themeresolver]] === Themes @@ -775,6 +781,7 @@ application. [[mvc-themeresolver-defining]] ==== Define a theme + To use themes in your web application, you must set up an implementation of the `org.springframework.ui.context.ThemeSource` interface. The `WebApplicationContext` interface extends `ThemeSource` but delegates its responsibilities to a dedicated @@ -823,9 +830,9 @@ example, we could have a `/WEB-INF/classes/cool_nl.properties` that references a background image with Dutch text on it. - [[mvc-themeresolver-resolving]] ==== Resolve themes + After you define themes, as in the preceding section, you decide which theme to use. The `DispatcherServlet` will look for a bean named `themeResolver` to find out which `ThemeResolver` implementation to use. A theme resolver works in much the same way as a @@ -853,6 +860,7 @@ Spring also provides a `ThemeChangeInterceptor` that allows theme changes on eve request with a simple request parameter. + [[mvc-multipart]] === Multipart requests @@ -871,7 +879,6 @@ your context is used. After that, the multipart attribute in your request is tre like any other attribute. - [[mvc-multipart-resolver-commons]] ==== __Commons FileUpload__ @@ -902,11 +909,16 @@ Once Servlet 3.0 multipart parsing has been enabled in one of the above mentione you can add a bean of type `StandardServletMultipartResolver` and with the name `multipartResolver` to your Spring configuration. + + + [[filters]] == Filters The `spring-web` module provides some useful filters. + + [[filters-http-put]] === HTTP PUT Form @@ -920,6 +932,7 @@ the body of the request, and wraps the `ServletRequest` in order to make the for available through the `ServletRequest.getParameter{asterisk}()` family of methods. + [[filters-forwarded-headers]] === Forwarded Headers @@ -947,6 +960,7 @@ Applications that don't have a proxy and don't need to use forwarded headers can configure the `ForwardedHeaderFilter` to remove and ignore such headers. + [[filters-shallow-etag]] === Shallow ETag @@ -957,6 +971,7 @@ response and computing the ETag value at the end. See <> for more details. + [[filters-cors]] === CORS @@ -968,6 +983,7 @@ See the section on <> and the <> for more + [[mvc-controller]] == Annotated Controllers [.small]#<># @@ -1206,7 +1222,6 @@ the `PathMatcher` implementation used can be customized. See <># @@ -1518,7 +1531,7 @@ supported controller method arguments and return values. The table below shows supported controller method arguments. Reactive types are not supported for any arguments. -JDK 1.8's `java.util.Optional` is supported as a method argument in combination with +JDK 8's `java.util.Optional` is supported as a method argument in combination with annotations that have a `required` attribute -- e.g. `@RequestParam`, `@RequestHeader`, etc, and is equivalent to `required=false`. @@ -1629,6 +1642,7 @@ as a result of a class-level `@SessionAttributes` declaration. |For access to request attributes. |=== + [[mvc-ann-return-types]] ==== Return Values [.small]#<># @@ -1758,6 +1772,7 @@ parameters. [[mvc-ann-typeconversion]] ==== Type Conversion + String-based values extracted from the request including request parameters, path variables, request headers, and cookie values may need to be converted to the target type of the method parameter or field (e.g., binding a request parameter to a field in @@ -1770,6 +1785,7 @@ the `FormattingConversionService`, see <`, `MultiValueMap`, or `HttpHeaders` argument, the map is populated with all header values. - [TIP] ==== Built-in support is available for converting a comma-separated string into an @@ -1815,7 +1830,6 @@ example a method parameter annotated with `@RequestHeader("Accept")` may be of t ==== - [[mvc-ann-cookievalue]] ==== @CookieValue @@ -1995,6 +2009,7 @@ See <> and [[mvc-multipart-forms]] ==== File upload + After the `MultipartResolver` completes its job, the request is processed like any other. First, create a form with a file input that will allow the user to upload a form. The encoding attribute ( `enctype="multipart/form-data"`) lets the browser know how to @@ -2178,9 +2193,9 @@ other redirect attributes, flash attributes are saved in the HTTP session (and h not appear in the URL). See <> for more information. - [[mvc-flash-attributes]] ==== Flash attributes + Flash attributes provide a way for one request to store attributes intended for use in another. This is most commonly needed when redirecting -- for example, the __Post/Redirect/Get__ pattern. Flash attributes are saved temporarily before the @@ -2226,6 +2241,7 @@ Therefore the use of flash attributes is recommended mainly for redirect scenari [[mvc-multipart-forms-non-browsers]] ==== @RequestPart + Multipart requests can also be submitted from non-browser clients in a RESTful service scenario. All of the above examples and configuration apply here as well. However, unlike browsers that typically submit files and simple form fields, a programmatic @@ -2284,6 +2300,7 @@ converted with the help of the `MappingJackson2HttpMessageConverter`. [[mvc-ann-requestbody]] ==== @RequestBody + The `@RequestBody` method parameter annotation indicates that a method parameter should be bound to the value of the HTTP request body. For example: @@ -2431,7 +2448,6 @@ converters, see the previous section and <>. - [[mvc-ann-jackson]] ==== Jackson JSON @@ -2538,6 +2554,7 @@ request has a query parameter named `jsonp` or `callback`. Those names can be customized through `jsonpParameterNames` property. + [[mvc-ann-modelattrib-methods]] === Model Methods @@ -2605,6 +2622,7 @@ attribute rather than as a view name. The view name is then derived based on vie conventions instead, much like for methods returning `void` -- see <>. + [[mvc-ann-initbinder]] === Binder Methods @@ -2666,6 +2684,7 @@ controller-specific tweaking of the binding rules. ---- + [[mvc-ann-controller-advice]] === Controller Advice @@ -2701,7 +2720,8 @@ Both `@ControllerAdvice` and `@RestControllerAdvice` can target a subset of cont See the {api-spring-framework}/web/bind/annotation/ControllerAdvice.html[@ControllerAdvice] -Javadoc for more details. +javadoc for more details. + @@ -2790,6 +2810,7 @@ the original request. Note that you can also use the ==== + [[mvc-links-to-controllers]] === Links to Controllers @@ -2864,6 +2885,7 @@ with a base URL and then use the instance-based "withXxx" methods. For example: ---- + [[mvc-links-to-controllers-from-views]] === Links in views @@ -2918,9 +2940,12 @@ in order to use a specific instance of `MvcUriComponentsBuilder` with a custom b + [[mvc-exceptionhandlers]] == Exception Handling + + [[mvc-exceptionhandlers-overview]] === Overview @@ -3007,6 +3032,7 @@ value converted with message converters and written to the response stream. [[mvc-ann-rest-spring-mvc-exceptions]] === Framework exceptions + Spring MVC may raise a number of exceptions while processing a request. The `SimpleMappingExceptionResolver` can easily map any exception to a default error view as needed. However, when working with clients that interpret responses in an automated way @@ -3104,7 +3130,6 @@ See `ResponseEntityExceptionHandler`. - [[mvc-ann-annotated-exceptions]] === Annotated Exception @@ -3117,6 +3142,7 @@ response accordingly. By default the `DispatcherServlet` registers the [[mvc-ann-customer-servlet-container-error-page]] === Container error page + When the status of the response is set to an error status code and the body of the response is empty, Servlet containers commonly render an HTML formatted error page. To customize the default error page of the container, you can declare an `` @@ -3172,9 +3198,13 @@ or in a JSP: ---- + + [[mvc-ann-async]] == Async Requests + + [[mvc-ann-async-processing]] === Processing @@ -3271,8 +3301,10 @@ https://spring.io/blog/2012/05/07/spring-mvc-3-2-preview-introducing-servlet-3-a blog post series]. + [[mvc-ann-async-exceptions]] === Exception handling + What happens if a `Callable` returned from a controller method raises an Exception while being executed? The short answer is the same as what happens when a controller method raises an exception. It goes through the regular @@ -3284,8 +3316,10 @@ When using a `DeferredResult` you have a choice whether to call `setResult` or `setErrorResult` with an `Exception` instance. + [[mvc-ann-async-interception]] === Async interceptors + A `HandlerInterceptor` can also implement `AsyncHandlerInterceptor` in order to implement the `afterConcurrentHandlingStarted` callback, which is called instead of `postHandle` and `afterCompletion` when asynchronous processing @@ -3304,6 +3338,8 @@ details. When using a `Callable` you can wrap it with an instance of `WebAsyncTask` which also provides registration methods for timeout and completion. + + [[mvc-ann-async-http-streaming]] === Streaming response @@ -3345,6 +3381,8 @@ Note that `ResponseBodyEmitter` can also be used as the body in a `ResponseEntity` in order to customize the status and headers of the response. + + [[mvc-ann-async-sse]] === Server-Sent Events @@ -3368,6 +3406,8 @@ a publish-subscribe model within a more messaging-centric architecture. For further background on this see http://blog.pivotal.io/pivotal/products/websocket-architecture-in-spring-4-0[the following blog post]. + + [[mvc-ann-async-output-stream]] === Streaming raw data @@ -3399,6 +3439,7 @@ Note that `StreamingResponseBody` can also be used as the body in a the response. + [[mvc-ann-async-reactive-types]] === Reactive return values @@ -3456,8 +3497,10 @@ processing and hence does not require a thread to absorb the effect of blocking. For asynchronous requests there are minor requirements at the Servlet container level and more controls in Spring MVC configuration. + [[mvc-ann-async-configuration-servlet3]] ==== Servlet container config + For applications configured with a `web.xml` be sure to update to version 3.0: [source,xml,indent=0] @@ -3519,6 +3562,7 @@ just like with `web.xml`. To simplify all this configuration, consider extending `AbstractAnnotationConfigDispatcherServletInitializer` which automatically set those options and make it very easy to register `Filter` instances. + [[mvc-ann-async-configuration-spring-mvc]] ==== Spring MVC config @@ -3542,9 +3586,13 @@ the timeout value. The class constructor of `WebAsyncTask` also allows providing `AsyncTaskExecutor`. + + include::webmvc-cors.adoc[leveloffset=+1] + + [[mvc-web-security]] == Web Security @@ -3563,6 +3611,7 @@ Another option is to use a framework dedicated to Web Security. http://hdiv.org/[HDIV] is one such framework and integrates with Spring MVC. + [[mvc-coc-modelmap]] === The Model ModelMap (ModelAndView) @@ -3716,6 +3765,7 @@ that can be configured. + [[mvc-caching]] == HTTP Caching @@ -3737,6 +3787,7 @@ This section describes the different choices available to configure HTTP caching Spring Web MVC application. + [[mvc-caching-cachecontrol]] === Cache-Control @@ -3775,6 +3826,7 @@ accepted as an argument in several Spring Web MVC APIs. .noTransform().cachePublic(); ---- + [[mvc-caching-static-resources]] === Static resources @@ -3816,6 +3868,7 @@ And in XML: ---- + [[mvc-caching-etag-lastmodified]] === @Controller caching @@ -3893,6 +3946,7 @@ will check that the resource has not been modified and if it has been, it will r `HTTP 409 Precondition Failed` response to prevent concurrent modifications. + [[mvc-httpcaching-shallowetag]] === ETag Filter @@ -3914,6 +3968,7 @@ https://tools.ietf.org/html/rfc7232#section-2.3[RFC 7232 Section 2.3]. + [[mvc-config]] == MVC Config [.small]#<># @@ -3994,6 +4049,7 @@ completion feature of your IDE to discover what attributes and sub-elements are available. + [[mvc-config-conversion]] === Type conversion [.small]#<># @@ -4066,6 +4122,7 @@ and the `FormattingConversionServiceFactoryBean` for more information on when to ==== + [[mvc-config-validation]] === Validation [.small]#<># @@ -4229,6 +4286,7 @@ In XML, the same: ---- + [[mvc-config-message-converters]] === Message Converters [.small]#<># @@ -4319,6 +4377,7 @@ It is also possible to do the same in XML: ---- + [[mvc-config-view-controller]] === View Controllers @@ -4352,6 +4411,7 @@ And the same in XML use the `` element: ---- + [[mvc-config-view-resolvers]] === View Resolvers [.small]#<># @@ -4550,6 +4610,7 @@ match to incoming URLs without versions -- e.g. `"/jquery/jquery.min.js"` to `"/jquery/1.2.0/jquery.min.js"`. + [[mvc-default-servlet-handler]] === Default Servlet @@ -4736,7 +4797,6 @@ Note that `MyPostProcessor` needs to be declared as a bean either explicitly in detected through a `` declaration. -include::webmvc-view.adoc[leveloffset=+1] - +include::webmvc-view.adoc[leveloffset=+1] diff --git a/src/docs/asciidoc/web/websocket.adoc b/src/docs/asciidoc/web/websocket.adoc index 355a6ce45f9..4a6433cadbf 100644 --- a/src/docs/asciidoc/web/websocket.adoc +++ b/src/docs/asciidoc/web/websocket.adoc @@ -2,7 +2,6 @@ = WebSockets :doc-spring-security: {doc-root}/spring-security/site/docs/current/reference - This part of the reference documentation covers the Spring Framework support for Servlet stack based WebSocket messaging including use of STOMP as a a WebSocket sub-protocol. @@ -24,8 +23,10 @@ applications. + [[websocket-intro]] == Introduction + The WebSocket protocol http://tools.ietf.org/html/rfc6455[RFC 6455] defines an important new capability for web applications: full-duplex, two-way communication between client and server. It is an exciting new capability on the heels of a long history of @@ -49,6 +50,7 @@ and also provides additional value-add as explained in the rest of the introduct [[websocket-into-fallback-options]] === Fallback Options + An important challenge to adoption is the lack of support for WebSocket in some browsers. Notably the first Internet Explorer version to support WebSocket is version 10 (see http://caniuse.com/websockets for support by browser versions). @@ -68,6 +70,7 @@ application otherwise. [[websocket-intro-architecture]] === Messaging + Aside from short-to-midterm adoption challenges, using WebSocket brings up important design considerations that are important to recognize early on, especially in contrast to what we know about building web applications today. @@ -95,6 +98,7 @@ annotation based programming model. [[websocket-intro-sub-protocol]] === WebSocket Sub-Protocol + WebSocket does imply a __messaging architecture__ but does not mandate the use of any specific __messaging protocol__. It is a very thin layer over TCP that transforms a stream of bytes into a stream of messages @@ -128,6 +132,7 @@ WebSocket and over the web. [[websocket-intro-when-to-use]] === Do I Use WebSocket? + With all the design considerations surrounding the use of WebSocket, it is reasonable to ask, "When is it appropriate to use?". @@ -171,6 +176,7 @@ WebSocket clients or to a specific user. [[websocket-server]] == WebSocket API + The Spring Framework provides a WebSocket API designed to adapt to various WebSocket engines. Currently the list includes WebSocket runtimes such as Tomcat 7.0.47+, Jetty 9.1+, GlassFish 4.1+, WebLogic 12.1.3+, and Undertow 1.0+ (and WildFly 8.0+). Additional support @@ -194,6 +200,7 @@ directly. [[websocket-server-handler]] === WebSocketHandler + Creating a WebSocket server is as simple as implementing `WebSocketHandler` or more likely extending either `TextWebSocketHandler` or `BinaryWebSocketHandler`: @@ -274,6 +281,7 @@ into other HTTP serving environments with the help of [[websocket-server-handshake]] === WebSocket Handshake + The easiest way to customize the initial HTTP WebSocket handshake request is through a `HandshakeInterceptor`, which exposes "before" and "after" the handshake methods. Such an interceptor can be used to preclude the handshake or to make any attributes @@ -346,6 +354,7 @@ session with status `1011` that indicates a server error. [[websocket-server-deployment]] === Deployment + The Spring WebSocket API is easy to integrate into a Spring MVC application where the `DispatcherServlet` serves both HTTP WebSocket handshake as well as other HTTP requests. It is also easy to integrate into other HTTP processing scenarios @@ -417,6 +426,8 @@ Java initialization API, if required: ---- + + [[websocket-server-runtime-configuration]] === Server config @@ -543,6 +554,8 @@ or WebSocket XML namespace: ---- + + [[websocket-server-allowed-origins]] === Allowed origins @@ -615,14 +628,19 @@ XML configuration equivalent: ---- + + [[websocket-fallback]] == SockJS Fallback + As explained in the <>, WebSocket is not supported in all browsers yet and may be precluded by restrictive network proxies. This is why Spring provides fallback options that emulate the WebSocket API as close as possible based on the https://github.com/sockjs/sockjs-protocol[SockJS protocol] (version 0.3.3). + + [[websocket-fallback-sockjs-overview]] === Overview @@ -684,8 +702,10 @@ For even more detail refer to the SockJS protocol http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html[narrated test]. + [[websocket-fallback-sockjs-enable]] === Enable SockJS + SockJS is easy to enable through Java configuration: [source,java,indent=0] @@ -746,6 +766,8 @@ https://github.com/sockjs/sockjs-client/[sockjs-client] page and the list of transport types supported by browser. The client also provides several configuration options, for example, to specify which transports to include. + + [[websocket-fallback-xhr-vs-iframe]] === IE 8, 9 @@ -827,6 +849,8 @@ be cached. For details on how to enable it see the https://github.com/sockjs/sockjs-client/[SockJS client] page. ==== + + [[websocket-fallback-sockjs-heartbeat]] === Heartbeats @@ -848,6 +872,8 @@ for scheduling heartbeats tasks. The task scheduler is backed by a thread pool with default settings based on the number of available processors. Applications should consider customizing the settings according to their specific needs. + + [[websocket-fallback-sockjs-servlet3-async]] === Client disconnects @@ -876,6 +902,8 @@ defined in `AbstractSockJsSession`. If you need to see the stack traces, set tha log category to TRACE. ==== + + [[websocket-fallback-cors]] === SockJS and CORS @@ -903,6 +931,7 @@ Alternatively if the CORS configuration allows it consider excluding URLs with t SockJS endpoint prefix thus letting Spring's `SockJsService` handle it. + [[websocket-fallback-sockjs-client]] === SockJsClient @@ -986,6 +1015,7 @@ public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport [[websocket-stomp]] == STOMP + The WebSocket protocol defines two types of messages, text and binary, but their content is undefined. It's expected that the client and server may agree on using a sub-protocol (i.e. a higher-level protocol) to define message semantics. @@ -997,6 +1027,7 @@ messages. [[websocket-stomp-overview]] === Overview + http://stomp.github.io/stomp-specification-1.2.html#Abstract[STOMP] is a simple text-oriented messaging protocol that was originally created for scripting languages such as Ruby, Python, and Perl to connect to enterprise message brokers. It is @@ -1102,6 +1133,7 @@ Spring MVC provides a programming model based on HTTP. [[websocket-stomp-enable]] === Enable STOMP + The Spring Framework provides support for using STOMP over WebSocket through the +spring-messaging+ and +spring-websocket+ modules. Here is an example of exposing a STOMP WebSocket/SockJS endpoint at the URL path @@ -1207,6 +1239,7 @@ sections <> and <> for more information on authentication. + [[websocket-stomp-message-flow]] === Flow of Messages @@ -1430,6 +1463,7 @@ But it can also be qualified by its name "brokerMessagingTemplate" if another bean of the same type exists. + [[websocket-stomp-handle-simple-broker]] === Simple Broker @@ -1446,7 +1480,6 @@ See <>. - [[websocket-stomp-handle-broker-relay]] === External Broker @@ -1529,6 +1562,8 @@ subscribed WebSocket clients. In effect, the broker relay enables robust and scalable message broadcasting. + + [[websocket-stomp-handle-broker-relay-configure]] === Connect to Broker @@ -1574,6 +1609,8 @@ and may be useful for example in a cloud environment where the actual host to wh the TCP connection is established is different from the host providing the cloud-based STOMP service. + + [[websocket-stomp-destination-separator]] === Dot as Separator @@ -1649,7 +1686,6 @@ If the application prefix is set to "/app" then the foo method is effectively ma - [[websocket-stomp-authentication]] === Authentication @@ -1776,7 +1812,6 @@ its own sub-class of `AbstractWebSocketMessageBrokerConfigurer` marked with - [[websocket-stomp-user-destination]] === User Destinations @@ -1900,7 +1935,6 @@ of the `message-broker` element in XML. - [[websocket-stomp-appplication-context-events]] === Events and Interception @@ -1980,6 +2014,7 @@ to access information about the message. ---- + [[websocket-stomp-client]] === STOMP Client @@ -2380,6 +2415,8 @@ SockJS Task Scheduler:: stats from thread pool of the SockJS task scheduler whic is used to send heartbeats. Note that when heartbeats are negotiated on the STOMP level the SockJS heartbeats are disabled. + + [[websocket-stomp-testing]] === Testing