Spring笔记――8.基于XML Schema的简化配置

我们可以使用XML Schema的配置方式来简化xml文件的配置。


p:简化设值注入

p:与property子元素作用相同,用于设值注入。若想使用p,则xml文件中需要引入对p的说明,一般自动生成的xml都会自带。xmlns:p="http://www.springframework.org/schema/p"

<bean id="chinese" class="com.cm.Aperson" p:age="29" p:axe-ref="stoneAxe" />

这种情况下p是bean的一个属性而非元素,axe后边加ref表明axe不是一个基本类型而是一个实例变量。


c:简化构造注入

c:能够简化构造注入,相当于constructor-arg子元素。需导入 xmlns:c="http://www.springframework.org/schema/c"

<bean id="chinese" class="com.cm.Aperson" c:age="29" c:axe-ref="stoneAxe" />

上面代码仅仅把p改成了c,表明age,axe都是构造函数的两个参数,框架会去自动找符合这两个参数的构造器。也可以使用下面的形式指明到底是第几个参数。

<bean id="chinese" class="com.cm.Aperson" c:_0="29" p:_1-ref="stoneAxe" />

在这种方式中,用_0代替了属性的名字(也是构造器中形参名字)。当传入实例变量时,也要加-ref。


util:命名空间

需要导入xmlns:util="http://www.springframework.org/schema/util"。 此命名空间提供了constant,property-path,list,set,map,properties元素,能够简化大多数xml配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/util
	http://www.springframework.org/schema/util/spring-util-4.0.xsd
	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
	<bean id="chinese" class="com.cm.Chinese" p:age-ref="chin.age"
		p:axe-ref="stoneAxe" p:schools-ref="chin.schools" />
	<util:constant id="chin.age"
		static-field="java.sql.Connection.TRANSACTION_SERILIZABLE" />
	<util:properties id="confTest" location="classpath:text_zh_CN.properties" />
	<util:list id="chin.schools" list-class="java.util.LinkedList">
		<value>小学</value>
		<value>初中</value>
		<value>高中</value>
	</util:list>
	<util:set id="chin.axes" set-class="java.util.HashSet">
		<value>字符串</value>
		<bean class="com.cm.SteelAxe" />
		<ref bean="stoneAxe" />
	</util:set>
	<util:map id="chin.scores" map-class="java.util.TreeMap">
		<entry key="Math" value="99" />
		<entry key="English" value="94" />
		<entry key="Chinese" value="90" />
		<entry key="Art" value="29" />
	</util:map>
</beans>

除此之外,Srping还有一些其他常用的Schema配置,比如aop,jee,jms,long和tx等。

本文出自 “指尖轻飞” 博客,谢绝转载!

你可能感兴趣的:(spring)