确保配置文件是正常的
spring.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=数据库名
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.username=名字
spring.datasource.password=密码
在测试文件里面出现 "this.dataSource" is null的话。看看有没有写@RunWith(SpringRunner.class)注解。如果没有加上这个注解,下面这些自动装配的注解,是不会自动装配的,也就是空引用。
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
import java.sql.SQLException;
@Component
@SpringBootTest
@RunWith(SpringRunner.class)
public class JDBCtest2 {
@Autowired
DataSource dataSource;
@Autowired
JdbcTemplate jdbc;
@Test
public void Test() throws SQLException {
System.out.println("默认数据源为:"+dataSource.getClass());
System.out.println("数据库链接实例:"+dataSource.getConnection());
Integer i = jdbc.queryForObject("select count(*) from loginTable",Integer.class);
System.out.println("表中共有:"+i);
}
}
如果是运行类出现空引用的话,我遇到的问题是
如果只在查询类声明
DataSource dataSource; JdbcTemplate jdbc;
,即使加了自动注入,也是不会自动加载配置的。所以还是空引用。
解决方法是加入一个构造函数,如下图所示。
然后在控制器类同样也声明数据源和JDBC对象
然后在控制器里面需要的函数进行构造函数的引用
大功告成