p 命名空間允許你使用 bean 元素的屬性而不是 <property/>子元素來描述 Bean 實例的屬性值。從 Spring2.0 開始,Spring 支持基于 xml Schema 的方式來簡化配置文件。beans 元素的結構定義在一個 XML Schema 文檔中。但是,p 命名空間沒有定義在 XSD 文件中,而是直接存在與 Spring 內核中。使用p 命名空間時,只需要在配置文件根元素beans 引入 xmlns:p="http://www.springframework.org/schema/p"。
p 命名空間配置的示例:
<?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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="magicWand" class="com.huey.dream.bean.Weapon" p:type="Magic Wand" p:weightKg="9.5" /> <bean id="magician" class="com.huey.dream.bean.GameCharacter" p:type="Magician" p:level="10" p:weapon-ref="magicWand" /> </beans>
上述的配置與如下的配置等價:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="magicWand" class="com.huey.dream.bean.Weapon"> <property name="type" value="Magic Wand" /> <property name="weightKg" value="9.5" /> </bean> <bean id="magician" class="com.huey.dream.bean.GameCharacter"> <property name="type" value="Magician" /> <property name="level" value="10" /> <property name="weapon" ref="magicWand" /> </bean></beans>c 命名空間
c 命名空間 與 p 命名空間用法類似,不同是 p 命名空間作用于屬性注入,而 c 命名空間作用于構造注入。
p 命名空間配置的示例:
<?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:c="http://www.springframework.org/schema/c" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="magicWand" class="com.huey.dream.bean.Weapon" c:type="Magic Wand" c:weightKg="9.5" /> <bean id="magician" class="com.huey.dream.bean.GameCharacter" c:type="Magician" c:level="10" c:weapon-ref="magicWand" /></beans>
上述的配置與如下的配置等價:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="magicWand" class="com.huey.dream.bean.Weapon"> <constructor-arg name="type" value="Magic Wand" /> <constructor-arg name="weightKg" value="9.5" /> </bean> <bean id="magician" class="com.huey.dream.bean.GameCharacter"> <constructor-arg name="type" value="Magician" /> <constructor-arg name="level" value="10" /> <constructor-arg name="weapon" ref="magicWand" /> </bean></beans>
新聞熱點
疑難解答