Annotation Type Configuration
@Target(TYPE) @Retention(RUNTIME) @Documented @Component public @interface Configuration
Indicates that a class declares one or more@Beanmethods 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
@ConfigurationclassesVia
AnnotationConfigApplicationContext@Configurationclasses are typically bootstrapped using eitherAnnotationConfigApplicationContextor 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 the
AnnotationConfigApplicationContextjavadocs for further details, and seeAnnotationConfigWebApplicationContextfor web configuration instructions in aServletcontainer.Via Spring
<beans>XMLAs an alternative to registering
@Configurationclasses directly against anAnnotationConfigApplicationContext,@Configurationclasses may be declared as normal<bean>definitions within Spring XML files:<beans> <context:annotation-config/> <bean class="com.acme.AppConfig"/> </beans>In the example above,
<context:annotation-config/>is required in order to enableConfigurationClassPostProcessorand other annotation-related post processors that facilitate handling@Configurationclasses.Via component scanning
@Configurationis meta-annotated with@Component, therefore@Configurationclasses are candidates for component scanning (typically using Spring XML's<context:component-scan/>element) and therefore may also take advantage of@Autowired/@Injectlike any regular@Component. In particular, if a single constructor is present autowiring semantics will be applied transparently for that constructor:@Configuration public class AppConfig { private final SomeBean someBean; public AppConfig(SomeBean someBean) { this.someBean = someBean; } // @Bean definition using "SomeBean" }@Configurationclasses may not only be bootstrapped using component scanning, but may also themselves configure component scanning using the@ComponentScanannotation:@Configuration @ComponentScan("com.acme.app.services") public class AppConfig { // various @Bean definitions ... }See the
@ComponentScanjavadocs for details.Working with externalized values
Using the
EnvironmentAPIExternalized values may be looked up by injecting the Spring
Environmentinto a@Configurationclass — for example, using the@Autowiredannotation:@Configuration public class AppConfig { @Autowired Environment env; @Bean public MyBean myBean() { MyBean myBean = new MyBean(); myBean.setName(env.getProperty("bean.name")); return myBean; } }Properties resolved through the
Environmentreside in one or more "property source" objects, and@Configurationclasses may contribute property sources to theEnvironmentobject using the@PropertySourceannotation:@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 the
Environmentand@PropertySourcejavadocs for further details.Using the
@ValueannotationExternalized values may be injected into
@Configurationclasses using the@Valueannotation:@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 often used in conjunction with Spring's
PropertySourcesPlaceholderConfigurerthat can be enabled automatically in XML configuration via<context:property-placeholder/>or explicitly in a@Configurationclass via a dedicatedstatic@Beanmethod (see "a note on BeanFactoryPostProcessor-returning@Beanmethods" of@Bean's javadocs for details). Note, however, that explicit registration of aPropertySourcesPlaceholderConfigurervia astatic@Beanmethod is typically only required if you need to customize configuration such as the placeholder syntax, etc. Specifically, if no bean post-processor (such as aPropertySourcesPlaceholderConfigurer) has registered an embedded value resolver for theApplicationContext, Spring will register a default embedded value resolver which resolves placeholders against property sources registered in theEnvironment. See the section below on composing@Configurationclasses with Spring XML using@ImportResource; see the@Valuejavadocs; and see the@Beanjavadocs for details on working withBeanFactoryPostProcessortypes such asPropertySourcesPlaceholderConfigurer.Composing
@ConfigurationclassesWith the
@Importannotation@Configurationclasses may be composed using the@Importannotation, similar to the way that<import>works in Spring XML. Because@Configurationobjects are managed as Spring beans within the container, imported configurations may be injected — for example, via constructor injection:@Configuration public class DatabaseConfig { @Bean public DataSource dataSource() { // instantiate, configure and return DataSource } } @Configuration @Import(DatabaseConfig.class) public class AppConfig { private final DatabaseConfig dataConfig; public AppConfig(DatabaseConfig dataConfig) { this.dataConfig = dataConfig; } @Bean public MyBean myBean() { // reference the dataSource() bean method return new MyBean(dataConfig.dataSource()); } }Now both
AppConfigand the importedDatabaseConfigcan be bootstrapped by registering onlyAppConfigagainst the Spring context:new AnnotationConfigApplicationContext(AppConfig.class);
With the
@Profileannotation@Configurationclasses may be marked with the@Profileannotation to indicate they should be processed only if a given profile or profiles are active:@Profile("development") @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 } }Alternatively, you may also declare profile conditions at the
@Beanmethod level — for example, for alternative bean variants within the same configuration class:@Configuration public class ProfileDatabaseConfig { @Bean("dataSource") @Profile("development") public DataSource embeddedDatabase() { ... } @Bean("dataSource") @Profile("production") public DataSource productionDatabase() { ... } }See the
@ProfileandEnvironmentjavadocs for further details.With Spring XML using the
@ImportResourceannotationAs mentioned above,
@Configurationclasses may be declared as regular Spring<bean>definitions within Spring XML files. It is also possible to import Spring XML configuration files into@Configurationclasses using the@ImportResourceannotation. Bean definitions imported from XML can be injected — for example, using the@Injectannotation:@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
@Configurationclasses@Configurationclasses 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
AppConfigneed be registered against the application context. By virtue of being a nested@Configurationclass,DatabaseConfigwill be registered automatically. This avoids the need to use an@Importannotation when the relationship betweenAppConfigandDatabaseConfigis already implicitly clear.Note also that nested
@Configurationclasses can be used to good effect with the@Profileannotation to provide two options of the same bean to the enclosing@Configurationclass.Configuring lazy initialization
By default,
@Beanmethods will be eagerly instantiated at container bootstrap time. To avoid this,@Configurationmay be used in conjunction with the@Lazyannotation to indicate that all@Beanmethods declared within the class are by default lazily initialized. Note that@Lazymay be used on individual@Beanmethods as well.Testing support for
@ConfigurationclassesThe Spring TestContext framework available in the
spring-testmodule provides the@ContextConfigurationannotation which can accept an array of component class references — typically@Configurationor@Componentclasses.@RunWith(SpringRunner.class) @ContextConfiguration(classes = {AppConfig.class, DatabaseConfig.class}) public class MyTests { @Autowired MyBean myBean; @Autowired DataSource dataSource; @Test public void test() { // assertions against myBean ... } }See the TestContext framework reference documentation for details.
Enabling built-in Spring features using
@EnableannotationsSpring features such as asynchronous method execution, scheduled task execution, annotation driven transaction management, and even Spring MVC can be enabled and configured from
@Configurationclasses using their respective "@Enable" annotations. See@EnableAsync,@EnableScheduling,@EnableTransactionManagement,@EnableAspectJAutoProxy, and@EnableWebMvcfor details.Constraints when authoring
@Configurationclasses- Configuration classes must be provided as classes (i.e. not as instances returned from factory methods), allowing for runtime enhancements through a generated subclass.
- Configuration classes must be non-final.
- Configuration classes must be non-local (i.e. may not be declared within a method).
- Any nested configuration classes must be declared as
static. @Beanmethods may not in turn create further configuration classes (any such instances will be treated as regular beans, with their configuration annotations remaining undetected).
- Since:
- 3.0
- Author:
- Rod Johnson, Chris Beams
- See Also:
Bean,Profile,Import,ImportResource,ComponentScan,Lazy,PropertySource,AnnotationConfigApplicationContext,ConfigurationClassPostProcessor,Environment,ContextConfiguration
Element Detail
value
String value
Explicitly specify the name of the Spring bean definition associated with the@Configurationclass. If left unspecified (the common case), a bean name will be automatically generated.The custom name applies only if the
@Configurationclass is picked up via component scanning or supplied directly to anAnnotationConfigApplicationContext. If the@Configurationclass is registered as a traditional XML bean definition, the name/id of the bean element will take precedence.- Returns:
- the explicit component name, if any (or empty String otherwise)
- See Also:
AnnotationBeanNameGenerator
- Default:
- ""