Spring IOC容器的基本應用
Spring IOC概述
IOC全稱Inversion of Control,被譯為控制反轉,是指程式中對象的擷取方式發生反轉,由最初的new方式建立,轉變為由第三方架構建立、注入(DI),它降低了對象之間的耦合度。
Spring容器是IOC機制的一種實現,同時IOC也是Spring架構的基礎和核心,它藉助DI(Dependency Injection)方法實現。
Spring Bean容器
Spring容器是Spring架構中的核心組件,負責建立Bean對象(一種簡單規範的JAVA對象)及管理這些對象之間的依賴關係。
Spring容器是如何工作的呢?在Spring項目運行是,Spring容器負責讀取項目中的中繼資料資訊(這些中繼資料可能是基於xml、也可能是基於註解實現),然後這些資訊建立Bean對象的執行個體。
IOC是Spring架構中的一種機制,提供了容器中對象的控制反轉功能,這個功能的實現需要藉助依賴尋找和依賴注入。
Spring容器中繼資料配置
Spring中中繼資料的配置有兩種方式,基於xml或annotation方式。這個小節瞭解基於XML方式的中繼資料實現bean元素的基本配置(後續在描述annotation方式)。
<?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.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
Spring中多個元素設定檔的實現方法
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
Spring容器的初始化
Spring中容器的類型為Application類型,其初始化方法如下:
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
Spring容器初始化是需要載入中繼資料的配置資訊,類如beans.xml檔案中聲明的中繼資料的相關配置。
Spring 容器的使用
Spring容器初始化以後,可以通過容器的getBean(...)方法擷取容器的Bean對象,進而操作Bean對象,例如:
Contex.getBean(“xxxService”,XxxService.class);
本文永久更新連結地址:https://www.bkjia.com/Linux/2018-03/151300.htm