WebX 3.0学习笔记(五):SpringExt

WebX是基于Java Servlet API的通用web框架。WebX致力于提供极具扩展性的机制,以满足web应用不断变化的需求,而springext正是webx扩展机制的基石。springext是对spring的扩展,在spring的基础之上提供了扩展能力。


springext能作什么呢?

以ResourceLoadingService为例,它是webs的非常有用的一个service,可以在各种输入源中加载资源文件。


以bean方式装配ResourceLoadingService

如果以Spring Bean方式配置ResourceLoadingService,会是如下这样子:

<bean id="resourceLoadingService" class="com.alibaba…ResourceLoadingService">
     <property name="mappings">
          <map>
               <entry key="/file" value-ref="fileLoader" />
               <entry key="/webroot" value-ref="webappLoader" />
          </map>
     </property>
</bean>
<bean id="fileLoader" class="com.alibaba…FileResourceLoader" >
     <property name="basedir" value="${user.home}" />
</bean>
<bean id="webappLoader" class="com.alibaba…WebappResourceLoader" />

这样的配置简单易行,体现了spring的IoC原则,但是它具有以下缺点:

1、没有检验机制,即使是spring配置写错了,也要等到运行时才会发现。

2、无法了解更多约束,即使是查看了api文档,也未必能知道哪些参数是必填的,哪些参数是互斥的。

3、由于spring配置依赖于服务的实现,所以当服务的实现改变时,spring配置会失败。

以spring scheme 方式装配ResourceLoadingService

Spring 2.0以后,开始支持了xml schema来定义配置,用Spring Schema来配置ResourceLoadingService会变成下面的样子:

<resource-loading id="resourceLoadingService" xmlns="http://www.alibaba.com/schema/services/resource-loading">
     <resource pattern="/file">
          <file-loader basedir="${user.home}" />
     </resource>
     <resource pattern="/webroot">
          <webapp-loader />
     </resource>
</resource-loading>

相对于spring bean定义方式,spring schema方式有以下优点:

1、更易读,配置描述的是服务提供的内容,没有了像bean、property之类的编程术语。

2、具有了检验机制,任何支持xml schema的xml编辑器都可以告诉你配置是否有错误。

3、包含了更多约束,xml schema可以告诉你哪些参数是可选的,哪些参数是必填的。

4、最重要的一点,服务的实现对装配者来说是透明的,只要xml schema不变,即使服务实现发生了变化,也不用修改xml配置。

最后一点实现是通过schema解释器来实现的,服务提供都会负责提供这个解释器,它的作用就是把xml schema配置翻译成spring bean配置。

将具体的实现交给服务提供者,使服务使用者可以用它所能理解的语言来装配服务,这就是spring schema的核心价值。

spring schema有一个很大的缺点:无法扩展。假设你想在上面的例子中添加一个新的资源加载器database-loader,由于在设计schema时没有考虑这种情况,加上去之后会报错,除非你修改schema,而这显然违反了OCP原则。

以springext schema方式装配ResourceLoadingService

SpringExt扩展了Spring,使Spring Schema具有了扩展能力,如果用SpringExt来定义相同的配置会是下面的样子:

<resource-loading id="resourceLoadingService"
     xmlns="http://www.alibaba.com/schema/services"
     xmlns:loaders="http:www.alibaba.com/schema/services/resource-loading/loaders">
     <resource pattern="/file">
          <loaders:file-loader basedir="${user.home}" />
     </resource>
     <resource>
          <loaders:webapp-loader />
     </resource>
</resource-loading>

如果要添加一种新的ResourceLoader--DatabaseResourceLoader,只需要两步:

1、配置maven依赖

2、在配置文件中添加配置项如下:

<resource>

     <loaders:database-loader connection="jdbc:mysql:mydb" />

</resource>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值