直接上文档吧,很方便!

    1. 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:
    2. @Configuration
    3. public class AppConfig {
    4. @Bean
    5. public MyBean myBean() {
    6. // instantiate, configure and return bean ...
    7. }
    8. }
    9. Bootstrapping @Configuration classes
    10. Via AnnotationConfigApplicationContext
    11. @Configuration classes are typically bootstrapped using either AnnotationConfigApplicationContext or its web-capable variant, AnnotationConfigWebApplicationContext. A simple example with the former follows:
    12. AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    13. ctx.register(AppConfig.class);
    14. ctx.refresh();
    15. MyBean myBean = ctx.getBean(MyBean.class);
    16. // use myBean ...
    17. See the AnnotationConfigApplicationContext javadocs for further details, and see AnnotationConfigWebApplicationContext for web configuration instructions in a Servlet container.
    18. Via Spring <beans> XML
    19. As an alternative to registering @Configuration classes directly against an AnnotationConfigApplicationContext, @Configuration classes may be declared as normal <bean> definitions within Spring XML files:
    20. <beans>
    21. <context:annotation-config/>
    22. <bean class="com.acme.AppConfig"/>
    23. </beans>
    24. 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.
    25. Via component scanning
    26. @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 like any regular @Component. In particular, if a single constructor is present autowiring semantics will be applied transparently for that constructor:
    27. @Configuration
    28. public class AppConfig {
    29. private final SomeBean someBean;
    30. public AppConfig(SomeBean someBean) {
    31. this.someBean = someBean;
    32. }
    33. // @Bean definition using "SomeBean"
    34. }
    35. @Configuration classes may not only be bootstrapped using component scanning, but may also themselves configure component scanning using the @ComponentScan annotation:
    36. @Configuration
    37. @ComponentScan("com.acme.app.services")
    38. public class AppConfig {
    39. // various @Bean definitions ...
    40. }
    41. See the @ComponentScan javadocs for details.
    42. Working with externalized values
    43. Using the Environment API
    44. Externalized values may be looked up by injecting the Spring org.springframework.core.env.Environment into a @Configuration class for example, using the @Autowired annotation:
    45. @Configuration
    46. public class AppConfig {
    47. @Autowired Environment env;
    48. @Bean
    49. public MyBean myBean() {
    50. MyBean myBean = new MyBean();
    51. myBean.setName(env.getProperty("bean.name"));
    52. return myBean;
    53. }
    54. }
    55. 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 @PropertySource annotation:
    56. @Configuration
    57. @PropertySource("classpath:/com/acme/app.properties")
    58. public class AppConfig {
    59. @Inject Environment env;
    60. @Bean
    61. public MyBean myBean() {
    62. return new MyBean(env.getProperty("bean.name"));
    63. }
    64. }
    65. See the Environment and @PropertySource javadocs for further details.
    66. Using the @Value annotation
    67. Externalized values may be injected into @Configuration classes using the @Value annotation:
    68. @Configuration
    69. @PropertySource("classpath:/com/acme/app.properties")
    70. public class AppConfig {
    71. @Value("${bean.name}") String beanName;
    72. @Bean
    73. public MyBean myBean() {
    74. return new MyBean(beanName);
    75. }
    76. }
    77. This approach is often used in conjunction with Spring's PropertySourcesPlaceholderConfigurer that can be enabled automatically in XML configuration via <context:property-placeholder/> or explicitly in a @Configuration class via a dedicated static @Bean method (see "a note on BeanFactoryPostProcessor-returning @Bean methods" of @Bean's javadocs for details). Note, however, that explicit registration of a PropertySourcesPlaceholderConfigurer via a static @Bean method is typically only required if you need to customize configuration such as the placeholder syntax, etc. Specifically, if no bean post-processor (such as a PropertySourcesPlaceholderConfigurer) has registered an embedded value resolver for the ApplicationContext, Spring will register a default embedded value resolver which resolves placeholders against property sources registered in the Environment. See the section below on composing @Configuration classes with Spring XML using @ImportResource; see the @Value javadocs; and see the @Bean javadocs for details on working with BeanFactoryPostProcessor types such as PropertySourcesPlaceholderConfigurer.
    78. Composing @Configuration classes
    79. With the @Import annotation
    80. @Configuration classes may be composed using the @Import annotation, similar to the way that <import> works in Spring XML. Because @Configuration objects are managed as Spring beans within the container, imported configurations may be injected for example, via constructor injection:
    81. @Configuration
    82. public class DatabaseConfig {
    83. @Bean
    84. public DataSource dataSource() {
    85. // instantiate, configure and return DataSource
    86. }
    87. }
    88. @Configuration
    89. @Import(DatabaseConfig.class)
    90. public class AppConfig {
    91. private final DatabaseConfig dataConfig;
    92. public AppConfig(DatabaseConfig dataConfig) {
    93. this.dataConfig = dataConfig;
    94. }
    95. @Bean
    96. public MyBean myBean() {
    97. // reference the dataSource() bean method
    98. return new MyBean(dataConfig.dataSource());
    99. }
    100. }
    101. Now both AppConfig and the imported DatabaseConfig can be bootstrapped by registering only AppConfig against the Spring context:
    102. new AnnotationConfigApplicationContext(AppConfig.class);
    103. With the @Profile annotation
    104. @Configuration classes may be marked with the @Profile annotation to indicate they should be processed only if a given profile or profiles are active:
    105. @Profile("development")
    106. @Configuration
    107. public class EmbeddedDatabaseConfig {
    108. @Bean
    109. public DataSource dataSource() {
    110. // instantiate, configure and return embedded DataSource
    111. }
    112. }
    113. @Profile("production")
    114. @Configuration
    115. public class ProductionDatabaseConfig {
    116. @Bean
    117. public DataSource dataSource() {
    118. // instantiate, configure and return production DataSource
    119. }
    120. }
    121. Alternatively, you may also declare profile conditions at the @Bean method level for example, for alternative bean variants within the same configuration class:
    122. @Configuration
    123. public class ProfileDatabaseConfig {
    124. @Bean("dataSource")
    125. @Profile("development")
    126. public DataSource embeddedDatabase() { ... }
    127. @Bean("dataSource")
    128. @Profile("production")
    129. public DataSource productionDatabase() { ... }
    130. }
    131. See the @Profile and org.springframework.core.env.Environment javadocs for further details.
    132. With Spring XML using the @ImportResource annotation
    133. 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 for example, using the @Inject annotation:
    134. @Configuration
    135. @ImportResource("classpath:/com/acme/database-config.xml")
    136. public class AppConfig {
    137. @Inject DataSource dataSource; // from XML
    138. @Bean
    139. public MyBean myBean() {
    140. // inject the XML-defined dataSource bean
    141. return new MyBean(this.dataSource);
    142. }
    143. }
    144. With nested @Configuration classes
    145. @Configuration classes may be nested within one another as follows:
    146. @Configuration
    147. public class AppConfig {
    148. @Inject DataSource dataSource;
    149. @Bean
    150. public MyBean myBean() {
    151. return new MyBean(dataSource);
    152. }
    153. @Configuration
    154. static class DatabaseConfig {
    155. @Bean
    156. DataSource dataSource() {
    157. return new EmbeddedDatabaseBuilder().build();
    158. }
    159. }
    160. }
    161. 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 and DatabaseConfig is already implicitly clear.
    162. 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.
    163. Configuring lazy initialization
    164. 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.
    165. Testing support for @Configuration classes
    166. The Spring TestContext framework available in the spring-test module provides the @ContextConfiguration annotation which can accept an array of component class references typically @Configuration or @Component classes.
    167. @RunWith(SpringRunner.class)
    168. @ContextConfiguration(classes = {AppConfig.class, DatabaseConfig.class})
    169. public class MyTests {
    170. @Autowired MyBean myBean;
    171. @Autowired DataSource dataSource;
    172. @Test
    173. public void test() {
    174. // assertions against myBean ...
    175. }
    176. }
    177. See the TestContext framework reference documentation for details.
    178. Enabling built-in Spring features using @Enable annotations
    179. 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.
    180. Constraints when authoring @Configuration classes
    181. Configuration classes must be provided as classes (i.e. not as instances returned from factory methods), allowing for runtime enhancements through a generated subclass.
    182. Configuration classes must be non-final (allowing for subclasses at runtime), unless the proxyBeanMethods flag is set to false in which case no runtime-generated subclass is necessary.
    183. Configuration classes must be non-local (i.e. may not be declared within a method).
    184. Any nested configuration classes must be declared as static.
    185. @Bean methods may not in turn create further configuration classes (any such instances will be treated as regular beans, with their configuration annotations remaining undetected).
    186. Since:
    187. 3.0
    188. See Also:
    189. Bean, Profile, Import, ImportResource, ComponentScan, Lazy, PropertySource, AnnotationConfigApplicationContext, ConfigurationClassPostProcessor, org.springframework.core.env.Environment, org.springframework.test.context.ContextConfiguration
    190. @Target(ElementType.TYPE)
    191. @Retention(RetentionPolicy.RUNTIME)
    192. @Documented
    193. @Component
    194. public @interface Configuration {
    195. /**
    196. * Explicitly specify the name of the Spring bean definition associated with the
    197. * {@code @Configuration} class. If left unspecified (the common case), a bean
    198. * name will be automatically generated.
    199. * <p>The custom name applies only if the {@code @Configuration} class is picked
    200. * up via component scanning or supplied directly to an
    201. * {@link AnnotationConfigApplicationContext}. If the {@code @Configuration} class
    202. * is registered as a traditional XML bean definition, the name/id of the bean
    203. * element will take precedence.
    204. * @return the explicit component name, if any (or empty String otherwise)
    205. * @see AnnotationBeanNameGenerator
    206. */
    207. @AliasFor(annotation = Component.class)
    208. String value() default "";
    209. /**
    210. * Specify whether {@code @Bean} methods should get proxied in order to enforce
    211. * bean lifecycle behavior, e.g. to return shared singleton bean instances even
    212. * in case of direct {@code @Bean} method calls in user code. This feature
    213. * requires method interception, implemented through a runtime-generated CGLIB
    214. * subclass which comes with limitations such as the configuration class and
    215. * its methods not being allowed to declare {@code final}.
    216. * <p>The default is {@code true}, allowing for 'inter-bean references' via direct
    217. * method calls within the configuration class as well as for external calls to
    218. * this configuration's {@code @Bean} methods, e.g. from another configuration class.
    219. * If this is not needed since each of this particular configuration's {@code @Bean}
    220. * methods is self-contained and designed as a plain factory method for container use,
    221. * switch this flag to {@code false} in order to avoid CGLIB subclass processing.
    222. * <p>Turning off bean method interception effectively processes {@code @Bean}
    223. * methods individually like when declared on non-{@code @Configuration} classes,
    224. * a.k.a. "@Bean Lite Mode" (see {@link Bean @Bean's javadoc}). It is therefore
    225. * behaviorally equivalent to removing the {@code @Configuration} stereotype.
    226. * @since 5.2
    227. */
    228. boolean proxyBeanMethods() default true;
    229. }

    proxyBeanMethods表示是否为当前Configuration类生成一个CGLib代理,默认为true, 表示每次调用内部的@Bean方法时,直接返回容器里的单例bean,否则每次调用都会生成新的Bean实例。

    举个例子:

    1. @Configuration(proxyBeanMethods = false)
    2. @ConditionalOnProperty(prefix = "demo", name = "auto", havingValue = "true", matchIfMissing = false)
    3. public class DemoAutoConfiguration {
    4. public DemoAutoConfiguration() {
    5. System.out.println("##DemoAutoConfiguration##");
    6. }
    7. @Bean(name = "addr1")
    8. public AddressService addrService() {
    9. return new AddressService();
    10. }
    11. }
    1. @Autowired
    2. private DemoAutoConfiguration demoAutoConfiguration;
    3. @Autowired
    4. @Qualifier("addr1")
    5. private DemoAutoConfiguration.AddressService addressService1;
    6. public void run(ApplicationArguments args) throws Exception {
    7. DemoAutoConfiguration.AddressService addressService = demoAutoConfiguration.addrService();
    8. System.out.println(addressService == addressService1);
    9. }

    如果proxyBeanMethods=false, 则demoAutoConfiguration.addrService()方法返回新的对象,与addressService1不一致,如果proxyBeanMethods=true,则每次调用demoAutoConfiguration.addrService()返回的对象为容器里的bean,与addressService1一致。