为了账号安全,请及时绑定邮箱和手机立即绑定

请问为什么使用spring 3 jdbcTemplate 却总是null?

请问为什么使用spring 3 jdbcTemplate 却总是null?

斯蒂芬大帝 2022-01-05 20:07:49
web mvc 正常。只是dao层方面。我只写了一个类,没有接口,只是想做一下简单连接。代码如下:@Repositorypublic class TestDaoImp {private JdbcTemplate jdbcTemplate;@Autowiredpublic void setDataSource(@Qualifier(value="dataSource") DataSource dataSource) {this.jdbcTemplate = new JdbcTemplate(dataSource);}public void query() {// TODO Auto-generated method stubjdbcTemplate.queryForInt("select count(*) from bar_ip");}}然后是xml配置:<annotation-driven /><context:component-scan base-package="sdf.dsf" /><beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><beans:property name="driverClassName"><beans:value>com.mysql.jdbc.Driver</beans:value></beans:property><beans:property name="url"><beans:value>jdbc:mysql://localhost:3306/bar</beans:value></beans:property><beans:property name="username"><beans:value>root</beans:value></beans:property><beans:property name="password"><beans:value>125202505</beans:value></beans:property></beans:bean>在TestDaoImp 的query()方法中的jdbcTemplate总是为null。。。不知道为什么。。我是不是漏掉什么配置了???
查看完整描述

2 回答

?
繁花不似锦

TA贡献1851条经验 获得超4个赞

jdbcTemplate报空指针?
会不会setDataSource()没执行,检验一下
再确定<context:component-scan base-package="sdf.dsf" />搜索到了TestDaoImp 这个类
或者换换写法试试看吧
public void setDataSource(@Qualifier(value="dataSource") DataSource dataSource) {
this.dataSource=dataSource;
newJdbcTemplate();
}
public void newJdbcTemplate()
{
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
配置方面貌似没漏什么

 


查看完整回答
反对 回复 2022-01-10
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

你没有配置sessionFactory
可以参考一下
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="namingStrategy">
<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
<property name="packagesToScan" value="com.idos.entity" />
</bean>


查看完整回答
反对 回复 2022-01-10
  • 2 回答
  • 0 关注
  • 448 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号