@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:

标示一个类声明了一个或多个 @Bean 方法,并且可以被 Spring 容器处理,在运行时为这些 beans 产生 bean definations 和服务请求,例如:

 @Configuration

 public class AppConfig { 

     @Bean

     public MyBean myBean() {

         // instantiate, configure and return bean ...

   // 实例化,配置和返回 bean

     }

 }

Bootstrapping @Configuration classes  

启动 @Configuration 类

Via AnnotationConfigApplicationContext

通过 AnnotationConfigApplicationContext

@Configuration classes are typically bootstrapped using either AnnotationConfigApplicationContext or its web-capable variant, AnnotationConfigWebApplicationContext. A simple example with the former follows:

@Configuration 类通常使用 AnnotationConfigApplicationContext 或它的 Web 变体 AnnotationConfigWebApplicationContext 来启动。下面是使用前者的一个简单例子: 

 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.

从 AnnotationConfigApplicationContext javaDoc 中查看更多详细说明,查看 AnnotationConfigWebApplicationContext 的 web.xml 的配置介绍。

Via Spring <beans> XML

通过 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:

作为 AnnotationConfigApplicationContext 直接注册 @Configuration 类的替代,@Configuration 类可以作为一个普通 <bean> definations 在 Spring XML 文件中声明:

 <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.

在上面的例子中,为了启用处理 @Configuration 类的  ConfigurationClassPostProcessor 和其他注解相关的 post processors 需要在 Spring XML 文件中声明 <context:annotation-config/> 。

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 使用了 @Component 注解元数据,因此 @Configuration 是组件扫描的候选(通常使用 Spring XML 的 <context:component-scan/> 元素)因此也可以在字段和方法级别使用 @Autowired/@Inject(但是不能用在构造器级别)。

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

@Configuration 类不仅能通过组件扫描启用,而且他们也可以使用 @ComponentScan 注解配置组件扫描:

 @Configuration

 @ComponentScan("com.acme.app.services")

 public class AppConfig {

     // various @Bean definitions ...

     // 多个 @Bean definations

 }

See the @ComponentScan javadoc for details.

参看 @ComponentScan javadoc 获取详细信息。

Working with externalized values

跟外化值一块使用

Using the Environment API

使用 Enviroment API

Externalized values may be looked up by injecting the Spring Environment into a @Configuration class using the @Autowired or the @Inject annotation:

外化值可以通过注入 Spring Enviroment 来查找并通过使用 @Autowired 或 @Inject 注解置入 @Configuration 类中。

  @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:

通过 Enviroment 处理的属性位于一个或多个 “属性源” (property source) 对象中,@Configuration  类可以使用 @PropertySources 注解为 Enviroment 对象提供属性源。

 @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.

参看 Enviroment 和 @PropertySource Java 文档获取更多信息。

Using the @Value annotation

使用 @Value 注解

Externalized values may be 'wired into' @Configuration classes using the @Value annotation:

外化值可以使用 @Value 注解绑定进 @Configuration 类。

 @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.

当使用 Spring 的 PropertySourcesPlaceholderConfigurer 时此方式非常有用,PropertySourcesPlaceholderConfigurer 通常在 Spring XML 中通过 <context:property-placeholder/> 来启用。参看下面的使用 @ImportResource(用 Spring XML)组合 @Configuration 类的章节,参看 @Value JavaDoc 和 @Bean JavaDoc 中关于使用 BeanFactoryPostProcessor 类型比如 PropertySourcesPlaceholderConfigurer 的详细信息。

Composing @Configuration classes

组合 @Configuration 类

With the @Import annotation

与 @Import 注解一块使用

@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:

使用 @Import 组合 @Configuration 类,与在 Spring XML 中使用 <import> 的方式没有不同。因为 @Configuration 对象在容器中作为 Spring beans 管理,导入的配置可以使用 @Autowired 或 @Inject 被注入。

 @Configuration

 public class DatabaseConfig {

     @Bean

     public DataSource dataSource() {

         // instantiate, configure and return DataSource

         // 实例化,配置并返回 DataSource

     }

 }

 @Configuration

 @Import(DatabaseConfig.class)

 public class AppConfig {

     @Inject DatabaseConfig dataConfig;

     @Bean

     public MyBean myBean() {

         // reference the dataSource() bean method

         // 引用 dataSource() bean 方法

         return new MyBean(dataConfig.dataSource());

     }

 }

Now both AppConfig and the imported DatabaseConfig can be bootstrapped by registering only AppConfig against the Spring context:

现在在 Spring 上下文中只注册 AppConfig,AppConfig 和导入的 DatabaseConfig 就都可以被启用:

 new AnnotationConfigApplicationContext(AppConfig.class);

With the @Profile annotation 

与 @Profile 注解一块使用

@Configuration classes may be marked with the @Profile annotation to indicate they should be processed only if a given profile or profiles are active:

@Configuration 可以被 @Profile 注解标注,表示当给定的 profile 或 profiles 激活时它们(被 @Profile 注解标注的 @Configuration 类)将被处理:

 @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 the @Profile and Environment javadocs for further details.

 参见 @Profile 和 Enviroment JavaDocs 获取更多详细信息。

With Spring XML using the @ImportResource annotation

 使用 @ImportResource 注解导入 Spring XML 文件中的配置

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 @Inject:

 上面提到过,@Cofiguration 类可以在 Spring XML 文件中声明为普通 Spring <bean> definiaions。也可以使用 @ImportResource 注解将 Spring XML 配置导入到 @Configuration 类中。从XML中导入的 bean definitions 可以使用 @Autowired 或 @Inject 被注入:

 @Configuration

 @ImportResource("classpath:/com/acme/database-config.xml")

 public class AppConfig {

     @Inject DataSource dataSource; // from XML 来自XML

     @Bean

     public MyBean myBean() {

         // inject the XML-defined dataSource bean 注入 XML 定义的 dataSource bean

         return new MyBean(this.dataSource);

     }

 } 

With nested @Configuration classes

使用嵌套的 @Configuration 类

@Configuration classes may be nested within one another as follows:

@Configuration 类可以像下面这样被嵌入到另外一个 @Configuration 类中:

 @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.

当按此约定启动时,只需要将 AppConfig 注册到应用上下文。通过成为一个嵌套的 @Configuration 类,DatabaseConfig 将会被自动注册。 当 AppConfig 和 DatabaseConfig 的关系很清晰时,这样就避免了使用 @Import 注解。

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.

也请注意,使用嵌套 @Configuration 类可以得到好的效果, 与 @Profile 注解一块为外部 @Configuration 类提供同一个bean 的两个选择。

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.

默认地,@Bean 方法将在容器启动时被早期实例化。为了避免这种情况,@Configuration 可以使用 @Lazy 注解表示在此类中声明的所有 @Bean 方法将被延迟初始化。注意 @Bean 也可以用在单独的 @Bean 方法上。

Testing support for @Configuration classes

 @Configuration 类的测试支持

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:

 在 spring-test 模块中提供 @ContextConfiguration 注解使用Spring TestContext 框架,在 Spring 3.1 中它接受一个 @Configuration 类对象数组:

 @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.

查阅 TestContext 框架参考文档获取详细信息。

Enabling built-in Spring features using @Enable annotations

使用 @Enable 注解启用内置 Spring 特性:

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. 

Spring 特性比如异步方法执行,计划任务执行,注解驱动事务管理甚至 Spring MVC,可以使用他们各自的 @Enable 注解从 @Configuration 类启用和配置。参看 @EnableAync,@EnableScheduling, @EnableTransactionManagement, @EnableAspectJAutoProxy, and @EnableWebMvc 获取详细信息。

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.

使用 @Configuration 类的约束限制:

@Configuration classes 必须是非 final的。

@Configuration classes 必须是非局部的(不能再方法内部声明)

@Configuration classes 必须有一个默认无参构造函数并且不能使用 @Autowired 构造器函数。任何嵌套配置类必须是静态的。

原文地址:https://www.cnblogs.com/whilliy/p/5744291.html