《Spring攻略(第2版)》——1.9 用依賴檢查屬性
本節書摘來自異步社區《Spring攻略(第2版)》一書中的第1章,第1.9節,作者: 【美】Gary Mak , Josh Long , Daniel Rubio著,更多章節內容可以訪問雲棲社區“異步社區”公眾號查看
1.9 用依賴檢查屬性
1.9.1 問題
在大規模的應用中,IoC容器中可能聲明了幾百個或者幾千個Bean,這些Bean之間的依賴往往非常複雜。設值方法注入的不足之一是無法確定一個屬性將會被注入。檢查所有必要的屬性是否已經設置是非常困難的。
1.9.2 解決方案
Spring的依賴檢查功能能夠幫助你檢查在一個Bean上的所有特定類型屬性是否都已經設置。你隻要在的dependency-check屬性中指定依賴檢查模式就可以了。注意,依賴檢查功能隻能檢查屬性是否已經設置,而無法檢查它們的值是否非空。表1-1列出了Spring支持的所有依賴檢查模式。
*默認模式為none,但是可以設置根元素的default-dependency-check屬性來改變。如果Bean指定了自己的模式,默認模式將被覆蓋。你必須小心設置這個屬性,因為它將改變IoC容器中的所有Bean的默認依賴檢查模式。
1.9.3 工作原理
檢查簡單類型屬性
假定序列生成器的suffix屬性沒有設置。那麼生成器將生成後綴為空字符串的序列號。這種問題通常很難調試,特別是在複雜的Bean中。幸運的是,Spring能夠檢查所有特定類型的屬性是否已經設置。為了要求Spring檢查簡單類型(也就是原始類型和集合類型)的屬性,將的dependency-check屬性設置為simple。
<bean
dependency-check="simple">
<property name="initial" value="100000" />
<property name="prefixGenerator" ref="datePrefixGenerator" />
</bean>
如果任何這些類型的屬性沒有設置,就會拋出UnsatisfiedDependencyException異常,指出未設置的屬性。
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating
bean with name 'sequenceGenerator' defined in class path resource [beans.xml]:
Unsatisfied dependency expressed through bean property 'suffix': Set this property
value or disable dependency checking for this bean.
檢查對象類型的屬性
如果前綴生成器未被設置,請求它的時候將會拋出討厭的NullPointerException異常。為了使依賴檢查能檢查對象類型(也就是簡單類型之外的)的Bean屬性,將dependency-check屬性改為objects。
<bean
dependency-check="objects">
<property name="initial" value="100000" />
<property name="suffix" value="A" />
</bean>
當你運行應用程序時,Spring將通知你prefixGenerator屬性未設置。
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating
bean with name 'sequenceGenerator' defined in class path resource [beans.xml]:
Unsatisfied dependency expressed through bean property 'prefixGenerator': Set this
property value or disable dependency checking for this bean.
檢查所有類型屬性
如果你想檢查任何類型的所有Bean屬性,可以將dependency-check屬性改為all。
<bean
dependency-check="all">
<property name="initial" value="100000" />
</bean>
依賴檢查和構造程序注入
Spring的依賴檢查功能隻檢查屬性是否通過設值方法注入。所以,即使你已經通過構造程序注入了前綴生成器,仍然會拋出UnsatisfiedDependencyException異常。
<bean
dependency-check="all">
<constructor-arg ref="datePrefixGenerator" />
<property name="initial" value="100000" />
<property name="suffix" value="A" />
</bean>
最後更新:2017-05-31 15:31:28