spring-framework / org.springframework.context.annotation

Package org.springframework.context.annotation

Types

AdviceModeImportSelector

abstract class AdviceModeImportSelector<A : Annotation> : ImportSelector

Convenient base class for ImportSelector implementations that select imports based on an AdviceMode value from an annotation (such as the @Enable* annotations).

AnnotatedBeanDefinitionReader

open class AnnotatedBeanDefinitionReader

Convenient adapter for programmatic registration of annotated bean classes. This is an alternative to ClassPathBeanDefinitionScanner, applying the same resolution of annotations but for explicitly registered classes only.

AnnotationBeanNameGenerator

open class AnnotationBeanNameGenerator : BeanNameGenerator

org.springframework.beans.factory.support.BeanNameGenerator implementation for bean classes annotated with the org.springframework.stereotype.Component annotation or with another annotation that is itself annotated with org.springframework.stereotype.Component as a meta-annotation. For example, Spring's stereotype annotations (such as org.springframework.stereotype.Repository) are themselves annotated with org.springframework.stereotype.Component.

Also supports Java EE 6's javax.annotation.ManagedBean and JSR-330's javax.inject.Named annotations, if available. Note that Spring component annotations always override such standard annotations.

If the annotation's value doesn't indicate a bean name, an appropriate name will be built based on the short name of the class (with the first letter lower-cased). For example:

com.xyz.FooServiceImpl -> fooServiceImpl

AnnotationConfigBeanDefinitionParser

open class AnnotationConfigBeanDefinitionParser : BeanDefinitionParser

Parser for the <context:annotation-config/> element.

AnnotationScopeMetadataResolver

open class AnnotationScopeMetadataResolver : ScopeMetadataResolver

A ScopeMetadataResolver implementation that by default checks for the presence of Spring's Scope annotation on the bean class.

The exact type of annotation that is checked for is configurable via #setScopeAnnotationType(Class).

AutoProxyRegistrar

open class AutoProxyRegistrar : ImportBeanDefinitionRegistrar

Registers an auto proxy creator against the current BeanDefinitionRegistry as appropriate based on an @Enable* annotation having mode and proxyTargetClass attributes set to the correct values.

ClassPathBeanDefinitionScanner

open class ClassPathBeanDefinitionScanner : ClassPathScanningCandidateComponentProvider

A bean definition scanner that detects bean candidates on the classpath, registering corresponding bean definitions with a given registry (BeanFactory or ApplicationContext).

Candidate classes are detected through configurable type filters. The default filters include classes that are annotated with Spring's org.springframework.stereotype.Component, org.springframework.stereotype.Repository, org.springframework.stereotype.Service, or org.springframework.stereotype.Controller stereotype.

Also supports Java EE 6's javax.annotation.ManagedBean and JSR-330's javax.inject.Named annotations, if available.

CommonAnnotationBeanPostProcessor

open class CommonAnnotationBeanPostProcessor : InitDestroyAnnotationBeanPostProcessor, InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable

org.springframework.beans.factory.config.BeanPostProcessor implementation that supports common Java annotations out of the box, in particular the JSR-250 annotations in the javax.annotation package. These common Java annotations are supported in many Java EE 5 technologies (e.g. JSF 1.2), as well as in Java 6's JAX-WS.

This post-processor includes support for the javax.annotation.PostConstruct and javax.annotation.PreDestroy annotations - as init annotation and destroy annotation, respectively - through inheriting from InitDestroyAnnotationBeanPostProcessor with pre-configured annotation types.

The central element is the javax.annotation.Resource annotation for annotation-driven injection of named beans, by default from the containing Spring BeanFactory, with only mappedName references resolved in JNDI. The "alwaysUseJndiLookup" flag enforces JNDI lookups equivalent to standard Java EE 5 resource injection for name references and default names as well. The target beans can be simple POJOs, with no special requirements other than the type having to match.

The JAX-WS javax.xml.ws.WebServiceRef annotation is supported too, analogous to javax.annotation.Resource but with the capability of creating specific JAX-WS service endpoints. This may either point to an explicitly defined resource by name or operate on a locally specified JAX-WS service class. Finally, this post-processor also supports the EJB 3 javax.ejb.EJB annotation, analogous to javax.annotation.Resource as well, with the capability to specify both a local bean name and a global JNDI name for fallback retrieval. The target beans can be plain POJOs as well as EJB 3 Session Beans in this case.

The common annotations supported by this post-processor are available in Java 6 (JDK 1.6) as well as in Java EE 5/6 (which provides a standalone jar for its common annotations as well, allowing for use in any Java 5 based application).

For default usage, resolving resource names as Spring bean names, simply define the following in your application context:

 <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
For direct JNDI access, resolving resource names as JNDI resource references within the Java EE application's "java:comp/env/" namespace, use the following:
 <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"> <property name="alwaysUseJndiLookup" value="true"/> </bean>
mappedName references will always be resolved in JNDI, allowing for global JNDI names (including "java:" prefix) as well. The "alwaysUseJndiLookup" flag just affects name references and default names (inferred from the field name / property name).

NOTE: A default CommonAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom CommonAnnotationBeanPostProcessor bean definition!

NOTE: Annotation injection will be performed before XML injection; thus the latter configuration will override the former for properties wired through both approaches.

ComponentScanBeanDefinitionParser

open class ComponentScanBeanDefinitionParser : BeanDefinitionParser

Parser for the <context:component-scan/> element.

ConfigurationClassPostProcessor

open class ConfigurationClassPostProcessor : BeanDefinitionRegistryPostProcessor, PriorityOrdered, ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware

BeanFactoryPostProcessor used for bootstrapping processing of Configuration classes.

Registered by default when using <context:annotation-config/> or <context:component-scan/>. Otherwise, may be declared manually as with any other BeanFactoryPostProcessor.

This post processor is Ordered#HIGHEST_PRECEDENCE as it is important that any Bean methods declared in Configuration classes have their respective bean definitions registered before any other BeanFactoryPostProcessor executes.

ConfigurationCondition

interface ConfigurationCondition : Condition

A Condition that offers more fine-grained control when used with @Configuration. Allows certain Conditions to adapt when they match based on the configuration phase. For example, a condition that checks if a bean has already been registered might choose to only be evaluated during the REGISTER_BEAN ConfigurationPhase.

ContextAnnotationAutowireCandidateResolver

open class ContextAnnotationAutowireCandidateResolver : QualifierAnnotationAutowireCandidateResolver

Complete implementation of the org.springframework.beans.factory.support.AutowireCandidateResolver strategy interface, providing support for qualifier annotations as well as for lazy resolution driven by the Lazy annotation in the context.annotation package.

DeferredImportSelector

interface DeferredImportSelector : ImportSelector

A variation of ImportSelector that runs after all @Configuration beans have been processed. This type of selector can be particularly useful when the selected imports are @Conditional.

Implementations can also extend the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation to indicate a precedence against other DeferredImportSelectors.

FilterType

class FilterType

Enumeration of the type filters that may be used in conjunction with ComponentScan.

Jsr330ScopeMetadataResolver

open class Jsr330ScopeMetadataResolver : ScopeMetadataResolver

Simple ScopeMetadataResolver implementation that follows JSR-330 scoping rules: defaulting to prototype scope unless javax.inject.Singleton is present.

This scope resolver can be used with ClassPathBeanDefinitionScanner and AnnotatedBeanDefinitionReader for standard JSR-330 compliance. However, in practice, you will typically use Spring's rich default scoping instead - or extend this resolver with custom scoping annotations that point to extended Spring scopes.

LoadTimeWeavingConfigurer

interface LoadTimeWeavingConfigurer

Interface to be implemented by org.springframework.context.annotation.Configuration classes annotated with EnableLoadTimeWeaving that wish to customize the LoadTimeWeaver instance to be used.

See org.springframework.scheduling.annotation.EnableAsync for usage examples and information on how a default LoadTimeWeaver is selected when this interface is not used.

MBeanExportConfiguration

open class MBeanExportConfiguration : ImportAware, EnvironmentAware, BeanFactoryAware

@Configuration class that registers a AnnotationMBeanExporter bean.

This configuration class is automatically imported when using the EnableMBeanExport annotation. See its javadoc for complete usage details.

ScannedGenericBeanDefinition

open class ScannedGenericBeanDefinition : GenericBeanDefinition, AnnotatedBeanDefinition

Extension of the org.springframework.beans.factory.support.GenericBeanDefinition class, based on an ASM ClassReader, with support for annotation metadata exposed through the AnnotatedBeanDefinition interface.

This class does not load the bean Class early. It rather retrieves all relevant metadata from the ".class" file itself, parsed with the ASM ClassReader. It is functionally equivalent to AnnotatedGenericBeanDefinition#AnnotatedGenericBeanDefinition(AnnotationMetadata) but distinguishes by type beans that have been scanned vs those that have been otherwise registered or detected by other means.

Annotations

ComponentScans

class ComponentScans

Container annotation that aggregates several ComponentScan annotations.

Can be used natively, declaring several nested ComponentScan annotations. Can also be used in conjunction with Java 8's support for repeatable annotations, where ComponentScan can simply be declared several times on the same method, implicitly generating this container annotation.

Conditional

class Conditional

Indicates that a component is only eligible for registration when all specified conditions match.

A condition is any state that can be determined programmatically before the bean definition is due to be registered (see Condition for details).

The @Conditional annotation may be used in any of the following ways:

  • as a type-level annotation on any class directly or indirectly annotated with @Component, including Configuration classes
  • as a meta-annotation, for the purpose of composing custom stereotype annotations
  • as a method-level annotation on any Bean method

If a @Configuration class is marked with @Conditional, all of the @Bean methods, Import annotations, and ComponentScan annotations associated with that class will be subject to the conditions.

NOTE: Inheritance of @Conditional annotations is not supported; any conditions from superclasses or from overridden methods will not be considered. In order to enforce these semantics, @Conditional itself is not declared as java.lang.annotation.Inherited; furthermore, any custom composed annotation that is meta-annotated with @Conditional must not be declared as @Inherited.

DependsOn

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.

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 <bean depends-on="..."/> is respected instead.

Description

class Description

Adds a textual description to bean definitions derived from org.springframework.stereotype.Component or Bean.

EnableAspectJAutoProxy

class EnableAspectJAutoProxy

Enables support for handling components marked with AspectJ's @Aspect annotation, similar to functionality found in Spring's <aop:aspectj-autoproxy> XML element. To be used on @Configuration classes as follows:

 @Configuration @EnableAspectJAutoProxy public class AppConfig { @Bean public FooService fooService() { return new FooService(); } @Bean public MyAspect myAspect() { return new MyAspect(); } }
Where FooService is a typical POJO component and MyAspect is an @Aspect-style aspect:
 public class FooService { // various methods }
 @Aspect public class MyAspect { @Before("execution(* FooService+.*(..))") public void advice() { // advise FooService methods as appropriate } }
In the scenario above, @EnableAspectJAutoProxy ensures that MyAspect will be properly processed and that FooService will be proxied mixing in the advice that it contributes.

Users can control the type of proxy that gets created for FooService using the #proxyTargetClass() attribute. The following enables CGLIB-style 'subclass' proxies as opposed to the default interface-based JDK proxy approach.

 @Configuration @EnableAspectJAutoProxy(proxyTargetClass=true) public class AppConfig { // ... }

Note that @Aspect beans may be component-scanned like any other. Simply mark the aspect with both @Aspect and @Component:

 package com.foo; @Component public class FooService { ... } @Aspect @Component public class MyAspect { ... }
Then use the @ComponentScan annotation to pick both up:
 @Configuration @ComponentScan("com.foo") @EnableAspectJAutoProxy public class AppConfig { // no explicit @Bean definitions required }

EnableLoadTimeWeaving

class EnableLoadTimeWeaving

Activates a Spring LoadTimeWeaver for this application context, available as a bean with the name "loadTimeWeaver", similar to the <context:load-time-weaver> element in Spring XML.

To be used on @org.springframework.context.annotation.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:
<beans> <context:load-time-weaver/> <!-- application-specific <bean> definitions --> </beans> 
The LoadTimeWeaverAware interface Any bean that implements the interface will then receive the LoadTimeWeaver reference automatically; for example, Spring's JPA bootstrap support. Customizing the LoadTimeWeaver The default weaver is determined automatically: see DefaultContextLoadTimeWeaver.

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

 @Configuration @EnableLoadTimeWeaving public class AppConfig implements LoadTimeWeavingConfigurer { @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:

<beans> <context:load-time-weaver weaverClass="com.acme.MyLoadTimeWeaver"/> </beans> 

The code example differs from the XML example in that it actually instantiates the MyLoadTimeWeaver type, meaning that it can also configure the instance, e.g. calling the #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 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:

<beans> <context:load-time-weaver aspectj-weaving="on"/> </beans> 

The two examples are equivalent with one significant exception: in the XML case, the functionality of <context:spring-configured> is implicitly enabled when aspectj-weaving is "on". This does not occur when using @EnableLoadTimeWeaving(aspectjWeaving=ENABLED). Instead you must explicitly add @EnableSpringConfigured (included in the spring-aspects module)

EnableMBeanExport

class EnableMBeanExport

Enables default exporting of all standard MBeans from the Spring context, as well as well all @ManagedResource annotated beans.

The resulting org.springframework.jmx.export.MBeanExporter bean is defined under the name "mbeanExporter". Alternatively, consider defining a custom AnnotationMBeanExporter bean explicitly.

This annotation is modeled after and functionally equivalent to Spring XML's <context:mbean-export/> element.

ImportResource

class ImportResource

Indicates one or more resources containing bean definitions to import.

Like Import, this annotation provides functionality similar to the <import/> element in Spring XML. It is typically used when designing Configuration classes to be bootstrapped by an AnnotationConfigApplicationContext, but where some XML functionality such as namespaces is still necessary.

By default, arguments to the #value attribute will be processed using a org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader if ending in ".groovy"; otherwise, an org.springframework.beans.factory.xml.XmlBeanDefinitionReader will be used to parse Spring <beans/> XML files. Optionally, the #reader attribute may be declared, allowing the user to choose a custom BeanDefinitionReader implementation.

Lazy

class Lazy

Indicates whether a bean is to be lazily initialized.

May be used on any class directly or indirectly annotated with or on methods annotated with Bean.

If this annotation is not present on a @Component or @Bean definition, eager initialization will occur. If present and set to true, the @Bean or @Component will not be initialized until referenced by another bean or explicitly retrieved from the enclosing org.springframework.beans.factory.BeanFactory. If present and set to false, the bean will be instantiated on startup by bean factories that perform eager initialization of singletons.

If Lazy is present on a Configuration class, this indicates that all @Bean methods within that @Configuration should be lazily initialized. If @Lazy is present and false on a @Bean method within a @Lazy-annotated @Configuration class, this indicates overriding the 'default lazy' behavior and that the bean should be eagerly initialized.

In addition to its role for component initialization, this annotation may also be placed on injection points marked with org.springframework.beans.factory.annotation.Autowired or javax.inject.Inject: In that context, it leads to the creation of a lazy-resolution proxy for all affected dependencies, as an alternative to using org.springframework.beans.factory.ObjectFactory or javax.inject.Provider.

Primary

class Primary

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.

This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML.

May be used on any class directly or indirectly annotated with @Component or on methods annotated with @Bean.

Example
 @Component public class FooService { private FooRepository fooRepository; @Autowired public FooService(FooRepository fooRepository) { this.fooRepository = fooRepository; } } @Component public class JdbcFooRepository extends FooRepository { public JdbcFooRepository(DataSource dataSource) { // ... } } @Primary @Component public class HibernateFooRepository extends FooRepository { public HibernateFooRepository(SessionFactory sessionFactory) { // ... } } 

Because HibernateFooRepository is marked with @Primary, it will be injected preferentially over the jdbc-based variant assuming both are present as beans within the same Spring application context, which is often the case when component-scanning is applied liberally.

Note that using @Primary at the class level has no effect unless component-scanning is being used. If a @Primary-annotated class is declared via XML, @Primary annotation metadata is ignored, and <bean primary="true|false"/> is respected instead.

Profile

class Profile

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

A profile is a named logical grouping that may be activated programmatically via ConfigurableEnvironment#setActiveProfiles or declaratively by setting the spring.profiles.active property as a JVM system property, as an environment variable, or as a Servlet context parameter in web.xml for web applications. Profiles may also be activated declaratively in integration tests via the @ActiveProfiles annotation.

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

  • as a type-level annotation on any class directly or indirectly annotated with @Component, including Configuration classes
  • as a meta-annotation, for the purpose of composing custom stereotype annotations
  • as a method-level annotation on any Bean method

If a @Configuration class is marked with @Profile, all of the @Bean methods and Import annotations associated with that class will be bypassed unless one or more of the specified profiles are active. This is analogous to the behavior in Spring XML: if the profile attribute of the beans element is supplied e.g., <beans profile="p1,p2">, the beans element will not be parsed unless at least profile 'p1' or 'p2' has been activated. Likewise, if a @Component or @Configuration class is marked with @Profile({"p1", "p2"}), that class will not be registered or processed unless at least profile 'p1' or 'p2' has been activated.

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

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

NOTE: With @Profile on @Bean methods, a special scenario may apply: In the case of overloaded @Bean methods of the same Java method name (analogous to constructor overloading), an @Profile condition needs to be consistently declared on all overloaded methods. If the conditions are inconsistent, only the condition on the first declaration among the overloaded methods will matter. @Profile can therefore not be used to select an overloaded method with a particular argument signature over another; resolution between all factory methods for the same bean follows Spring's constructor resolution algorithm at creation time. Use distinct Java method names pointing to the same bean name if you'd like to define alternative beans with different profile conditions; see ProfileDatabaseConfig in Configuration's javadoc.

When defining Spring beans via XML, the "profile" attribute of the <beans> element may be used. See the documentation in the spring-beans XSD (version 3.1 or greater) for details.

PropertySources

class PropertySources

Container annotation that aggregates several PropertySource annotations.

Can be used natively, declaring several nested PropertySource annotations. Can also be used in conjunction with Java 8's support for repeatable annotations, where PropertySource can simply be declared several times on the same type, implicitly generating this container annotation.

Scope

class Scope

When used as a type-level annotation in conjunction with org.springframework.stereotype.Component, @Scope indicates the name of a scope to use for instances of the annotated type.

When used as a method-level annotation in conjunction with Bean, @Scope indicates the name of a scope to use for the instance returned from the method.

In this context, scope means the lifecycle of an instance, such as singleton, prototype, and so forth. Scopes provided out of the box in Spring may be referred to using the SCOPE_* constants available in the ConfigurableBeanFactory and WebApplicationContext interfaces.

To register additional custom scopes, see org.springframework.beans.factory.config.CustomScopeConfigurer.

Functions

AnnotationConfigApplicationContext

fun AnnotationConfigApplicationContext(configure: AnnotationConfigApplicationContext.() -> Unit): AnnotationConfigApplicationContext

Extension for AnnotationConfigApplicationContext allowing AnnotationConfigApplicationContext { ... } style initialization.