今天一同学问我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名称空间定义时就会导致冲突。