Browse Source

Document common use cases for @Order vs @Priority vs @DependsOn

Issue: SPR-16213
pull/1601/merge
Juergen Hoeller 8 years ago
parent
commit
84699c8b9b
  1. 43
      spring-beans/src/main/java/org/springframework/beans/factory/annotation/Autowired.java
  2. 40
      spring-context/src/main/java/org/springframework/context/annotation/Bean.java
  3. 34
      spring-core/src/main/java/org/springframework/core/annotation/Order.java
  4. 24
      src/docs/asciidoc/core/core-beans.adoc

43
spring-beans/src/main/java/org/springframework/beans/factory/annotation/Autowired.java

@ -23,31 +23,34 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
/** /**
* Marks a constructor, field, setter method or config method as to be * Marks a constructor, field, setter method or config method as to be autowired
* autowired by Spring's dependency injection facilities. * by Spring's dependency injection facilities.
* *
* <p>Only one constructor (at max) of any given bean class may carry this * <p>Only one constructor (at max) of any given bean class may carry this annotation,
* annotation, indicating the constructor to autowire when used as a Spring * indicating the constructor to autowire when used as a Spring bean. Such a
* bean. Such a constructor does not have to be public. * constructor does not have to be public.
* *
* <p>Fields are injected right after construction of a bean, before any * <p>Fields are injected right after construction of a bean, before any config
* config methods are invoked. Such a config field does not have to be public. * methods are invoked. Such a config field does not have to be public.
* *
* <p>Config methods may have an arbitrary name and any number of arguments; * <p>Config methods may have an arbitrary name and any number of arguments; each of
* each of those arguments will be autowired with a matching bean in the * those arguments will be autowired with a matching bean in the Spring container.
* Spring container. Bean property setter methods are effectively just * Bean property setter methods are effectively just a special case of such a general
* a special case of such a general config method. Such config methods * config method. Such config methods do not have to be public.
* do not have to be public.
* *
* <p>In the case of multiple argument methods, the 'required' parameter is * <p>In the case of a multi-arg constructor or method, the 'required' parameter is
* applicable for all arguments. * applicable to all arguments. Individual parameters may be declared as Java-8-style
* {@link java.util.Optional} or, as of Spring Framework 5.0, also as {@code @Nullable}
* or a not-null parameter type in Kotlin, overriding the base required semantics.
* *
* <p>In case of a {@link java.util.Collection} or {@link java.util.Map} * <p>In case of a {@link java.util.Collection} or {@link java.util.Map} dependency type,
* dependency type, the container can autowire all beans matching the * the container autowires all beans matching the declared value type. For such purposes,
* declared value type. For such purposes, the map keys must be declared * the map keys must be declared as type String which will be resolved to the corresponding
* as type String and will be resolved to the corresponding bean names. * bean names. Such a container-provided collection will be ordered, taking into account
* Alternatively, a target bean may also be of type {@code Collection} or * {@link org.springframework.core.Ordered}/{@link org.springframework.core.annotation.Order}
* {@code Map} itself, getting injected as such. * values of the target components, otherwise following their registration order in the
* container. Alternatively, a single matching target bean may also be a generally typed
* {@code Collection} or {@code Map} itself, getting injected as such.
* *
* <p>Note that actual injection is performed through a * <p>Note that actual injection is performed through a
* {@link org.springframework.beans.factory.config.BeanPostProcessor * {@link org.springframework.beans.factory.config.BeanPostProcessor

40
spring-context/src/main/java/org/springframework/context/annotation/Bean.java

@ -60,15 +60,16 @@ import org.springframework.core.annotation.AliasFor;
* } * }
* </pre> * </pre>
* *
* <h3>Scope, DependsOn, Primary, and Lazy</h3> * <h3>Profile, Scope, Lazy, DependsOn, Primary, Order</h3>
* *
* <p>Note that the {@code @Bean} annotation does not provide attributes for scope, * <p>Note that the {@code @Bean} annotation does not provide attributes for profile,
* depends-on, primary, or lazy. Rather, it should be used in conjunction with * scope, lazy, depends-on or primary. Rather, it should be used in conjunction with
* {@link Scope @Scope}, {@link DependsOn @DependsOn}, {@link Primary @Primary}, * {@link Scope @Scope}, {@link Lazy @Lazy}, {@link DependsOn @DependsOn} and
* and {@link Lazy @Lazy} annotations to achieve those semantics. For example: * {@link Primary @Primary} annotations to declare those semantics. For example:
* *
* <pre class="code"> * <pre class="code">
* &#064;Bean * &#064;Bean
* &#064;Profile("production")
* &#064;Scope("prototype") * &#064;Scope("prototype")
* public MyBean myBean() { * public MyBean myBean() {
* // instantiate and configure MyBean obj * // instantiate and configure MyBean obj
@ -76,6 +77,33 @@ import org.springframework.core.annotation.AliasFor;
* } * }
* </pre> * </pre>
* *
* The semantics of the above-mentioned annotations match their use at the component
* class level: {@code Profile} allows for selective inclusion of certain beans.
* {@code @Scope} changes the bean's scope from singleton to the specified scope.
* {@code @Lazy} only has an actual effect in case of the default singleton scope.
* {@code @DependsOn} enforces the creation of specific other beans before this
* bean will be created, in addition to any dependencies that the bean expressed
* through direct references, which is typically helpful for singleton startup.
* {@code @Primary} is a mechanism to resolve ambiguity at the injection point level
* if a single target component needs to be injected but several beans match by type.
*
* <p>Additionally, {@code @Bean} methods may also declare qualifier annotations
* and {@link org.springframework.core.annotation.Order @Order} values, to be
* taken into account during injection point resolution just like corresponding
* annotations on the corresponding component classes but potentially being very
* individual per bean definition (in case of multiple definitions with the same
* bean class). Qualifiers narrow the set of candidates after the initial type match;
* order values determine the order of resolved elements in case of collection
* injection points (with several target beans matching by type and qualifier).
*
* <p><b>NOTE:</b> {@code @Order} values may influence priorities at injection points
* but please be aware that they do not influence singleton startup order which is an
* orthogonal concern determined by dependency relationships and {@code @DependsOn}
* declarations as mentioned above. Also, {@link javax.annotation.Priority} is not
* available at this level since it cannot be declared on methods; its semantics can
* be modelled through {@code @Order} values in combination with {@code @Primary} on
* a single bean per type.
*
* <h3>{@code @Bean} Methods in {@code @Configuration} Classes</h3> * <h3>{@code @Bean} Methods in {@code @Configuration} Classes</h3>
* *
* <p>Typically, {@code @Bean} methods are declared within {@code @Configuration} * <p>Typically, {@code @Bean} methods are declared within {@code @Configuration}
@ -143,7 +171,7 @@ import org.springframework.core.annotation.AliasFor;
* *
* <h3>Bootstrapping</h3> * <h3>Bootstrapping</h3>
* *
* <p>See @{@link Configuration} Javadoc for further details including how to bootstrap * <p>See the @{@link Configuration} javadoc for further details including how to bootstrap
* the container using {@link AnnotationConfigApplicationContext} and friends. * the container using {@link AnnotationConfigApplicationContext} and friends.
* *
* <h3>{@code BeanFactoryPostProcessor}-returning {@code @Bean} methods</h3> * <h3>{@code BeanFactoryPostProcessor}-returning {@code @Bean} methods</h3>

34
spring-core/src/main/java/org/springframework/core/annotation/Order.java

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -27,21 +27,29 @@ import org.springframework.core.Ordered;
/** /**
* {@code @Order} defines the sort order for an annotated component. * {@code @Order} defines the sort order for an annotated component.
* *
* <p>The {@link #value} is optional and represents an order value as defined * <p>The {@link #value} is optional and represents an order value as defined in the
* in the {@link Ordered} interface. Lower values have higher priority. The * {@link Ordered} interface. Lower values have higher priority. The default value is
* default value is {@code Ordered.LOWEST_PRECEDENCE}, indicating * {@code Ordered.LOWEST_PRECEDENCE}, indicating lowest priority (losing to any other
* lowest priority (losing to any other specified order value). * specified order value).
* *
* <p>Since Spring 4.1, the standard {@link javax.annotation.Priority} * <p><b>NOTE:</b> Since Spring 4.0, annotation-based ordering is supported for many
* annotation can be used as a drop-in replacement for this annotation. * kinds of components in Spring, even for collection injection where the order values
* of the target components are taken into account (either from their target class or
* from their {@code @Bean} method). While such order values may influence priorities
* at injection points, please be aware that they do not influence singleton startup
* order which is an orthogonal concern determined by dependency relationships and
* {@code @DependsOn} declarations (influencing a runtime-determined dependency graph).
* *
* <p><b>NOTE</b>: Annotation-based ordering is supported for specific kinds * <p>Since Spring 4.1, the standard {@link javax.annotation.Priority} annotation
* of components only &mdash; for example, for annotation-based AspectJ * can be used as a drop-in replacement for this annotation in ordering scenarios.
* aspects. Ordering strategies within the Spring container, on the other * Note that {@code Priority} may have additional semantics when a single element
* hand, are typically based on the {@link Ordered} interface in order to * has to be picked (see {@link AnnotationAwareOrderComparator#getPriority}).
* allow for programmatically configurable ordering of each <i>instance</i>.
* *
* <p>Consult the Javadoc for {@link org.springframework.core.OrderComparator * <p>Alternatively, order values may also be determined on a per-instance basis
* through the {@link Ordered} interface, allowing for configuration-determined
* instance values instead of hard-coded values attached to a particular class.
*
* <p>Consult the javadoc for {@link org.springframework.core.OrderComparator
* OrderComparator} for details on the sort semantics for non-ordered objects. * OrderComparator} for details on the sort semantics for non-ordered objects.
* *
* @author Rod Johnson * @author Rod Johnson

24
src/docs/asciidoc/core/core-beans.adoc

@ -4437,9 +4437,20 @@ The same applies for typed collections:
[TIP] [TIP]
==== ====
Your beans can implement the `org.springframework.core.Ordered` interface or either use Your target beans can implement the `org.springframework.core.Ordered` interface or use
the `@Order` or standard `@Priority` annotation if you want items in the array or list the `@Order` or standard `@Priority` annotation if you want items in the array or list
to be sorted into a specific order. to be sorted into a specific order. Otherwise their order will follow the registration
order of the corresponding target bean definitions in the container.
The `@Order` annotation may be declared at target class level but also on `@Bean` methods,
potentially being very individual per bean definition (in case of multiple definitions
with the same bean class). `@Order` values may influence priorities at injection points
but please be aware that they do not influence singleton startup order which is an
orthogonal concern determined by dependency relationships and `@DependsOn` declarations.
Note that the standard `javax.annotation.Priority` annotation is not available at the
`@Bean` level since it cannot be declared on methods. Its semantics can be modelled
through `@Order` values in combination with `@Primary` on a single bean per type.
==== ====
Even typed Maps can be autowired as long as the expected key type is `String`. The Map Even typed Maps can be autowired as long as the expected key type is `String`. The Map
@ -7004,7 +7015,6 @@ another configuration class:
public A a() { public A a() {
return new A(); return new A();
} }
} }
@Configuration @Configuration
@ -7267,6 +7277,14 @@ way, navigating `@Configuration` classes and their dependencies becomes no diffe
than the usual process of navigating interface-based code. than the usual process of navigating interface-based code.
-- --
[TIP]
====
If you would like to influence the startup creation order of certain beans, consider
declaring some of them as `@Lazy` (for creation on first access instead of on startup)
or as `@DependsOn` on certain other beans (making sure that specific other beans will
be created before the current bean, beyond what the latter's direct dependencies imply).
====
[[beans-java-conditional]] [[beans-java-conditional]]
==== Conditionally include @Configuration classes or @Bean methods ==== Conditionally include @Configuration classes or @Bean methods

Loading…
Cancel
Save