[英]Understanding spring @Configuration class
在了解了Spring @Autowired用法的問題后,我想為彈簧布線的另一個選項@Configuration
類創建一個完整的知識庫。
假設我有一個如下所示的spring XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<import resource="another-application-context.xml"/>
<bean id="someBean" class="stack.overflow.spring.configuration.SomeClassImpl">
<constructor-arg value="${some.interesting.property}" />
</bean>
<bean id="anotherBean" class="stack.overflow.spring.configuration.AnotherClassImpl">
<constructor-arg ref="someBean"/>
<constructor-arg ref="beanFromSomewhereElse"/>
</bean>
</beans>
我怎樣才能使用@Configuration
? 它對代碼本身有什么影響嗎?
@Configuration
可以通過幾個步驟將xml遷移到@Configuration
:
創建一個@Configuration
注釋類:
@Configuration public class MyApplicationContext { }
對於每個<bean>
標記,創建一個使用@Bean
注釋的方法:
@Configuration public class MyApplicationContext { @Bean(name = "someBean") public SomeClass getSomeClass() { return new SomeClassImpl(someInterestingProperty); // We still need to inject someInterestingProperty } @Bean(name = "anotherBean") public AnotherClass getAnotherClass() { return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse); // We still need to inject beanFromSomewhereElse } }
為了導入beanFromSomewhereElse
我們需要導入它的定義。 它可以用XML定義,我們將使用@ImportResource
:
@ImportResource("another-application-context.xml") @Configuration public class MyApplicationContext { ... }
如果bean在另一個@Configuration
類中定義,我們可以使用@Import
注釋:
@Import(OtherConfiguration.class) @Configuration public class MyApplicationContext { ... }
在我們導入其他XML或@Configuration
類之后,我們可以通過聲明@Configuration
類的私有成員來使用它們在我們的上下文中聲明的bean,如下所示:
@Autowired @Qualifier(value = "beanFromSomewhereElse") private final StrangeBean beanFromSomewhereElse;
或者直接在方法中使用它作為參數,該方法使用@Qualifier
定義依賴於此beanFromSomewhereElse
的bean,如下所示:
@Bean(name = "anotherBean") public AnotherClass getAnotherClass(@Qualifier (value = "beanFromSomewhereElse") final StrangeBean beanFromSomewhereElse) { return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse); }
導入屬性與從另一個xml或@Configuration
類導入bean非常相似。 我們將使用@Value
而不是使用@Qualifier
,如下所示:
@Autowired @Value("${some.interesting.property}") private final String someInterestingProperty;
這也可以與SpEL表達式一起使用。
為了允許spring將這些類視為bean容器,我們需要在主xml中將此標記放在上下文中:
<context:annotation-config/>
您現在可以導入@Configuration
類與創建簡單bean完全相同:
<bean class="some.package.MyApplicationContext"/>
有一些方法可以完全避免使用Spring XML,但它們不在本答案的范圍內。 您可以在我的博客文章中找到其中一個選項,我的答案基於這些選項。
基本上我發現這種聲明bean的方法比使用XML更舒服,因為我看到了一些優點:
@Configuration
類被編譯,錯別字只是不允許編譯 我看到它們的缺點並不多,但有一些我能想到的:
@Configuration
類,您必須在編譯時提供類。 通常這不是問題,但有些情況可能會發生。 結論:在應用程序上下文中組合XML, @Configuration
Configuration和注釋是完美的。 Spring並不關心聲明bean的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.