From 59b27004dea31d0dd46465d1d254c5df4de3be0c Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 20 Nov 2012 12:09:44 -0800 Subject: [PATCH] Document @Enable* annotations Update reference manual with details of Java configuration @Enable* annotations. Examples of Java style @Configuration is provided when appropriate alongside existing XML samples. Several existing @Configuration samples have been changed to placing the @Enable annotation below the @Configuration annotation. This has been done to provide consistency with existing Javadoc. Issue: SPR-9920 --- src/reference/docbook/aop.xml | 165 ++++++++---- src/reference/docbook/beans.xml | 21 +- src/reference/docbook/cache.xml | 31 ++- src/reference/docbook/index.xml | 10 +- src/reference/docbook/jmx.xml | 31 ++- src/reference/docbook/mvc.xml | 40 +-- src/reference/docbook/orm.xml | 2 +- src/reference/docbook/scheduling.xml | 344 ++++++++++++++------------ src/reference/docbook/transaction.xml | 46 ++-- 9 files changed, 415 insertions(+), 275 deletions(-) diff --git a/src/reference/docbook/aop.xml b/src/reference/docbook/aop.xml index 1b7dd7a8d6d..cda64fe4c7a 100644 --- a/src/reference/docbook/aop.xml +++ b/src/reference/docbook/aop.xml @@ -327,27 +327,46 @@ automatically generate a proxy for that bean to intercept method invocations and ensure that advice is executed as needed. - The @AspectJ support is enabled by including the following element - inside your spring configuration: + The @AspectJ support can be enabled with XML or Java style + configuration. In either case you will also need to ensure that + AspectJ's aspectjrt.jar + library is on the classpath of your application (version 1.6.8 or later). + This library is available in the 'lib' + directory of an AspectJ distribution or via the Maven Central repository. - <aop:aspectj-autoproxy/> +
+ Enabling @AspectJ Support with Java configuration - This assumes that you are using schema support as described in - . See for how to import the tags in - the aop namespace. + To enable @AspectJ support with Java + @Configuration add the + @EnableAspectJAutoProxy annotation: - If you are using the DTD, it is still possible to enable @AspectJ - support by adding the following definition to your application - context: + @Configuration +@EnableAspectJAutoProxy +public class AppConfig { - <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" /> +} +
- You will also need AspectJ's - aspectjrt.jar library on the - classpath of your application, version 1.6.8 or later. This library is - available in the 'lib' directory - of an AspectJ distribution or via the Maven Central repository. +
+ Enabling @AspectJ Support with XML configuration + + To enable @AspectJ support with XML based configuration use the + aop:aspectj-autoproxy element: + + <aop:aspectj-autoproxy/> + + This assumes that you are using schema support as described in + . See for how to import the tags in + the aop namespace. + + If you are using the DTD, it is still possible to enable @AspectJ + support by adding the following definition to your application + context: + + <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" /> +
@@ -2929,10 +2948,21 @@ public class Account { linkend="aop-aj-ltw"/>). The AnnotationBeanConfigurerAspect itself needs configuring by Spring (in order to obtain a reference to the bean - factory that is to be used to configure new objects). The Spring @EnableSpringConfigured to any + @Configuration class. + + @Configuration +@EnableSpringConfigured +public class AppConfig { + +} + + If you prefer XML based configuration, the Spring context - namespace defines a convenient tag for doing this: just include - the following in your application context configuration: + namespace defines a convenient + context:spring-configured element: <context:spring-configured/> @@ -3000,7 +3030,7 @@ public class Account { there is one aspect instance per classloader that defines the type. This means that if you define multiple application contexts within the same classloader hierarchy you need to consider where to define the - <context:spring-configured/> bean and where to + @EnableSpringConfigured bean and where to place spring-aspects.jar on the classpath. @@ -3011,7 +3041,7 @@ public class Account { these contexts will co-exist within the same classloader hierarchy, and so the AnnotationBeanConfigurerAspect can only hold a reference to one of them. In this case we recommend defining - the <context:spring-configured/> bean in the + the @EnableSpringConfigured bean in the shared (parent) application context: this defines the services that you are likely to want to inject into domain objects. A consequence is that you cannot configure domain objects with references to beans @@ -3199,6 +3229,16 @@ public class Account { finer-grained profiling tool to that specific area immediately afterwards. + + The example presented here uses XML style configuration, it is + also possible to configure and use @AspectJ with + Java Configuration. + Specifically the @EnableLoadTimeWeaving + annotation can be used as an alternative to + <context:load-time-weaver/> + (see below for details). + + Here is the profiling aspect. Nothing too fancy, just a quick-and-dirty time-based profiler, using the @AspectJ-style of aspect declaration. @@ -3477,7 +3517,7 @@ public final class Main { Configuring a LoadTimeWeaver - using XML for a particular + for a particular ApplicationContext can be as easy as adding one line. (Please note that you almost certainly will need to be using an ApplicationContext as your @@ -3489,9 +3529,17 @@ public final class Main { To enable the Spring Framework's LTW support, you need to configure a LoadTimeWeaver, which typically is done using the - <context:load-time-weaver/> element. Find - below a valid <context:load-time-weaver/> - definition that uses default settings. + @EnableLoadTimeWeaving annotation. + + @Configuration +@EnableLoadTimeWeaving +public class AppConfig { + +} + + Alternatively, if you prefer XML based configuration, use the + <context:load-time-weaver/> element. Note + that the element is defined in the 'context' namespace. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" @@ -3507,19 +3555,11 @@ http://www.springframework.org/schema/context </beans> - The above <context:load-time-weaver/> - bean definition will define and register a number of LTW-specific - infrastructure beans for you automatically, such as a - LoadTimeWeaver and an - AspectJWeavingEnabler. Notice how the - <context:load-time-weaver/> is defined in the - 'context' namespace; note also that the referenced - XML Schema file is only available in versions of Spring 2.5 and - later. - - What the above configuration does is define and register a - default LoadTimeWeaver bean for you. - The default LoadTimeWeaver is the + The above configuration will define and register a number of + LTW-specific infrastructure beans for you automatically, such + as a LoadTimeWeaver and an + AspectJWeavingEnabler. The default + LoadTimeWeaver is the DefaultContextLoadTimeWeaver class, which attempts to decorate an automatically detected LoadTimeWeaver: the exact type of @@ -3595,12 +3635,26 @@ http://www.springframework.org/schema/context when using the DefaultContextLoadTimeWeaver: it is of course possible to specify exactly which LoadTimeWeaver implementation that you - wish to use by specifying the fully-qualified classname as the value - of the 'weaver-class' attribute of the - <context:load-time-weaver/> element. Find - below an example of doing just that: + wish to use. + + To specify a specific LoadTimeWeaver + with Java configuration implement the + LoadTimeWeavingConfigurer interface and override + the getLoadTimeWeaver() method: + + @Configuration +@EnableLoadTimeWeaving +public class AppConfig implements LoadTimeWeavingConfigurer { + @Override + public LoadTimeWeaver getLoadTimeWeaver() { + return new ReflectiveLoadTimeWeaver(); + } +} + + If you are using XML based configuration you can specify the fully-qualified + classname as the value of the 'weaver-class' attribute on the + <context:load-time-weaver/> element: - <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" @@ -3617,8 +3671,7 @@ http://www.springframework.org/schema/context </beans> The LoadTimeWeaver that is - defined and registered by the - <context:load-time-weaver/> element can be + defined and registered by the configuration can be later retrieved from the Spring container using the well-known name 'loadTimeWeaver'. Remember that the LoadTimeWeaver exists just as a @@ -3632,41 +3685,45 @@ http://www.springframework.org/schema/context details, because the specifics of how the weaving is actually effected is beyond the scope of this section. - There is one final attribute of the - <context:load-time-weaver/> left to discuss: - the 'aspectj-weaving' attribute. This is a simple + There is one final attribute of the configuration left to discuss: + the 'aspectjWeaving' attribute + (or 'aspectj-weaving' if you are using XML). This is a simple attribute that controls whether LTW is enabled or not, it is as simple as that. It accepts one of three possible values, summarised below, - with the default value if the attribute is not present being ' - autodetect' + with the default value if the attribute is not present being + 'autodetect' - '<literal>aspectj-weaving</literal>' attribute values + AspectJ weaving attribute values - + - Attribute Value + Annotation Value + XML Value Explanation + ENABLED on AspectJ weaving is on, and aspects will be woven at load-time as appropriate. + DISABLED off LTW is off... no aspect will be woven at load-time. + AUTODETECT autodetect If the Spring LTW infrastructure can find at least one 'META-INF/aop.xml' file, then @@ -3809,7 +3866,7 @@ TR: REVISED, PLS REVIEW. Chnaged the last one to *inside*--> is recommended Oracle Containers for Java EE (OC4J 10.1.3.1 and above), Resin (3.1 and above) and JBoss (5.x or above) provide a ClassLoader that is capable of local instrumentation. Spring's native LTW leverages such ClassLoaders to enable AspectJ weaving. - You can enable LTW by simply activating context:load-time-weaver + You can enable LTW by simply activating load-time weaving as described earlier. Specifically, you do not need to modify the launch script to add -javaagent:path/to/spring-instrument.jar. diff --git a/src/reference/docbook/beans.xml b/src/reference/docbook/beans.xml index c2c4425b961..00ad057fe6e 100644 --- a/src/reference/docbook/beans.xml +++ b/src/reference/docbook/beans.xml @@ -953,18 +953,25 @@ List userList = service.getUsernameList();
Registering a <interfacename>LoadTimeWeaver</interfacename> - The context namespace introduced in Spring 2.5 - provides a load-time-weaver - element. + The LoadTimeWeaver is used by Spring to dynamically + transform classes as they are loaded into the Java virtual machine (JVM). + + To enable load-time weaving add the @EnableLoadTimeWeaving + to one of your @Configuration classes: + + @Configuration +@EnableLoadTimeWeaving +public class AppConfig { + +} + + Alternatively for XML configuration use the context:load-time-weaver element: <beans> - <context:load-time-weaver/> - </beans> - Adding this element to an XML-based Spring configuration file - activates a Spring LoadTimeWeaver for the + Once configured for the ApplicationContext. Any bean within that ApplicationContext may implement LoadTimeWeaverAware, thereby receiving a diff --git a/src/reference/docbook/cache.xml b/src/reference/docbook/cache.xml index 194e92a4765..85b7beff656 100644 --- a/src/reference/docbook/cache.xml +++ b/src/reference/docbook/cache.xml @@ -273,8 +273,17 @@ public Book importBooks(String deposit, Date date)]]> Enable caching annotations It is important to note that even though declaring the cache annotations does not automatically triggers 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 disable it by removing only one configuration line rather then all the annotations in your code). In practice, this - translates to one line that informs Spring that it should process the cache annotations, namely: + enabled (which means if you ever suspect caching is to blame, you can disable it by removing only one configuration line rather then all the annotations in your code). + + To enable caching annotations add the annotation @EnableCaching to one of your @Configuration classes: + + @Configuration +@EnableCaching +public class AppConfig { + +} + + Alternatively for XML configuration use the cache:annotation-driven element: xmlns:cache="http://www.springframework.org/schema/cache" ]]> ]]> - The namespace allows various options to be specified that influence the way the caching behaviour is added to the application through AOP. The configuration is similar (on purpose) - with that of tx:annotation-driven: + Both the cache:annotation-driven element and @EnableCaching annotation allow various options to be specified that influence the way the + caching behaviour is added to the application through AOP. The configuration is intentionally similar + with that of @Transactional:
- <literal><cache:annotation-driven/></literal> - settings + Cache annotation settings - + - Attribute + XML Attribute + + Annotation Attribute Default @@ -305,6 +316,7 @@ public Book importBooks(String deposit, Date date)]]> cache-manager + N/A (See CachingConfigurer Javadoc) cacheManager @@ -316,6 +328,7 @@ public Book importBooks(String deposit, Date date)]]> mode + mode proxy @@ -334,6 +347,7 @@ public Book importBooks(String deposit, Date date)]]> proxy-target-class + proxyTargetClass false @@ -351,6 +365,7 @@ public Book importBooks(String deposit, Date date)]]> order + order Ordered.LOWEST_PRECEDENCE diff --git a/src/reference/docbook/index.xml b/src/reference/docbook/index.xml index 50b859a38a5..50b2075d343 100644 --- a/src/reference/docbook/index.xml +++ b/src/reference/docbook/index.xml @@ -176,9 +176,16 @@ Rossen + Stoyanchev + + Phillip + + Webb + + @@ -189,7 +196,8 @@ Kopylenko, Mark Pollack, Thierry Templier, Erwin Vervaet, Portia Tung, Ben Hale, Adrian Colyer, John Lewis, Costin Leau, Mark Fisher, Sam Brannen, Ramnivas Laddad, Arjen Poutsma, Chris Beams, Tareq Abedrabbo, - Andy Clement, Dave Syer, Oliver Gierke, Rossen Stoyanchev + Andy Clement, Dave Syer, Oliver Gierke, Rossen Stoyanchev, + Phillip Webb diff --git a/src/reference/docbook/jmx.xml b/src/reference/docbook/jmx.xml index 6f9707dc4bf..891fd5bc22a 100644 --- a/src/reference/docbook/jmx.xml +++ b/src/reference/docbook/jmx.xml @@ -433,7 +433,6 @@ public class JmxTestBean implements IJmxTestBean { must be configured with an implementation instance of the JmxAttributeSource interface for it to function correctly (there is no default). - To mark a bean for export to JMX, you should annotate the bean class with the ManagedResource annotation. Each method you wish to expose as an operation must be marked with the @@ -1076,21 +1075,31 @@ public class AnnotationTestBean implements IJmxTestBean {
- The <literal><context:mbean-export/></literal> element - If you are using at least Java 5, then a convenience subclass of + Configuring annotation based MBean export + If you prefer using the annotation based + approach to define your management interfaces, then a convenience subclass of MBeanExporter is available: AnnotationMBeanExporter. When defining an instance of this subclass, the namingStrategy, assembler, and attributeSource configuration is no longer needed, since it will always use standard Java annotation-based metadata (autodetection is always enabled as well). In fact, - an even simpler syntax is supported by Spring's - 'context' namespace.. Rather than defining an - MBeanExporter bean, just provide this single element: + rather than defining an MBeanExporter bean, an even + simpler syntax is supported by the @EnableMBeanExport + @Configuration annotation. + + @Configuration +@EnableMBeanExport +public class AppConfig { + +} + + If you prefer XML based configuration the 'context:mbean-export' + element serves the same purpose. ]]> - You can provide a reference to a particular MBean server if + You can provide a reference to a particular MBean server if necessary, and the defaultDomain attribute (a property of AnnotationMBeanExporter) accepts an alternate value for the generated MBean @@ -1100,7 +1109,13 @@ public class AnnotationTestBean implements IJmxTestBean { MetadataNamingStrategy. - ]]>. + @EnableMBeanExport(server="myMBeanServer", defaultDomain="myDomain") +@Configuration +ContextConfiguration { + +} + + ]]> Do not use interface-based AOP proxies in combination with autodetection of diff --git a/src/reference/docbook/mvc.xml b/src/reference/docbook/mvc.xml index f7ebb14641b..3a6559268a3 100644 --- a/src/reference/docbook/mvc.xml +++ b/src/reference/docbook/mvc.xml @@ -4560,8 +4560,8 @@ public class MyWebApplicationInitializer implements WebApplicationInitializer { @EnableWebMvc to one of your @Configuration classes: - @EnableWebMvc -@Configuration + @Configuration +@EnableWebMvc public class WebConfig { } @@ -4702,8 +4702,8 @@ public class WebConfig { methods to override. See WebMvcConifgurer for a list of all methods and the Javadoc for further details: - @EnableWebMvc -@Configuration + @Configuration +@EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override @@ -4753,8 +4753,8 @@ public class WebConfig extends WebMvcConfigurerAdapter { An example of registering interceptors in Java: - @EnableWebMvc -@Configuration + @Configuration +@EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override @@ -4799,8 +4799,8 @@ public class WebConfig extends WebMvcConfigurerAdapter { An example of customizing content negotiation in Java: - @EnableWebMvc -@Configuration + @Configuration +@EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override @@ -4839,8 +4839,8 @@ public class WebConfig extends WebMvcConfigurerAdapter { An example of forwarding a request for "/" to a view called "home" in Java: - @EnableWebMvc -@Configuration + @Configuration +@EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override @@ -4875,8 +4875,8 @@ public class WebConfig extends WebMvcConfigurerAdapter { /resources/** from a public-resources directory within the web application root you would use: - @EnableWebMvc -@Configuration + @Configuration +@EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override @@ -4894,8 +4894,8 @@ public class WebConfig extends WebMvcConfigurerAdapter { maximum use of the browser cache and a reduction in HTTP requests made by the browser: - @EnableWebMvc -@Configuration + @Configuration +@EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override @@ -4972,8 +4972,8 @@ public class WebConfig extends WebMvcConfigurerAdapter { annotation and then inject the Environment abstraction for access to all defined properties: - @EnableWebMvc -@Configuration + @Configuration +@EnableWebMvc @PropertySource("/WEB-INF/spring/application.properties") public class WebConfig extends WebMvcConfigurerAdapter { @@ -5020,8 +5020,8 @@ public class WebConfig extends WebMvcConfigurerAdapter { To enable the feature using the default setup use: - @EnableWebMvc -@Configuration + @Configuration +@EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override @@ -5047,8 +5047,8 @@ public class WebConfig extends WebMvcConfigurerAdapter { the default Servlet name is unknown, then the default Servlet's name must be explicitly provided as in the following example: - @EnableWebMvc -@Configuration + @Configuration +@EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override diff --git a/src/reference/docbook/orm.xml b/src/reference/docbook/orm.xml index 252d63a9961..9e5fad0ab34 100644 --- a/src/reference/docbook/orm.xml +++ b/src/reference/docbook/orm.xml @@ -1474,7 +1474,7 @@ TR: OK AS IS. The requirement is to provide the classloader for the runtime envi As described in the aforementioned section, you can configure a context-wide LoadTimeWeaver - using the context:load-time-weaver configuration element. (This has been available since Spring 2.5.) + using the @EnableLoadTimeWeaving annotation of context:load-time-weaver XML element. Such a global weaver is picked up by all JPA LocalContainerEntityManagerFactoryBeans automatically. This is the preferred way of setting up a load-time weaver, delivering autodetection of the platform (WebLogic, OC4J, GlassFish, Tomcat, Resin, JBoss or VM agent) and automatic propagation of the weaver to all weaver-aware beans: diff --git a/src/reference/docbook/scheduling.xml b/src/reference/docbook/scheduling.xml index 61db3be7985..dab9706a73f 100644 --- a/src/reference/docbook/scheduling.xml +++ b/src/reference/docbook/scheduling.xml @@ -357,155 +357,52 @@ public class TaskExecutorExample {
-
- 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. - -
- The 'scheduler' element - - The following element will create a - ThreadPoolTaskScheduler instance with the - specified thread pool size. - - <task:scheduler id="scheduler" pool-size="10"/> - - The value provided for the 'id' attribute will be used as the - prefix for thread names within the pool. The 'scheduler' element is - relatively straightforward. If you do not provide a 'pool-size' - attribute, the default thread pool will only have a single thread. There - are no other configuration options for the scheduler. -
- -
- The 'executor' element - - The following will create a - ThreadPoolTaskExecutor instance: <task:executor id="executor" pool-size="10"/> - - As with the scheduler above, the value provided for the 'id' - attribute will be used as the prefix for thread names within the pool. - As far as the pool size is concerned, the 'executor' element supports - more configuration options than the 'scheduler' element. For one thing, - the thread pool for a ThreadPoolTaskExecutor is - itself more configurable. Rather than just a single size, an executor's - thread pool may have different values for the core - and the max size. If a single value is provided - then the executor will have a fixed-size thread pool (the core and max - sizes are the same). However, the 'executor' element's 'pool-size' - attribute also accepts a range in the form of "min-max". <task:executor id="executorWithPoolSizeRange" - pool-size="5-25" - queue-capacity="100"/> - - As you can see from that configuration, a 'queue-capacity' value - has also been provided. The configuration of the thread pool should also - be considered in light of the executor's queue capacity. For the full - description of the relationship between pool size and queue capacity, - consult the documentation for ThreadPoolExecutor. - The main idea is that when a task is submitted, the executor will first - try to use a free thread if the number of active threads is currently - less than the core size. If the core size has been reached, then the - task will be added to the queue as long as its capacity has not yet been - reached. Only then, if the queue's capacity has - been reached, will the executor create a new thread beyond the core - size. If the max size has also been reached, then the executor will - reject the task. - - By default, the queue is unbounded, but this - is rarely the desired configuration, because it can lead to - OutOfMemoryErrors if enough tasks are added to - that queue while all pool threads are busy. Furthermore, if the queue is - unbounded, then the max size has no effect at all. Since the executor - will always try the queue before creating a new thread beyond the core - size, a queue must have a finite capacity for the thread pool to grow - beyond the core size (this is why a fixed size pool - is the only sensible case when using an unbounded queue). - - In a moment, we will review the effects of the keep-alive setting - which adds yet another factor to consider when providing a pool size - configuration. First, let's consider the case, as mentioned above, when - a task is rejected. By default, when a task is rejected, a thread pool - executor will throw a TaskRejectedException. - However, the rejection policy is actually configurable. The exception is - thrown when using the default rejection policy which is the - AbortPolicy implementation. For applications - where some tasks can be skipped under heavy load, either the - DiscardPolicy or - DiscardOldestPolicy may be configured instead. - Another option that works well for applications that need to throttle - the submitted tasks under heavy load is the - CallerRunsPolicy. Instead of throwing an - exception or discarding tasks, that policy will simply force the thread - that is calling the submit method to run the task itself. The idea is - that such a caller will be busy while running that task and not able to - submit other tasks immediately. Therefore it provides a simple way to - throttle the incoming load while maintaining the limits of the thread - pool and queue. Typically this allows the executor to "catch up" on the - tasks it is handling and thereby frees up some capacity on the queue, in - the pool, or both. Any of these options can be chosen from an - enumeration of values available for the 'rejection-policy' attribute on - the 'executor' element. - - <task:executor id="executorWithCallerRunsPolicy" - pool-size="5-25" - queue-capacity="100" - rejection-policy="CALLER_RUNS"/> -
- -
- 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 - for configuring Message-driven POJOs. Basically a "ref" attribute can - point to any Spring-managed object, and the "method" attribute provides - the name of a method to be invoked on that object. Here is a simple - example. - - <task:scheduled-tasks scheduler="myScheduler"> - <task:scheduled ref="beanA" method="methodA" fixed-delay="5000"/> -</task:scheduled-tasks> - -<task:scheduler id="myScheduler" pool-size="10"/> - - As you can see, the scheduler is referenced by the outer element, - and each individual task includes the configuration of its trigger - metadata. In the preceding example, that metadata defines a periodic - trigger with a fixed delay indicating the number of milliseconds to wait - after each task execution has completed. Another option is 'fixed-rate', - indicating how often the method should be executed regardless of how long - any previous execution takes. Additionally, for both fixed-delay and - fixed-rate tasks an 'initial-delay' parameter may be specified indicating - the number of milliseconds to wait before the first execution of the - method. For more control, a "cron" attribute may be provided instead. - Here is an example demonstrating these other options. - - <task:scheduled-tasks scheduler="myScheduler"> - <task:scheduled ref="beanA" method="methodA" fixed-delay="5000" initial-delay="1000"/> - <task:scheduled ref="beanB" method="methodB" fixed-rate="5000"/> - <task:scheduled ref="beanC" method="methodC" cron="*/5 * * * * MON-FRI"/> -</task:scheduled-tasks> - -<task:scheduler id="myScheduler" pool-size="10"/> -
-
-
Annotation Support for Scheduling and Asynchronous Execution - Spring 3.0 also adds annotation support for both task scheduling and + Spring provides annotation support for both task scheduling and asynchronous method execution. +
+ + Enable scheduling annotations + + To enable support for @Scheduled and + @Async annotations add + @EnableScheduling and + @EnableAsync to one of your + @Configuration classes: + + @Configuration +@EnableAsync +@EnableSCheduling +public class AppConfig { +} + + You are free to pick and choose the relevant annotations + for your application. For example, if you only need support + for @Scheduled, simply omit + @EnableAsync. For more fine-grained + control you can additionally implement the + SchedulingConfigurer and/or + AsyncConfigurer interfaces. See + the Javadoc for full details. + + If you prefer XML configuration use the + <task:annotation-driven> element. + + <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/> +<task:executor id="myExecutor" pool-size="5"/> +<task:scheduler id="myScheduler" pool-size="10"/>} + + Notice with the above XML that an executor reference is provided + for handling those tasks that correspond to methods with the + @Async annotation, and the scheduler + reference is provided for managing those methods annotated + with @Scheduled. +
+
The @Scheduled Annotation @@ -636,25 +533,6 @@ public class SampleBeanInititalizer { }
-
- The <annotation-driven> Element - - To enable both @Scheduled and @Async annotations, simply include - the 'annotation-driven' element from the task namespace in your - configuration. - - <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/> - -<task:executor id="myExecutor" pool-size="5"/> - -<task:scheduler id="myScheduler" pool-size="10"/>} - - Notice that an executor reference is provided for handling those - tasks that correspond to methods with the @Async annotation, and the - scheduler reference is provided for managing those methods annotated - with @Scheduled. -
-
Executor qualification with @Async @@ -679,6 +557,148 @@ void doSomething(String s) {
+
+ 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. + +
+ The 'scheduler' element + + The following element will create a + ThreadPoolTaskScheduler instance with the + specified thread pool size. + + <task:scheduler id="scheduler" pool-size="10"/> + + The value provided for the 'id' attribute will be used as the + prefix for thread names within the pool. The 'scheduler' element is + relatively straightforward. If you do not provide a 'pool-size' + attribute, the default thread pool will only have a single thread. There + are no other configuration options for the scheduler. +
+ +
+ The 'executor' element + + The following will create a + ThreadPoolTaskExecutor instance: <task:executor id="executor" pool-size="10"/> + + As with the scheduler above, the value provided for the 'id' + attribute will be used as the prefix for thread names within the pool. + As far as the pool size is concerned, the 'executor' element supports + more configuration options than the 'scheduler' element. For one thing, + the thread pool for a ThreadPoolTaskExecutor is + itself more configurable. Rather than just a single size, an executor's + thread pool may have different values for the core + and the max size. If a single value is provided + then the executor will have a fixed-size thread pool (the core and max + sizes are the same). However, the 'executor' element's 'pool-size' + attribute also accepts a range in the form of "min-max". <task:executor id="executorWithPoolSizeRange" + pool-size="5-25" + queue-capacity="100"/> + + As you can see from that configuration, a 'queue-capacity' value + has also been provided. The configuration of the thread pool should also + be considered in light of the executor's queue capacity. For the full + description of the relationship between pool size and queue capacity, + consult the documentation for ThreadPoolExecutor. + The main idea is that when a task is submitted, the executor will first + try to use a free thread if the number of active threads is currently + less than the core size. If the core size has been reached, then the + task will be added to the queue as long as its capacity has not yet been + reached. Only then, if the queue's capacity has + been reached, will the executor create a new thread beyond the core + size. If the max size has also been reached, then the executor will + reject the task. + + By default, the queue is unbounded, but this + is rarely the desired configuration, because it can lead to + OutOfMemoryErrors if enough tasks are added to + that queue while all pool threads are busy. Furthermore, if the queue is + unbounded, then the max size has no effect at all. Since the executor + will always try the queue before creating a new thread beyond the core + size, a queue must have a finite capacity for the thread pool to grow + beyond the core size (this is why a fixed size pool + is the only sensible case when using an unbounded queue). + + In a moment, we will review the effects of the keep-alive setting + which adds yet another factor to consider when providing a pool size + configuration. First, let's consider the case, as mentioned above, when + a task is rejected. By default, when a task is rejected, a thread pool + executor will throw a TaskRejectedException. + However, the rejection policy is actually configurable. The exception is + thrown when using the default rejection policy which is the + AbortPolicy implementation. For applications + where some tasks can be skipped under heavy load, either the + DiscardPolicy or + DiscardOldestPolicy may be configured instead. + Another option that works well for applications that need to throttle + the submitted tasks under heavy load is the + CallerRunsPolicy. Instead of throwing an + exception or discarding tasks, that policy will simply force the thread + that is calling the submit method to run the task itself. The idea is + that such a caller will be busy while running that task and not able to + submit other tasks immediately. Therefore it provides a simple way to + throttle the incoming load while maintaining the limits of the thread + pool and queue. Typically this allows the executor to "catch up" on the + tasks it is handling and thereby frees up some capacity on the queue, in + the pool, or both. Any of these options can be chosen from an + enumeration of values available for the 'rejection-policy' attribute on + the 'executor' element. + + <task:executor id="executorWithCallerRunsPolicy" + pool-size="5-25" + queue-capacity="100" + rejection-policy="CALLER_RUNS"/> +
+ +
+ 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 + for configuring Message-driven POJOs. Basically a "ref" attribute can + point to any Spring-managed object, and the "method" attribute provides + the name of a method to be invoked on that object. Here is a simple + example. + + <task:scheduled-tasks scheduler="myScheduler"> + <task:scheduled ref="beanA" method="methodA" fixed-delay="5000"/> +</task:scheduled-tasks> + +<task:scheduler id="myScheduler" pool-size="10"/> + + As you can see, the scheduler is referenced by the outer element, + and each individual task includes the configuration of its trigger + metadata. In the preceding example, that metadata defines a periodic + trigger with a fixed delay indicating the number of milliseconds to wait + after each task execution has completed. Another option is 'fixed-rate', + indicating how often the method should be executed regardless of how long + any previous execution takes. Additionally, for both fixed-delay and + fixed-rate tasks an 'initial-delay' parameter may be specified indicating + the number of milliseconds to wait before the first execution of the + method. For more control, a "cron" attribute may be provided instead. + Here is an example demonstrating these other options. + + <task:scheduled-tasks scheduler="myScheduler"> + <task:scheduled ref="beanA" method="methodA" fixed-delay="5000" initial-delay="1000"/> + <task:scheduled ref="beanB" method="methodB" fixed-rate="5000"/> + <task:scheduled ref="beanC" method="methodC" cron="*/5 * * * * MON-FRI"/> +</task:scheduled-tasks> + +<task:scheduler id="myScheduler" pool-size="10"/> +
+
+
Using the Quartz Scheduler diff --git a/src/reference/docbook/transaction.xml b/src/reference/docbook/transaction.xml index e04ef281cd2..41573097195 100644 --- a/src/reference/docbook/transaction.xml +++ b/src/reference/docbook/transaction.xml @@ -689,7 +689,7 @@ would be rolled back, not necessarily following the EJB rules--> It is not sufficient to tell you simply to annotate your classes with the @Transactional annotation, add - the line (<tx:annotation-driven/>) to your + @EnableTransactionManagement to your configuration, and then expect you to understand how it all works. This section explains the inner workings of the Spring Framework's declarative transaction infrastructure in the event of @@ -1396,6 +1396,14 @@ public class DefaultFooService implements FooService { explicitly, as in the preceding example. + + The @EnableTransactionManagement + annotation provides equivalent support if you are using Java based + configuration. Simply add the annotation to a + @Configuration class. See Javadoc + for full details. + + Method visibility and <interfacename>@Transactional</interfacename> @@ -1460,13 +1468,14 @@ public class DefaultFooService implements FooService { behavior on any kind of method.
- <literal><tx:annotation-driven/></literal> - settings + Annotation driven transaction settings - + - Attribute + XML Attribute + + Annotation Attribute Default @@ -1478,6 +1487,10 @@ public class DefaultFooService implements FooService { transaction-manager + N/A (See + TransactionManagementConfigurer + Javadoc) + transactionManager Name of transaction manager to use. Only required @@ -1489,6 +1502,8 @@ public class DefaultFooService implements FooService { mode + mode + proxy The default mode "proxy" processes annotated @@ -1507,6 +1522,8 @@ public class DefaultFooService implements FooService { proxy-target-class + proxyTargetClass + false Applies to proxy mode only. Controls what type of @@ -1524,6 +1541,8 @@ public class DefaultFooService implements FooService { order + order + Ordered.LOWEST_PRECEDENCE Defines the order of the transaction advice that @@ -1539,11 +1558,10 @@ public class DefaultFooService implements FooService {
- The proxy-target-class attribute on the - <tx:annotation-driven/> element controls what + The proxy-target-class attribute controls what type of transactional proxies are created for classes annotated with the @Transactional annotation. If - proxy-target-class attribute is set to + proxy-target-class is set to true, class-based proxies are created. If proxy-target-class is false or if the attribute is omitted, standard JDK interface-based proxies are @@ -1552,20 +1570,20 @@ public class DefaultFooService implements FooService { - <tx:annotation-driven/> only looks for + @EnableTransactionManagement and + <tx:annotation-driven/> only looks for @Transactional on beans in the same - application context it is defined in. This means that, if you put - <tx:annotation-driven/> in a + application context they are defined in. This means that, if you put + annotation driven configuration in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your - controllers, and not your services. See for more information. The most derived location takes precedence when evaluating the - transactional settings for a method. In + transactional settings for a method. In the case of the following example, the DefaultFooService class is annotated at the class level with the settings for a read-only transaction, but the