Generated by
JDiff

org.springframework.context.annotation Documentation Differences

This file contains all the changes in documentation in the package org.springframework.context.annotation as colored differences. Deletions are shown like this, and additions are shown like this.
If no deletions or additions are shown in an entry, the HTML tags will be what has changed. The new HTML tags are shown in the differences. If no documentation existed, and then some was added in a later version, this change is noted in the appropriate class pages of differences, but the change is not shown on this page. Only changes in existing text are shown here. Similarly, documentation which was inherited from another class or interface is not shown here.
Note that an HTML error in the new documentation may cause the display of other documentation changes to be presented incorrectly. For instance, failure to close a <code> tag will cause all subsequent paragraphs to be displayed differently.

Class Bean

Indicates that a method produces a bean to be managed by the Spring container.

Overview

The

The names and semantics of the attributes to this annotation are intentionally similar intentionally similar to those of the {@code } element in the Spring XML schema. ForFor example:

     @Bean
     public MyBean myBean() {
         // instantiate and configure MyBean obj
         return obj;
     }

Bean Names

While a .name() attribute is available, the default strategy for determining for determining the name of a bean is to use the name of the {@code @Bean} method. This is convenient and and intuitive, but if explicit naming is desired, thethe {@code name()} attribute may be used. Also note that {@code name()} accepts an arrayarray of Strings. This is in order to allow allow for specifying multiple names (i.e., aliases) for a single bean.

     @Bean(name={"b1","b2"}) // bean available as 'b1' and 'b2', but not 'myBean'
     public MyBean myBean() {
         // instantiate and configure MyBean obj
         return obj;
     }

Scope, DependsOn, Primary, and Lazy

Note that the {@code @Bean} annotation does not provide attributes for scope, depends-on, primary, or lazy. Rather, it should be used in conjunction withwith @Scope, @DependsOn, @Primary, and @Lazy annotations to achieve achieve those semantics. For example:

     @Bean
     @Scope("prototype")
     public MyBean myBean() {
         // instantiate and configure MyBean obj
         return obj;
     }

{@code @Bean} Methods in {@code @Configuration} Classes

Typically, {@code @Bean} methods are declared within {@code @Configuration} classes. In this case, bean methods may reference other {@code @Bean} methods onin the same class by calling them directly. This ensures that references between beans are strongly typed and navigable. Such so-called 'inter-bean references' are guaranteed to respect scoping and AOP semantics, just like getBean() lookups would. These are the semantics known from the original 'Spring JavaConfig' project which require CGLIB subclassing of each such configuration class at runtime. As a consequence, {@code @Configuration} classes and their factory methods must not be marked as final or private in this mode. For example:

 @Configuration
 public class AppConfig {
     @Bean
     public FooService fooService() {
         return new FooService(fooRepository());
     }
     @Bean
     public FooRepository fooRepository() {
         return new JdbcFooRepository(dataSource());
     }
     // ...
 }

{@code @Bean} Lite Mode

{@code @Bean} methods may also be declared wihtinwithin classes anythat are not annotated with {@code @Configuration}. For example, bean methods may be declared in a {@code @Component} class or even in a plain old class. In such cases, in a which{@code case@Bean} theymethod will get processed in a configuration classso-called 'lite' mode.

Bean methods in which lite theymode will simply be calledtreated as plain factoryfactory methods fromby the container (similar to to {@code factory-method} declarationsdeclarations in XML), with scoping and lifecycle callbacks properly applied. The containing componentcontaining classes remain class remains unmodified in this case, and there are no unusual constraints forfor the containing class or the factory methods.

In contrast to the semantics for bean methods in {@code @Configuration} classes, however'inter-bean references' are not supported in lite mode. Instead, scoping semanticswhen one are{@code @Bean}-method invokes another {@code @Bean}-method in lite mode, the invocation is a standard Java method invocation; Spring does not respected as described aboveintercept the invocation via fora CGLIB proxy. This is analogous to inter-bean{@code @Transactional} method method invocationscalls where in thisproxy mode, Spring does not intercept the invocation — Spring does so only in AspectJ mode.

For example:

 @Component
 public class Calculator {
     public int sum(int a, int b) {
         return a+b;
     }

     @Bean
     public MyBean myBean() {
         return new MyBean();
     }
 }

Bootstrapping

See @Configuration Javadoc for further details including how to bootstrap the container using AnnotationConfigApplicationContext and friends.

A note on {@code BeanFactoryPostProcessor}-returning {@code @Bean} methods

Special consideration must be taken for {@code @Bean} methods that return Spring BeanFactoryPostProcessor ({@code BFPP}) types. Because {@code BFPP} objects must be instantiated very early in the container lifecycle, they can interfere with processing of annotations such as {@code @Autowired}, {@code @Value}, and {@code @PostConstruct} within {@code @Configuration} classes. To avoid these lifecycle issues, mark {@code BFPP}-returning {@code @Bean} methods as {@code static}. For example:

     @Bean
     public static PropertyPlaceholderConfigurer ppc() {
         // instantiate, configure and return ppc ...
     }
By marking this method as {@code static}, it can be invoked without causing instantiation of its declaring {@code @Configuration} class, thus avoiding the above-mentioned lifecycle conflicts. Note however that {@code static} {@code @Bean} methods will not be enhanced for scoping and AOP semantics as mentioned above. This works out in {@code BFPP} cases, as they are not typically referenced by other {@code @Bean} methods. As a reminder, a WARN-level log message will be issued for any non-static {@code @Bean} methods having a return type assignable to {@code BeanFactoryPostProcessor}. @author Rod Johnson @author Costin Leau @author Chris Beams @author Juergen Hoeller @author Sam Brannen @since 3.0 @see Configuration @see Scope @see DependsOn @see Lazy @see Primary @see org.springframework.stereotype.Component @see org.springframework.beans.factory.annotation.Autowired @see org.springframework.beans.factory.annotation.Value

Class ComponentScan

Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's {@code } element.

One of .basePackageClasses(), .basePackages() or its alias .value() mustmay be specified to define specific packages to scan. If specific packages are not defined scanning will occur from the package of the class with this annotation.

Note that the {@code } element has an {@code annotation-config} attribute, however this annotation does not. This is because in almost all cases when using {@code @ComponentScan}, default annotation config processing (e.g. processing {@code @Autowired} and friends) is assumed. Furthermore, when using AnnotationConfigApplicationContext, annotation config processors are always registered, meaning that any attempt to disable them at the {@code @ComponentScan} level would be ignored.

See @Configuration Javadoc for usage examples. @author Chris Beams @since 3.1 @see Configuration


Class ComponentScan.Filter

Declares the type filter to be used as an ComponentScan#includeFilters() include filter or ComponentScan#includeFiltersexcludeFilters() exclude filter.

Class Configuration

Indicates that a class declares one or more @@Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:
 @Configuration
 public class AppConfig {
     @Bean
     public MyBean myBean() {
         // instantiate, configure and return bean ...
     }
 }

Bootstrapping {@code @Configuration} classes

Via {@code AnnotationConfigApplicationContext}

{@code @Configuration} classes are typically bootstrapped using either AnnotationConfigApplicationContext or its web-capable variant, AnnotationConfigWebApplicationContext. A simple example with the former follows:
 AnnotationConfigApplicationContext ctx =
     new AnnotationConfigApplicationContext();
 ctx.register(AppConfig.class);
 ctx.refresh();
 MyBean myBean = ctx.getBean(MyBean.class);
 // use myBean ...
See AnnotationConfigApplicationContext Javadoc for further details and see AnnotationConfigWebApplicationContext for {@code web.xml} configuration instructions.

Via Spring {@code } XML

As an alternative to registering {@code @Configuration} classes directly against an {@code AnnotationConfigApplicationContext}, {@code @Configuration} classes may be declared as normal {@code } definitions within Spring XML files:

 {@code
 
    
    
 
 }
In the example above, {@code } is required in order to enable ConfigurationClassPostProcessor and other annotation-related post processors that facilitate handling {@code @Configuration} classes.

Via component scanning

{@code @Configuration} is meta-annotated with @@Component, therefore {@code @Configuration} classes are candidates for component scanning (typically using Spring XML's {@code } element) and therefore may also take advantage of @@Autowired/@@Inject at the field and method level (but not not at the constructor level).

{@code @Configuration} classes may not only be bootstrapped using component scanning, but may also themselves configure component scanning using the @@ComponentScan annotation:

 @Configuration
 @ComponentScan("com.acme.app.services")
 public class AppConfig {
     // various @Bean definitions ...
 }
See @@ComponentScan Javadoc for details.

Working with externalized values

Using the {@code Environment} API

Externalized values may be looked up by injecting the Spring Environment into a {@code @Configuration} class using the {@code @Autowired} or the {@code @Inject} annotation:
 @Configuration
 public class AppConfig {
     @Inject Environment env;

     @Bean
     public MyBean myBean() {
         MyBean myBean = new MyBean();
         myBean.setName(env.getProperty("bean.name"));
         return myBean;
     }
 }
Properties resolved through the {@code Environment} reside in one or more "property source" objects, and {@code @Configuration} classes may contribute property sources to the {@code Environment} object usingusing the @@PropertySources annotation:
 @Configuration
 @PropertySource("classpath:/com/acme/app.properties")
 public class AppConfig {
     @Inject Environment env;

     @Bean
     public MyBean myBean() {
         return new MyBean(env.getProperty("bean.name"));
     }
 }
See Environment and @@PropertySource Javadoc for further details.

Using the {@code @Value} annotation

Externalized values may be 'wired into' {@code @Configuration} classes using the @@Value annotation:
 @Configuration
 @PropertySource("classpath:/com/acme/app.properties")
 public class AppConfig {
     @Value("${bean.name}") String beanName;

     @Bean
     public MyBean myBean() {
         return new MyBean(beanName);
     }
 }
This approach is most useful when using Spring's PropertySourcesPlaceholderConfigurer, usually enabled via XML with {@code }. See the section below on composing {@code @Configuration} classes with Spring XML using {@code @ImportResource}, see @@Value Javadoc, and see @@Bean Javadoc for details on working with {@code BeanFactoryPostProcessor} types such as {@code PropertySourcesPlaceholderConfigurer}.

Composing {@code @Configuration} classes

With the {@code @Import} annotation

{@code @Configuration} classes may be composed using the @@Import annotation, not unlike the way that {@code } works in Spring XML. Because {@code @Configuration} objects are managed as Spring beans within the container, imported configurations may be injected using {@code @Autowired} or {@code @Inject}:

 @Configuration
 public class DatabaseConfig {
     @Bean
     public DataSource dataSource() {
         // instantiate, configure and return DataSource
     }
 }

 @Configuration
 @Import(DatabaseConfig.class)
 public class AppConfig {
     @Inject DatabaseConfig dataConfig;

     @Bean
     public MyBean myBean() {
         // reference the dataSource() bean method
         return new MyBean(dataConfig.dataSource());
     }
 }
Now both {@code AppConfig} and the imported {@code DatabaseConfig} can be bootstrapped by registering only {@code AppConfig} against the Spring context:
 new AnnotationConfigApplicationContext(AppConfig.class);

With the {@code @Profile} annotation

{@code @Configuration} classes may be marked with the @@Profile annotation to to indicate they should be processed only if a given profile or profiles are active:
 @Profile("embedded")
 @Configuration
 public class EmbeddedDatabaseConfig {
     @Bean
     public DataSource dataSource() {
         // instantiate, configure and return embedded DataSource
     }
 }

 @Profile("production")
 @Configuration
 public class ProductionDatabaseConfig {
     @Bean
     public DataSource dataSource() {
         // instantiate, configure and return production DataSource
     }
 }
See @@Profile and Environment Javadoc for further details.

With Spring XML using the {@code @ImportResource} annotation

As mentioned above, {@code @Configuration} classes may be declared as regular Spring {@code } definitions within Spring XML files. It is also possible to import Spring XML configuration files into {@code @Configuration} classes using the @@ImportResource annotation. Bean definitions imported from XML can be injected using {@code @Autowired} or {@code @Import}:
 @Configuration
 @ImportResource("classpath:/com/acme/database-config.xml")
 public class AppConfig {
     @Inject DataSource dataSource; // from XML

     @Bean
     public MyBean myBean() {
         // inject the XML-defined dataSource bean
         return new MyBean(this.dataSource);
     }
 }

With nested {@code @Configuration} classes

{@code @Configuration} classes may be nested within one another as follows:
 @Configuration
 public class AppConfig {
     @Inject DataSource dataSource;

     @Bean
     public MyBean myBean() {
         return new MyBean(dataSource);
     }

     @Configuration
     static class DatabaseConfig {
         @Bean
         DataSource dataSource() {
             return new EmbeddedDatabaseBuilder().build();
         }
     }
 }
When bootstrapping such an arrangement, only {@code AppConfig} need be registered against the application context. By virtue of being a nested {@code @Configuration} class, {@code DatabaseConfig} will be registered automatically. This avoids the need to use an {@code @Import} annotation when the relationship between {@code AppConfig} {@code DatabaseConfig} is already implicitly clear.

Note also that nested {@code @Configuration} classes can be used to good effect with the {@code @Profile} annotation to provide two options of the same bean to the enclosing {@code @Configuration} class.

Configuring lazy initialization

By default, {@code @Bean} methods will be eagerly instantiated at container bootstrap time. To avoid this, {@code @Configuration} may be used in conjunction with the @@Lazy annotation to indicate that all {@code @Bean} methods declared within the class are by default lazily initialized. Note that {@code @Lazy} may be used on individual {@code @Bean} methods as well.

Testing support for {@code @Configuration} classes

The Spring TestContext framework available in the {@code spring-test} module provides the {@code @ContextConfiguration} annotation, which as of Spring 3.1 can accept an array of {@code @Configuration} {@code Class} objects:
 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(classes={AppConfig.class, DatabaseConfig.class})
 public class MyTests {

     @Autowired MyBean myBean;

     @Autowired DataSource dataSource;

     @Test
     public void test() {
         // assertions against myBean ...
     }
 }
See TestContext framework reference documentation for details.

Enabling built-in Spring features using {@code @Enable} annotations

Spring features such as asynchronous method execution, scheduled task execution, annotation driven transaction management, and even Spring MVC can be enabled and configured from {@code @Configuration} classes using their respective "{@code @Enable}" annotations. See @EnableAsync, @EnableScheduling, @EnableTransactionManagement, @EnableAspectJAutoProxy, and @EnableWebMvc for details.

Constraints when authoring {@code @Configuration} classes

  • @Configuration classes must be non-final
  • @Configuration classes must be non-local (may not be declared within a method)
  • @Configuration classes must have a default/no-arg constructor and may not use @@Autowired constructor parameters. Any nested configuration classes must be {@code static}
@author Rod Johnson @author Chris Beams @since 3.0 @see Bean @see Profile @see Import @see ImportResource @see ComponentScan @see Lazy @see PropertySource @see AnnotationConfigApplicationContext @see ConfigurationClassPostProcessor @see org.springframework.core.env.Environment @see org.springframework.test.context.ContextConfiguration

Class DependsOn

Beans on which the current bean depends. Any beans specified are guaranteed to be created by the container before this bean. Used infrequently in cases where a bean does not explicitly depend on another through properties or constructor arguments, but rather depends on the side effects of another bean's initialization. Note: This attribute will not be inherited by child bean definitions, hence it needs to be specified per concrete bean definition.

May be used on any class directly or indirectly annotated with org.springframework.stereotype.Component or on methods annotated with Bean.

Using DependsOn at the class level has no effect unless component-scanning is being used. If a DependsOn-annotated class is declared via XML, DependsOn annotation metadata is ignored, and {@code } is respected instead. @author Juergen Hoeller @since 3.0


Class EnableLoadTimeWeaving

Activates a Spring LoadTimeWeaver for this application context, available as a bean with the name "loadTimeWeaver", similar to the {@code } element in Spring XML. To be used on @Configuration classes; the simplest possible example of which follows:
 @Configuration
 @EnableLoadTimeWeaving
 public class AppConfig {
     // application-specific @Bean definitions ...
 }
The example above is equivalent to the following Spring XML configuration:
 {@code
 
     
     <-- application-specific  definitions -->
 
 }

The {@code LoadTimeWeaverAware} interface

Any bean that implements the LoadTimeWeaverAware interface will then receive the {@code LoadTimeWeaver} reference automatically; for example, Spring's JPA bootstrap support.

Customizing the {@code LoadTimeWeaver}

The default weaver is determined automatically. As of Spring 3.1: detecting Sun's GlassFish, Oracle's OC4J, Spring's VM agent and any ClassLoader supported by Spring's ReflectiveLoadTimeWeaver (for example, the TomcatInstrumentableClassLoader).

To customize the weaver used, the {@code @Configuration} class annotated with {@code @EnableLoadTimeWeaving} may also implement the LoadTimeWeaverConfigurerLoadTimeWeavingConfigurer interface and return a custom {@code LoadTimeWeaver} instance through the {@code #getLoadTimeWeaver} method:

 @Configuration
 @EnableLoadTimeWeaving
 public class AppConfig implements LoadTimeWeaverConfigurerLoadTimeWeavingConfigurer {
     @Override
     public LoadTimeWeaver getLoadTimeWeaver() {
         MyLoadTimeWeaver ltw = new MyLoadTimeWeaver();
         ltw.addClassTransformer(myClassFileTransformer);
         // ...
         return ltw;
     }
 }

The example above can be compared to the following Spring XML configuration:

 {@code
 
     
 
 }

The code example differs from the XML example in that it actually instantiates the {@code MyLoadTimeWeaver} type, meaning that it can also configure the instance, e.g. calling the {@code #addClassTransformer} method. This demonstrates how the code-based configuration approach is more flexible through direct programmatic access.

Enabling AspectJ-based weaving

AspectJ load-time weaving may be enabled with the .aspectjWeaving() attribute, which will cause the org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter AspectJ class transformer to be registered through LoadTimeWeaver.addTransformer. AspectJ weaving will be activated by default if a "META-INF/aop.xml" resource is present on the classpath. Example:
 @Configuration
 @EnableLoadTimeWeaving(aspectjWeaving=ENABLED)
 public class AppConfig {
 }

The example above can be compared to the following Spring XML configuration:

 {@code
 
     
 
 }

The two examples are equivalent with one significant exception: in the XML case, the functionality of {@code } is implicitly enabled when {@code aspectj-weaving} is "on". This does not occur when using {@code @EnableLoadTimeWeaving(aspectjWeaving=ENABLED)}. Instead you must explicitly add {@code @EnableSpringConfigured} (included in the {@code spring-aspects} module) @author Chris Beams @since 3.1 @see LoadTimeWeaver @see DefaultContextLoadTimeWeaver @see org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter


Class FilterType

Enumeration of the type filters that may be used in conjunction with @ComponentScan. @author Mark Fisher @author Juergen Hoeller @author Chris Beams @since 2.5 @see ComponentScan @see ComponentScan.IncludeFilter #includeFilters() @see ComponentScan.ExcludeFilter #excludeFilters() @see org.springframework.core.type.filter.TypeFilter

Class Import

Indicates one or more @@Configuration classes to import.

Provides functionality equivalent to the {@code } element in Spring XML. Only supported for classes annotated with {@code @Configuration} or declaring at least one @Bean method, as well as ImportSelector and ImportBeanDefinitionRegistrar implementations.

@{@code @Bean} definitions declared in imported {@code @Configuration} classes should be accessed by using @@Autowired injection. Either the bean itself can can be autowired, or the configuration class instanceinstance declaring the bean can be autowired. The latter approach allows for explicit, IDE-friendly navigation between between {@code @Configuration} class methods.

May be declared at the class level or as a meta-annotation.

If XML or other non-{@code @Configuration} bean definition resources need to be imported, use @@ImportResource @author Chris Beams @since 3.0 @see Configuration @see ImportSelector @see ImportResource


Class ImportBeanDefinitionRegistrar

Interface to be implemented by types that register additional bean definitions when processing @Configuration classes. Useful when operating at the bean definition level (as opposed to {@code @Bean} method/instance level) is desired or necessary.

Along with {@code @Configuration} and ImportSelector, classes of this type may be provided to the @Import annotation (or may also be returned from an {@code ImportSelector}).

An ImportBeanDefinitionRegistrar may implement any of the following Aware interfaces, and their respective methods will be called prior to .registerBeanDefinitions:

See implementations and associated unit tests for usage examples. @author Chris Beams @since 3.1 @see Import @see ImportSelector @see Configuration


Class LoadTimeWeavingConfigurer

Interface to be implemented byby @ @Configuration classes annotated with @@EnableLoadTimeWeaving that wish to customize the LoadTimeWeaver instance to be used.

See @@EnableAsync for usage examples and information on how a default default {@code LoadTimeWeaver} is selected when this interface is not used. @author Chris Beams @since 3.1 @see LoadTimeWeavingConfiguration @see EnableLoadTimeWeaving


Class Profile

Indicates that a component is eligible for registration when one or more #value value specified profiles are active.

A profile is a named logical grouping that may be activatedactivated programatically via programmatically via ConfigurableEnvironment.setActiveProfiles or declarativelydeclaratively through setting the the spring.profiles.active property, usually through JVM system properties, as anan environment variable, or for web applications applications as a Servlet context parameter inin {@code web.xml}.

The {@code @Profile} annotation may be used in any of the following ways:

If a {@code @Configuration} class is marked with {@code @Profile}, all of the {@code @Bean} methods and @Import annotations associated with that class will class will be bypassed unless one or more the specified profiles are active. This is veryvery similar to to the behavior in Spring XML: if the {@code profile} attribute of thethe {@code beans} element is is supplied e.g., {@code }, thethe {@code beans} element will not be parsed unless unless profiles 'p1' and/or 'p2' have beenbeen activated. Likewise, if a {@code @Component} or or {@code @Configuration} class is markedmarked with {@code @Profile({"p1", "p2"})}, that class will will not be registered/processed unlessunless profiles 'p1' and/or 'p2' have been activated.

If a given profile is prefixed with the NOT operator ({@code !}), the annotated will be registered if the profile is not active. e.g., for {@code @Profile({"p1", "!p2"})}, registration will occur if profile 'p1' is active or if profile 'p2' is not active.

If the {@code @Profile} annotation is omitted, registration will occur, regardlessregardless of which, (if any,) profiles are active.

When defining Spring beans via XML, the {@code "profile"} attribute of thethe {@code } element may be used. See the documentation inin {@code spring-beans-} XSD (version 3.1.xsd} or greater) for details. @author Chris Beams @since 3.1 @see ConfigurableEnvironment#setActiveProfiles @see ConfigurableEnvironment#setDefaultProfiles @see AbstractEnvironment#ACTIVE_PROFILES_PROPERTY_NAME @see AbstractEnvironment#DEFAULT_PROFILES_PROPERTY_NAME