1. Introduction
在本教程中,我們將學習如何使用 Spring Framework 進行簡單的基於 XML 的 Bean 配置。
2. 依賴注入 – 概述
依賴注入是一種技術,其中對象的依賴項由外部容器提供。
假設我們有一個應用程序類,它依賴於一個實際處理業務邏輯的服務:
public class IndexApp {
private IService service;
// standard constructors/getters/setters
}
現在假設 IService 是一個接口:
public interface IService {
public String serve();
}
此接口可以有多個實現方案。
我們來快速看一下其中一個潛在的實現方案:
public class IndexService implements IService {
@Override
public String serve() {
return "Hello World";
}
}
這裏,IndexApp 是一個高層組件,依賴於名為 IService 的低層組件。
本質上,我們正在將 IndexApp 與特定 IService 實現分離,這可以根據各種因素而變化。
3. 依賴注入 – 實踐
讓我們看看如何注入依賴。
3.1. 使用屬性
讓我們看看如何使用基於 XML 的配置將依賴項連接起來:
<bean
id="indexService"
class="com.baeldung.di.spring.IndexService" />
<bean
id="indexApp"
class="com.baeldung.di.spring.IndexApp" >
<property name="service" ref="indexService" />
</bean>
如你所見,我們正在創建 IndexService 的實例併為其分配一個 ID。 默認情況下,該 Bean 是單例模式。 此外,我們還創建了 IndexApp 的實例。
在此 Bean 中,我們使用 setter 方法注入了其他 Bean。
3.2. 使用構造函數注入
與其通過設置方法注入 Bean,我們也可以使用構造函數注入依賴項:
<bean
id="indexApp"
class="com.baeldung.di.spring.IndexApp">
<constructor-arg ref="indexService" />
</bean>
3.3. 使用靜態工廠
我們還可以注入由工廠返回的 Bean。 讓我們創建一個簡單的工廠,該工廠返回一個基於提供的數字的 IService 實例:
public class StaticServiceFactory {
public static IService getNumber(int number) {
// ...
}
}
現在讓我們看看如何使用上述實現將 Bean 注入到 IndexApp 中,使用基於 XML 的配置:
<bean id="messageService"
class="com.baeldung.di.spring.StaticServiceFactory"
factory-method="getService">
<constructor-arg value="1" />
</bean>
<bean id="indexApp" class="com.baeldung.di.spring.IndexApp">
<property name="service" ref="messageService" />
</bean>
在上述示例中,我們使用靜態方法 getService 創建一個 id 為 messageService 的 Bean,並將該 Bean 注入到 IndexApp 中。
3.4. 使用工廠方法
讓我們考慮一個實例工廠,它根據提供的數字返回一個 <em >IService</em> 實例。 這一次,該方法不是靜態的:
public class InstanceServiceFactory {
public IService getNumber(int number) {
// ...
}
}
現在讓我們看看如何使用上述實現將 Bean 注入到 IndexApp 中,使用 XML 配置:
<bean id="indexServiceFactory"
class="com.baeldung.di.spring.InstanceServiceFactory" />
<bean id="messageService"
class="com.baeldung.di.spring.InstanceServiceFactory"
factory-method="getService" factory-bean="indexServiceFactory">
<constructor-arg value="1" />
</bean>
<bean id="indexApp" class="com.baeldung.di.spring.IndexApp">
<property name="service" ref="messageService" />
</bean>
在上述示例中,我們使用 factory-method 調用 getService 方法,在一個 InstanceServiceFactory 實例上創建具有 id 為 messageService 的 Bean,並將該 Bean 注入到 IndexApp 中。
4. 測試
以下是如何訪問配置的 Bean:
@Test
public void whenGetBeans_returnsBean() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("...");
IndexApp indexApp = applicationContext.getBean("indexApp", IndexApp.class);
assertNotNull(indexApp);
}
5. 結論
在本快速教程中,我們演示瞭如何使用基於 XML 的配置以及 Spring 框架來注入依賴的方法。