老师使用注解方式配置jdbcTemplate是不是哪里配置错了
我直接使用提供的源码测试查询功能,报空指针异常
打印测试一下,发现jdbcTemplate是null,没有找出错误在哪?
28
收起
正在回答
3回答
老师在课程讲解的方式和同学使用的测试方式类似,但是不全部相同;
老师在测试Test类中通过下面代码:
private JdbcTemplate jdbcTemplate;
{
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
}对JdbcTemplate 进行了初始化;
同学使用的方式没有获取JdbcTemplate 对象;
修改建议:在StudentDaoImpl类中的select方法中获取到JdbcTemplate 对象,然后再对其进行操作
public Student select(int id) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
System.out.println(jdbcTemplate);
String sql = "select * from student where id=?";
return jdbcTemplate.queryForObject(sql, new StudentRowMapper(), id);
}测试类中可以接收一下查询结果并打印观察一下:
@org.junit.Test
public void demo1() {
StudentDao studentDao = new StudentDaoImpl();
Student student=studentDao.select(1005);
System.out.println(student);
}另外:建议同学下次提问时,能够将代码粘贴出来并进行格式化,最好不要截图,不要粘贴在回复中,方便调试你的代码帮助你解答问题。
祝学习愉快!
SSM主流框架入门与综合项目实战2018版
- 参与学习 人
- 提交作业 205 份
- 解答问题 4317 个
Java中非常实用的SSM整合开发内容,从Spring开始,到MyBaits的进阶内容,再到SpringMVC的应用,最后是SSM整合开发案例,逐步深入,助你成长为一名Java工程师!
了解课程


恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星