1. 程式人生 > >Spring Java Configuration之@Configuration和@Bean

Spring Java Configuration之@Configuration和@Bean

Spring Java Configuration是指用配置類來代替spring中的xml配置檔案,

總的來說@Configuration相當於xml中的<beans>標籤,@Bean相當於xml中的<bean>標籤。

@Configuration沒什麼好說的,表示宣告下面要配置bean了。

具體說下@Bean,在官方的文件中有下面一段話,並舉了一個例子:

declare a bean, simply annotate a method with the @Bean annotation. WhenJavaConfig encounters such a method, it will execute that method and registerthe return value as a bean within aBeanFactory

. By default, thebean name will be the same as the method name (seebean naming for details on how to customize this behavior). Thefollowing is a simple example of a@Bean method declaration:

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return
new TransferServiceImpl(); } }

For comparison sake, the configuration above is exactly equivalent to thefollowing Spring XML:

<beans>
    <bean name="transferService" class="com.acme.TransferServiceImpl"/>
</beans>
                
其大意是說,@Bean通過註解一個方法來宣告一個bean。當JavaConfig遇到此方法時,這個方法會被執行,並且該方法的返回值被被註冊到BeanFactory中。預設的情況下,bean的註冊名稱是方法名稱。

後面的兩段程式碼的作用是相同的,只不過一個是java配置類,而另一個是用xml配置的。