1. 程式人生 > >spring的xml中p名稱空間與C名稱空間簡化屬性賦值

spring的xml中p名稱空間與C名稱空間簡化屬性賦值

p名稱空間與C名稱空間簡化屬性賦值

Spring給我們提供的一種比較簡便的方式來為我們的屬性賦值

P名稱空間用於簡化set方法的屬性賦值

C名稱空間用於簡化構造器的屬性賦值

第一步:加上我們的P名稱空間C名稱空間

<?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:c="http://www.springframework.org/schema/c"

    xsi:schemaLocation="

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

第二步配置xml

<!-- 通過p名稱空間來簡化我們的set方法的屬性賦值 -->

<bean id="personImpl2" class="cn.itcast.spring.demo5.PersonImpl"

 p:age="10" p:personName="tom222" p:birthday-ref="date"></bean>

第三步:測試用例

/**

 * 通過p名稱空間來簡化我們的屬性賦值

 */

@Test

publicvoid getPersonImpl2() throws Exception {

//獲取容器

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

PersonImpl bean = (PersonImpl) context.getBean(

"personImpl2");

System.out.println(bean.toString());

}

通過C名稱空間來簡化我們構造方法的屬性賦值

第一步xml當中的定義

<!-- -通過C名稱空間來簡化我們的構造器的屬性賦值 -->

<bean id="tomImpl3" class="cn.itcast.spring.demo6.TomImpl" c:tomName="jerry" c:color="棕色" c:sex="male" c:tomAge="15"></bean>