使用P名称空间配置属性

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


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值