已经在spring配置文件中配置了jdbcTemplate的bean,但是在测试类中jdbcTemlpate的注入报空指针
<?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.xsd ">
<!-- 配置spring的jdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 设置spring扫包路径 -->
<context:component-scan base-package="com.hzbckj.spring" />
<!-- 导入资源文件 -->
<context:property-placeholder location="db.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
</bean>
</beans>
这是spring配置文件
package com.hzbckj.spring.test;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* Created by jackson on 2017/2/6.
*/
@Component
public class dataSourceTest {
@Resource(name = "jdbcTemplate")
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Test
public void testJdbc(){
// ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// JdbcTemplate jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate");
String sql = "INSERT INTO user(name, balance) values('Jonn', 200)";
jdbcTemplate.execute(sql);
}
}
这是使用的地方
执行时jdbcTemplate一直报空