代码如下:
清单1:bean
package com.spring.DI; public class IdRefTestBean { private String id; public String getId() { System.out.println("getter "+id); return id; } public void setId(String id) { System.out.println("setter "+id); this.id = id; } }
清单2:配置文件src/config/diconfig.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id = "bean1" class="java.lang.String"> <constructor-arg index="0" value="hello!"/> </bean> <bean id="bean2" class = "java.lang.String"> <constructor-arg index="0" value="world"/> </bean> <bean id = "idrefBean1" class="com.spring.DI.IdRefTestBean"> <property name="id"> <idref bean="bean1"/> </property> </bean> </beans>
清单3:junit测试
package com.spring.DI;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DITest {
@Test
public void test() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext(“config/diconfig.xml”);
IdRefTestBean idRefTestBean = beanFactory.getBean(“idrefBean1”,IdRefTestBean.class);
System.out.println(idRefTestBean.getId().toUpperCase());
String id = beanFactory.getBean(“bean1”,String.class);
System.out.println(id);
}
}
输出结果:
setter bean1
getter bean1
BEAN1
hello!
为什么这里获取到bean中的String类型的属性id的值不为设置的hello,而是bean的“bean1”?
求指导
20
<bean id = “idrefBean1″ class=”com.spring.DI.IdRefTestBean”>
<property name=”id” value=”hello”/>
</bean>
假如你非要这样做,可以把idref改为ref试试看。
20
<idref bean=”bean1″/>
</property>,这里相当于setID,而idref 相当于value=bean1,只是多了一个验证功能,判断上下文能否存在一个bean id为bean1的值存在。