Spring XML配置的12个技巧
Spring是一个强有力的java程序框架,其被广泛应用于java的程序中。它用POJO提供了企业级服务。Spring利用依赖注入可以获得简单而有效的测试能力。Spring beans,依赖关系,以及服务所需要的bean都将在配置文件中予以描述,配置文件一般采用XML格式。然而XML配置文件冗长而不易使用,在你进行一个使用了大量bean的大项目中它将变得难以阅读和控制。
class="com.lizjason.spring.OrderService">
<property name="companyName">
<value>lizjason</value>
</property>
<constructor-arg>
<ref bean="orderDAO">
</constructor-arg>
</bean>
以上程序可以重新以简化格式书写为:
<bean id="orderService"
class="com.lizjason.spring.OrderService">
<property name="companyName"
value="lizjason"/>
<constructor-arg ref="orderDAO"/>
</bean>
简化格式在1.2版本时已经可用了,但请注意不存在<ref local="...">这种简化格式不仅可以较少你的代码输入量,而且可以使XML配置更加的清晰。当你的配置文件中存在大量的bean定义时,它可以显著地提高可读性。
<bean id="billingService"
class="com.lizjason.spring.BillingService">
<constructor-arg index="0" value="lizjason"/>
<constructor-arg index="1" value="100"/>
</bean>
最好用type属性取代上面的做法:
<bean id="billingService"
class="com.lizjason.spring.BillingService">
<constructor-arg type="java.lang.String"
value="lizjason"/>
<constructor-arg type="int" value="100"/>
</bean>
<bean id="abstractService" abstract="true"
class="com.lizjason.spring.AbstractService">
<property name="companyName"
value="lizjason"/>
</bean>
<bean id="shippingService"
parent="abstractService"
class="com.lizjason.spring.ShippingService">
<property name="shippedBy" value="lizjason"/>
</bean>
shippingService bean继承了abstractService bean的属性companyName的值lizjason。注意,如果你为bean声名一个class或工厂方法,这个bean将会默认为abstract
<beans>
<import resource="billingServices.xml"/>
<import resource="shippingServices.xml"/>
<bean id="orderService"
class="com.lizjason.spring.OrderService"/>
<beans>
然而,比起在XML中用imports预装配这些bean,利用ApplicationContext来配置它们将更加灵活,也可以使XML配置更加的易于管理。你可以像下面这样传递一个bean定义数组到ApplicationContext的构造函数中:
<bean id="orderService"
class="com.lizjason.spring.OrderService"
dependency-check="objects">
<property name="companyName"
value="lizjason"/>
<constructor-arg ref="orderDAO"/>
</bean>
在这个例子中,容器将确保这些属性不是privitives或者保证collections是为orderService bean设置的。为所有的bean设置默认的依赖检查是可能的,但这个特性由于有些bean的属性不需要设置而很少使用。
<beans>
<description>
This file defines billing service
related beans and it depends on
baseServices.xml,which provides
service bean templates...
</description>
...
</beans>
用description元素的一个好处就是工具可以很容易的把描述信息从这个元素中提取出来。
<bean id="orderService"
class="com.lizjason.spring.OrderService">
<constructor-arg ref="orderDAO"/>
</bean>
<bean id="billingService"
class="com.lizjason.spring.BillingService">
<property name="billingDAO"
ref="billingDAO">
</bean>
在这个例子中,orderService bean用了构造函数注入,而BillingService bean用了setter注入。构造函数注入可以确保bean正确地构建,但是setter注入更加的灵活和易于控制,特别是当class有多个属性并且它们中的一些是可选的情况是更是如此。