spring如何对普通类进行注入

来源:互联网 发布:淘宝卖家信誉等级查询 编辑:程序博客网 时间:2024/05/21 22:35

spring如何对普通类进行注入

2009-05-12 22:3710806080 | 浏览 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加载了
2009-05-13 12:15提问者采纳
没有注入成功是因为命名需合乎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

山楂小子 | 六级 采纳率31%

擅长: JAVA相关 星座/运势 小说 数据库DB

为您推荐:

按默认排序 | 按时间排序

其他3条回答

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

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

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:39liyi830813 | 八级
从你发的部分来看好像没什么问题

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

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

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

0 0
原创粉丝点击