ref与idref的区别

首先谈谈idref,下面是官方文档给出的两个例子:
第一个:

<bean id="theTargetBean" class="..."/>

<bean id="theClientBean" class="...">
    <property name="targetName">
        <idref bean="theTargetBean" />
    </property>
</bean>

第二个:

<bean id="theTargetBean" class="..." />

<bean id="client" class="...">
    <property name="targetName" value="theTargetBean" />
</bean>

第一个例子的代码片段在运行时就完全同与第二个例子的效果,所以说idref取出并不是bean的实例,而是一个bean的name(一个字符串),和value的效果差不多,但是idrep多了验证的功能,减少了配置的书误几率,它会使xml解析器在解析XML的时候,对引用的bean进行验证,判断bean是否存在,而ref则是调用一个bean的实例。

如果你要用bean的实例,以使用ref,而当你仅仅需要获得bean的名称,则可以使用idref。

下面是我敲的xml的inref:

<bean id="user1" class="com.entity.user" scope="prototype">
<property name="name">
<idref bean="card1"/>
</property>
</bean>

<bean id="card1" class="com.entity.card">
<property name="uid" value="id" ></property>
<property name="cname" value="name"></property>
</bean>

测试运行代码及结果:

@Test
	public void createBean1() {
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
		user u1=(user) applicationContext.getBean("user1");
		System.out.println(u1.getName());
	}

下面是xml的ref:

<bean id="user1" class="com.entity.user" scope="prototype">
<property name="c">
<ref bean="card1"/>
</property>
</bean>

<bean id="card1" class="com.entity.card">
<property name="cname" value="name"></property>
</bean>

测试运行代码及结果:

@Test
	public void createBean2() {
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
		user u1=(user) applicationContext.getBean("user1");
		System.out.println(u1.getC().getCname());
	}

通过两段代码的运行结果就可以看出来ref和idref的区别,ref调用的是bean的实例,bean里面有什么都会被调用,而idref则调用的bean的name(一段字符串),但是相较于value属性,idref又具有验证判断效果,它会使xml解析器在解析xml的时候判断idref中的bean是否真的存在于容器中,不然就会报错。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值