spring中的idref元素
idref元素是一个简单的对容器中存在的另外一个bean的检错途径(通过id);
<idref
bean="someBeanId"/> ,不同于<ref/>
someBeanId注入的是一个字符串,相当于:
<property
name="targetName" value="someBeanId"/>
如果"someBeanId"不是其中一个bean的ID,将会报BeanDefinitionStoreException
详细代码如下:
配置文件:idref_check.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.xsd"> <bean id="shihaofengqiu"
class="beans.Song"
p:title="十号风球"/> <bean id="xiaoming"
class="beans.Singer">
<property name="name" value="xiaoming"/>
<!--<property name="song" value="mrfanl"/>-->
<property name="song">
<!--<idref bean="mrfanl"/>--><!--报错-->
<idref bean="shihaofengqiu"/><!--通过-->
</property>
</bean>
</beans>
performer.java
package beans; public interface Performer {
public void play();
}
Singer.java
package beans; public class Singer implements Performer { private String name;
private String song; public Singer() { } public void setName(String name) {
this.name = name;
} public void setSong(String song) {
this.song = song;
} @Override
public void play() {
System.out.println("my name is:"+this.name);
System.out.println("my song is:"+this.song); }
}
Song.java
package beans; public class Song {
private String title; public Song(){} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
}
}
test.java
package main; import beans.Performer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class test {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("idref_check.xml");
Performer xiaoming = (Performer) ctx.getBean("xiaoming");
xiaoming.play();
}
}
结果: