Overview | Package | Class | Tree | Deprecated | Index | Help
| Spring Framework
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: REQUIRED | OPTIONAL | DETAIL: ELEMENT

## org.springframework.context.annotation
Annotation Type Configuration

    @Target(value=TYPE)
    @Retention(value=RUNTIME)
    @Documented
    @Component
    public @interface 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 `@Configuration` classes

### Via `AnnotationConfigApplicationContext`

`@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 `web.xml` configuration instructions.

### Via Spring `<beans>` XML

As an alternative to registering `@Configuration` classes directly against an `AnnotationConfigApplicationContext`, `@Configuration` classes 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 enable `ConfigurationClassPostProcessor` and other annotation-related post processors that facilitate handling `@Configuration` classes.

### Via component scanning

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

`@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 `Environment` API

Externalized values may be looked up by injecting the Spring `Environment` into a `@Configuration` class using the `@Autowired` or the `@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 `Environment` reside in one or more "property source" objects, and `@Configuration` classes may contribute property sources to the `Environment` object using 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 `@Value` annotation

Externalized values may be 'wired into' `@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 `<context:property-placeholder/>`. See the section below on composing `@Configuration` classes with Spring XML using `@ImportResource`, see `@Value` Javadoc, and see `@Bean` Javadoc for details on working with `BeanFactoryPostProcessor` types such as `PropertySourcesPlaceholderConfigurer`.

## Composing `@Configuration` classes

### With the `@Import` annotation

`@Configuration` classes may be composed using the `@Import` annotation, not unlike the way that `<import>` works in Spring XML. Because `@Configuration` objects are managed as Spring beans within the container, imported configurations may be injected using `@Autowired` or `@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 `AppConfig` and the imported `DatabaseConfig` can be bootstrapped by registering only `AppConfig` against the Spring context:

     new AnnotationConfigApplicationContext(AppConfig.class);

### With the `@Profile` annotation

`@Configuration` classes may be marked with the `@Profile` annotation 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 `@ImportResource` annotation

As mentioned above, `@Configuration` classes may be declared as regular Spring `<bean>` definitions within Spring XML files. It is also possible to import Spring XML configuration files into `@Configuration` classes using the `@ImportResource` annotation. Bean definitions imported from XML can be injected using `@Autowired` or `@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 `@Configuration` classes

`@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 `AppConfig` need be registered against the application context. By virtue of being a nested `@Configuration` class, `DatabaseConfig` will be registered automatically. This avoids the need to use an `@Import` annotation when the relationship between `AppConfig` `DatabaseConfig` is already implicitly clear.

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

## Configuring lazy initialization

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

## Testing support for `@Configuration` classes

The Spring TestContext framework available in the `spring-test` module provides the `@ContextConfiguration` annotation, which as of Spring 3.1 can accept an array of `@Configuration` `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 `@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 `@Configuration` classes using their respective "`@Enable`" annotations. See `@EnableAsync`, `@EnableScheduling`, `@EnableTransactionManagement`, `@EnableAspectJAutoProxy`, and `@EnableWebMvc` for details.

## Constraints when authoring `@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 `static`

Since:
  3.0
Author:
  Rod Johnson, Chris Beams
See Also:
  `Bean`, `Profile`, `Import`, `ImportResource`, `ComponentScan`, `Lazy`, `PropertySource`, `AnnotationConfigApplicationContext`, `ConfigurationClassPostProcessor`, `Environment`, `ContextConfiguration`

Optional Element Summary
`java.lang.String` | `value` Explicitly specify the name of the Spring bean definition associated with this Configuration class.

### value

    public abstract java.lang.String value

  Explicitly specify the name of the Spring bean definition associated with this Configuration class. If left unspecified (the common case), a bean name will be automatically generated.

  The custom name applies only if the Configuration class is picked up via component scanning or supplied directly to a `AnnotationConfigApplicationContext`. If the Configuration class is registered as a traditional XML bean definition, the name/id of the bean element will take precedence.

  Returns:
    the specified bean name, if any
  See Also:
    `DefaultBeanNameGenerator`
  Default:
    ""

Overview | Package | Class | Tree | Deprecated | Index | Help
| Spring Framework
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: REQUIRED | OPTIONAL | DETAIL: ELEMENT