本文整理六個主題:Bean 的定義/初始化/使用/銷毀、ref 的三種依賴寫法、五種自動裝配模式、四種依賴檢查模式、集合的注入方式,以及 Bean 的三種管理入口。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"https://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="" class="" init-method="" destroy-method=""
autowire="" dependency-check="">
<property>
<value></value>
</property>
</bean>
</beans>
初始化有兩種方式:設定 init-method,或實作 InitializingBean 介面並提供 afterPropertiesSet()。銷毀同理:設定 destroy-method,或實作 DisposableBean 介面的 destroy()。
使用 Bean 有三種途徑:
// 1) BeanWrapper —— 直接操作單一物件
HelloWorld hellworld = new HelloWorld();
BeanWrapper bw = new BeanWrapperImpl(hellworld);
bw.setPropertyValue("msg", "helloworld");
bw.getPropertyValue("msg");
// 2) BeanFactory —— 延遲載入
InputStream is = new FileInputStream("config.xml");
XmlBeanFactory factory = new XmlBeanFactory(is);
HelloWorld helloWorld = (HelloWorld) factory.getBean("HelloWorld");
helloWorld.getMsg();
// 3) ApplicationContext —— 啟動時預先實例化
ApplicationContext actx = new FileSystemXmlApplicationContext("config.xml");
HelloWorld helloWorld = (HelloWorld) actx.getBean("HelloWorld");
helloWorld.getMsg();
BeanFactory 與 ApplicationContext 的差別就在這裡:前者用到才建立,後者在容器啟動時就產生全部單例,啟動較慢但執行期更快,也更早暴露配置錯誤。
<property>
<ref local="local"/> || <ref bean="bean"/> || <ref parent="parent"/>
</property>
local 只能引用同一個設定檔內的 Bean,並會在解析時驗證 id 是否存在;bean 可跨檔引用;parent 則用於繼承父容器中的定義。
no:預設值,不做自動裝配。byName:依屬性名稱匹配 Bean 的 id。byType:依屬性型別匹配,若同型別有多個 Bean 會出錯。constructor:以建構子參數的型別匹配。autodetect:有建構子注入就用 constructor,否則退回 byType。需與 autowire 搭配使用:none(預設,不檢查)、simple(檢查基本型別與字串)、object(檢查依賴物件)、all(等於 simple + object)。
<!-- List -->
<property name="">
<list>
<value></value>
<value></value>
</list>
</property>
<!-- Set -->
<property name="">
<set>
<value></value>
<value></value>
</set>
</property>
<!-- Map -->
<property name="">
<map>
<entry key=""><value></value></entry>
</map>
</property>
<!-- Properties -->
<property name="">
<props>
<prop key="">HelloWorld</prop>
</props>
</property>
BeanWrapper 面向單一物件、BeanFactory 是最基礎的容器、ApplicationContext 則是企業應用的標準選擇。三者由低到高,功能與便利性遞增。值得一提的是,上述 XML 配置在現代 Spring 中已大量被 Java Config 與 @Autowired/@Component 取代,但理解這些標籤的語意,仍有助於讀懂老專案的設定檔。