什么是Spring的命名空间及使用Spring 的命名空间p 装配属性

这个就要从XML说了,Spring的配置管理可以利用XML方式进行配置,而XML里面就有命名空间这个概念。。实际上就和标签的意思有点像 你给一个命名空间以后,这个XML文件里面就可以用那个命名空间上下文里面的标签了。简化配置用,你可以去看看Spring AOP用命名空间和不用命名空间的配置有什么区别。

使用Spring 的命名空间p 装配属性

使用<property> 元素为Bean 的属性装配值和引用并不太复杂。尽管如此,Spring 的命名空间p 提供了另一种Bean 属性的装配方式,该方式不需要配置如此多的尖括号。

命名空间p 的schema URI 为http://www.springframework.org/schema/p。如果你想使用命名空间p,只需要在Spring 的XML 配置中增加如下一段声明:

 
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans 
  6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

通过此声明,我们现在可以使用p: 作为<bean> 元素所有属性的前缀来装配Bean 的属性。为了示范,我们重新声明了kenny Bean 的配置:

 
 
  1. <bean id="kenny" class="com.springinaction.springidol.Instrumentalist"
  2. p:song = "Jingle Bells"
  3. p:instrument-ref = "saxophone" />

p:song 属性的值被设置为“Jingle Bells”,将使用该值装配song 属性。同样,p:instrument-ref 属性的值被设置为“saxophone”,将使用一个ID 为saxophone 的Bean 引用来装配instrument 属性。-ref 后缀作为一个标识来告知Spring 应该装配一个引用而不是字面值。

选择<property> 还是命名空间p 取决于你,它们是等价的。命名空间p 的最主要优点是更简洁。在固定宽度的纸张上编写样例时,选择命名空间相对更合适。因此,在本书中你可能看到我不时的使用命名空间p,特别是水平页面空间比较紧凑时。

 

Spring 的配置文件中,有一个配置文件头:

 
 

<beans xmlns=”http://www.springframework.org/schema/beans”
xsi:schemaLocation=”

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”>

这表明,在当前配置文件中,使用的是beans命名空间,可以直接使用<bean id=”">。

如果要在这个配置文件中使用mvc命名空间下的annotation-driven元素,要写为<mvc:annotation-driven/>,当然,还需要告诉xml解析器,mvc这个命名空间是在哪里定义的,以便解析器能够验证当前文件中mvc:开头的元素是否符合mvc命名空间的:

复制代码

 
 

<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:mvc=”http://www.springframework.org/schema/mvc”
xsi:schemaLocation=”

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd”>

复制代码

这样解析器在解释mvc:命名空间的时候,会参考spring-mvc-3.0.xsd这个文件来检验<mvc:annotation-driven/>是否合格。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值