(環境:.Net1.1 ,Spring.net 1.2 Preview)
1.集合屬性注入
我們的組件經常需要集合類型的屬性注入,比如我的Hook(鉤子)組件需要注入一個集合,該集合中的元素(int型)指明了要截獲哪些類型的訊息。我們經常使用IList處理集合問題:
#region HookList 其中元素為整數類型
private IList hookList = new ArrayList() ;
public IList HookList
{
set
{
this.hookList = value ;
}
}
#endregion
對應的Spring配置片斷如下: <property name="HookList">
<list>
<value>1</value>
<value>3</value>
<value>2</value>
</list>
</property>
當IOC容器根據配置組裝後,發現HookList中的元素是string類型的,因為IList中可以容納任意類型的object,所以Spring採用了配置的預設類型--string。不出你想象,在運行時,如果使用下面的代碼一定會拋出異常:
foreach(int key in this.HookedList)
在經過一番思索和實驗後,結論是這樣的:
(1)如果要設定的集合屬性中的元素是string類型的,使用IList就很好。
(2)如果是其他類型,則屬性集合的類型最好是目標類型的數組,即上面的屬性可以改為: #region HookList
private int[] hookList = new int[0] ;
public int[] HookList
{
set
{
this.hookList = value ;
}
}
#endregion
屬性的定義經過修改後,設定檔和使用它的代碼不用做任何修改即可正常工作。
2.2006-06-12 當Spring依據設定檔裝配對象時,如果發生錯誤,那麼Spring在拋出異常之前將會依次調用每個已執行個體化對象的Dispose方法,然後再拋出System.Configuration.ConfigurationErrorsException。
如果你的程式在調用Spring.Context.Support.ContextRegistry.GetContext()時沒有了反應,那麼很可能是在調用某個執行個體的Dispose方法中有ManualResetEvent.WaitOne(-1, true);的存在。
3.2006-06-13 從多個Xml設定檔中讀取對象
有三種類型的設定檔可以用來裝配組件:
(1)App.config 在Context配置節中作如下指示:<resource uri="config://spring/objects"/>
(2)嵌入到程式集中的xml設定檔。在Context配置節中作如下指示:<resource uri="assembly://SpringNestConfigTest/SpringNestConfigTest/AppContext.xml"/>
格式: uri="assembly://MyAssembly/MyProject/AppContext.xml"/
(3)AppBase下的普通xml設定檔。在Context配置節中作如下指示:<resource uri="file://objects.xml"/>
綜合起來: <context>
<!-- using section in App.config -->
<resource uri="config://spring/objects"/>
<!-- using embedded assembly configuration file -->
<resource uri="assembly://SpringNestConfigTest/SpringNestConfigTest/AppContext.xml"/>
<!-- using common configuration file -->
<resource uri="file://objects.xml"/>
</context>
比如objects.xml的內容:<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<object name="esbNetMessageHook" type="ESFramework.Network.EsbNetMessageHook ,ESFramework">
</object>
<object name="agileTcp" type="ESFramework.Network.Tcp.AsynTcp ,ESFramework">
<property name="EsbLogger" ref="esbLogger"/>
</object>
</objects>
esbLogger對象定義於AppContext.xml中。