猿问

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

web mvc 正常。只是dao层方面。我只写了一个类,没有接口,只是想做一下简单连接。代码如下:
@Repository
public class TestDaoImp {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier(value="dataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}

public void query() {
// TODO Auto-generated method stub
jdbcTemplate.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。。。不知道为什么。。
我是不是漏掉什么配置了???

斯蒂芬大帝
浏览 449回答 2
2回答

繁花不似锦

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);}配置方面貌似没漏什么&nbsp;

繁星点点滴滴

你没有配置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>
随时随地看视频慕课网APP
我要回答