今天一同學問我Spring的p名稱空間怎麼用,我一下子也給忘了,哎,剛學完Struts2,Sping就忘了,趕緊翻書複習一下,但一看書其實也蠻簡單的p名稱空間直接存在Spring
內核中,與採用<property.../>元素定義Bean的屬性不同的是,採用P名稱空間之後,就可以直接在<bean.../>元素中使用屬性來定義Bean實例的屬性值了。
趕緊寫個例子複習一下。
從書上找到的很簡單的例子,因爲簡單易懂,記得牢麼,首先是兩個接口Person接口和Axe接口
package org.sun.service;
public interface Person {
//定義一個使用斧子的方法
public void userAxe();
}
package org.sun.service;
public interface Axe {
//Axe接口有個砍的方法
public String chop();
}
Chinese實現Person接口,StoneAxe實現Axe接口
package org.sun.service.impl;
import org.sun.service.Axe;
public class StoneAxe implements Axe {
@Override
public String chop() {
return "石斧砍柴好慢";
}
}
package org.sun.service.impl;
import org.sun.service.Axe;
import org.sun.service.Person;
public class Chinese implements Person{
private Axe axe;
private int age;
public Axe getAxe() {
return axe;
}
//設值注入axe屬性所需的setter方法
public void setAxe(Axe axe) {
this.axe = axe;
}
public int getAge() {
return age;
}
//設置注入age屬性所需的setter方法
public void setAge(int age) {
this.age = age;
}
//實現Person接口的userAxe方法
@Override
public void userAxe() {
//調用axe的chop()方法
//表明Person對象依賴於axe對象
System.out.println(axe.chop());
System.out.println("age屬性值:"+age);
}
}
配置文件ApplicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- 配置chinese實例,其實現類是Chinese-->
<bean id="chinese" class="org.sun.service.impl.Chinese" p:age="29" p:axe-ref="stoneAxe"/>
<!-- 配置stoneAxe實例,其實現類是StoneAxe-->
<bean id="stoneAxe" class="org.sun.service.impl.StoneAxe"/>
</beans>
配置test類並運行查看結果
有個問題要注意,如果某個Bean的屬性名是以“ref”結尾的,那麼採用P名稱空間定義時就會導致衝突。