一、簡述 java
spring reference寫到: spring
Java-based configuration: Starting with Spring 3.0, many features provided by the Spring JavaConfig project became part of the core Spring Framework. Thus you can define beans external to your application classes by using Java rather than XML files. To use these new features, see the @Configuration, @Bean , @Importand @DependsOnannotations.jast領會到:
從Spring3.0開始支持使用java代碼來代替XML來配置Spring,基於Java配置Spring依靠Spring的JavaConfig項目提供的不少優勢。經過使用@Configuration, @Bean ,@Importand,@DependsOnannotations來實現Java的配置Spring.
二、基於Java的Spring的配置(Java-based container configuration) app
基本概念:@Bean 和@Configuration ide
在Spring的新的Java-Configuration的中間產物是基於類的@Configuration的註解和基於方法的@Bean註解。
spa
@Bean註解是用來指明方法的實例化,配置和初始化一個對象是經過Spring的IoC容器來管理的。對於那些熟悉使用以XML配置Spring的<beans /> 標籤,@Bean註解和<bean />標籤是起相同做用的。你能和Spring的@Component註解的組件一塊兒使用@Bean註解方法, 然而,這些@Bean註解的方法一般是和@Configuration的Bean。
.net
@Configuration註解的類指明該類主要是做爲一個bean的來源定義。此外,@Configurationd定義的classes容許在同一個類中使用@Bean定義的方法來定義依賴的bean。如下是一個儘量簡單的用@Configuration定義的class: code
@Configuration public class AppConfig { @Bean publicMyService myService() { return newMyServiceImpl(); } }
上面定義的AppConfig類和如下使用xml的<beans/>標籤訂義是等價物。 xml
<beans> <bean id="myService" class="com.acme.services.MyServiceImpl"/> </beans>
接下來,深刻討論下註解@Bean和註解@Configuration,首先,無論怎樣,咱們將涵蓋所用方式使用基於Java的配置來建立一個Spring的容器。 對象
Spring reference寫到: ip
Full @Configuration vs lite@Beans mode?
When @Beanmethods are declared within classes that are notannotated with @Configuration they are referred to as being processed in a litemode. For example, bean methods declared in a @Componentor even in a plain old classwill be considered lite.
Unlike full @Configuration, lite @Beanmethods cannot easily declare inter-bean dependencies. Usually one @Beanmethod should not invoke another @Beanmethod when operating in litemode.
Only using @Beanmethods within @Configurationclasses is a recommended approach of ensuring that fullmode is always used. This will prevent the same @Beanmethod from accidentally being invoked multiple times and helps to reduce subtle bugs that can be hard to track down when operating in litemode.
譯爲:
完整的@Configuration VS 簡單的@Bean模式
當@Bean修飾方法是
使用AnnotationConfigApplicationContext初始化Spring容器