您的位置:首页 > 编程语言 > Java开发

spring如何对普通类进行注入

2016-04-21 18:21 537 查看




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


其他类似问题

2009-06-26spring
依赖注入怎么来理解?75

2010-02-02spring
中,能不能为抽象类注入属性?15

2012-11-13spring注解方式在一个普通的java类里面注入dao9

2012-02-21Spring
能否对普通类注入接口,报错

2012-03-26spring的依赖注入怎么理解157

2013-05-01用
TestCase 对 Spring 的 Bean 进行单元测试 [百度文库] 63

更多相关问题>>


为您推荐:

按默认排序 | 按时间排序


其他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配置文件.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: