ApplicationContext.xml

Spring的ApplicationContext有着不断简化自己的倾向,原有的autowire,抽象类,<ref>, <property>的简写等大家都知道了,这里说一些其他的东西。

1.default-lazy-init

Spring的lazy-init,可以使单元测试与集成测试时的速度大大加快,不过要留意一些PostBeanProcessor的子类如PropertityPlaceHolderConfigurer,还有spring mvc的servlet.xml,都不能定为lay-init,否则会吃大亏。

2.PropertyOverrideConfigurer

不同于PropertyPlaceholderConfigurer,PropertyOverrideConfigurer主要为了测试环境等进行透明的后期配置特殊更改,如

applicationContext-test.xml:  

  <bean id="testPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
        <property name="location" value="classpath:context/test/jdbc.properties"/>
  </bean>

test.properties:

dataSource.url=jdbc:hsqldb:res:default-db

即会在测试时将ApplicationContext 中id为dataSource的bean的url 改为嵌入式数据库。

3. Spring 2.0的schema简写

Spring 2.0开始推进了一系列的简写发,从僵硬的<bean id="xx" class="xxxx.xxx.xxx">,划为<aop:xxxx>这样的形式。

Spring 2.0所提供的各schema见spring参考手册的附录1,附录2还提供了自行开发schema的方式。手册里宣称,普通团队要开发schema有点麻烦,但呼吁各开源团队开发各自的schema.

4.default-merge

从Spring 2.0M2开始,beans支持default-merge= "true" 的定义,子类不需要重新定义父类的List型属性中已定义过的内容。

  在声明式事务体系下,一般会定义一个baseTxService基类

<bean id="baseTxService"
          class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
          abstract="true">
        <property name="transactionManager" ref="transactionManager"/>
        <property name="proxyTargetClass" value="true"/>
   <property name="transactionAttributes">
            <props>
                <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
                <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
                <prop key="save*">PROPAGATION_REQUIRED</prop>
                <prop key="update*">PROPAGATION_REQUIRED</prop>
                <prop key="remove*">PROPAGATION_REQUIRED</prop>
            </props>
        </property>
 </bean>

可以在beans统一定义default-merge= true,也可以每个bean定义,则子类的transactionAtttributes只须定义子类新增的部分,无须再定义get*,save*等。

<beans default-merge="true"> 
<bean id="orderManager" parent="baseTxService">
        <property name="target">
            <bean class="org.springside.bookstore.service.OrderManager"/>
        </property>
        <property name="transactionAttributes">
            <props>
                <prop key="shipOrder">PROPAGATION_REQUIRED</prop>
            </props>
         </property>
    </bean>
</beans>

5.IMPORT

如何组织ApplicationContext文件,决定了声明式编程会不会差一步变成配置地狱。SpringSide的建议,为了单元测试,ApplicationContext文件尽量放ClassPath 而不是WEB-INF 目录。另外,尽量使用<Import> 帮助以模块为单元组织ApplicationContext文件。

如根目录的 /applicationContext-manager.xml 和 springmvc-servlet.xml,都只定义公共的一些东西,然后以如下方式include模块里的applicationContext

<import resource="classpath:org/springside/bookstore/admin/applicationContext-manager.xml"/>