spring如何对普通类进行注入

spring如何对普通类进行注入

2009-05-12 22:37 10806080  |  浏览 3514 次
<bean id="xardDao"
  class="dao.impl.xardDaoImpl">
  <property name="hibernateTemplate">
   <ref bean="hibernateTemplate" />
  </property> 
 </bean>

 <bean id="xardService"
  class="service.impl.xardServiceImpl">
  <property name="xardDao">
   <ref bean="xardDao" />
  </property> 
 </bean>

现在想往一个普通类Test里注入xardService,
<bean id="Test"
  class="util.Text">
  <property name="xardService">
   <ref bean="xardService" />
  </property> 
 </bean>

这时候就在Test中报空指针异常了,显然注入没有成功,set方法也写了。
请教怎么往一个普通类里注入。这个类不是接口,没关系的吧。
从日志看出,服务器一启动的时候就帮我把applicationContext加载了
没有注入成功是因为命名需合乎sun规范,而且配置文件中必须和实际类中的变量名要满足一致的。
如:
<bean id="xardService" 
class="service.impl.xardServiceImpl"> 
<property name="xardDao"> 
<ref bean="xardDao" /> 
</property> 
</bean> 
那你的xardServiceImpl.java中必须有这样一个成员:
****
xardDaoImpl xardDao;
****
而且要有get,set方法。
那相似的,你的Text.java中必须有成员:
xardServiceImpl xardService;
提问者评价
大哥
评论  |  4  1

为您推荐:

按默认排序 | 按时间排序

其他3条回答

2009-05-13 11:58 80705041  | 六级
按照楼主这样说明应该没有问题

如果想解决的话,写一个测试类

applicationContext.xml这个文件如果在webRoot/WEB-INF下的话
测试类的里main方法这样写: ApplicationContext ctx = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
然后
Test t = (Test)ctx.getBean("Test");
t.foo();
//foo方法中打印下xardService
评论  |  0  0
2009-05-13 12:39 liyi830813  | 八级
从你发的部分来看好像没什么问题

最好是把错误提示发上来,检查有没有重复的bean,service中是否存在xardDao并且已经有get set方法(这个最好是用软件自动生成的)
评论  |  0  0
2009-05-13 03:33 user1temp  | 三级
不要接口一样可以.

有set方法,加上你的这段配置是没问题的.

问题是你要确定运行test类的时候,是否执行加载了applicationContext配置文件.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值