DBUtil
public class DBUtil {
@Autowired
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Test
public void queryUser() {
List<Map<String, Object>> list = jdbcTemplate.queryForList("select user_login,email from users limit 3");
System.out.println(list);
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
jdbcTemplate是需要注入到Spring容器中的,在你的配置中也看到了,已经注入了,但是你在测试的时候是在Test修改的方法上测试的,此时项目并没有启动,JdbcTemplate没有注入到spring容器中,所以你获取到了null,哈哈哈
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/spring.xml" })
public class DBUtil {
...
}
这样试一试
你有没有加载applicationContext.xml配置文件?
这是JUnit测试用例?你要想jdbcTemplate能注入用例的话DBUtil 也要交给Spring容器管理的
看看SpringTest使用说明
你的DBUtil需要是被spring管理的类才能注入jdbcTemplate,加个@Component注解试试,然后从springContext中加载这个bean
有没有加载applicationContext.xml配置文件
测试用例需要手动加载一下配置文件,ClassPathXmlApplicationContext c=new ClassPathXmlApplicationContext("配置文件");