spring中bean的配置问题

爱喝啤酒的猴子 2016-10-22 08:36:09
做spring(spring4.2)小实验遇到一个问题:
代码如下:
清单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”?
求解
...全文
135 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 2 楼 Q_zx1bydcom 的回复:
<property name="id"> <idref bean="bean1"/> </property>,这里相当于setID,而idref 相当于value=bean1,只是多了一个验证功能,判断上下文是否存在一个bean id为bean1的值存在。
有点明白了,上面的网友说的对,spring提供的实现方式很多,没有必要纠结这些模棱两可的问题
小凤雏 2016-10-24
  • 打赏
  • 举报
回复
<property name="id"> <idref bean="bean1"/> </property>,这里相当于setID,而idref 相当于value=bean1,只是多了一个验证功能,判断上下文是否存在一个bean id为bean1的值存在。
晴天_ccc 2016-10-22
  • 打赏
  • 举报
回复
你为IdRefTestBean这个bean注入一个字符串而已,为什么要在spring容器中创建一个String对象,然后再注入到IdRefTestBean中呢?直接使用下面配置就行。 <bean id = "idrefBean1" class="com.spring.DI.IdRefTestBean"> <property name="id" value="hello"/> </bean> 如果你非要这样做,可以把idref改为ref试试看。

67,514

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧