spring - JDBC 模板问题 Nullpointer 异常
问题描述
我试图在我的 Spring Boot 项目中使用 JDBCTemplate 连接到 postgresql 数据库,但是当我尝试进行查询时出现空指针异常
应用程序属性
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://url/test
spring.datasource.username=postgres
spring.datasource.password=pass
Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
</dependencies>
代码
public class TestDaoImpl implements TestDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void testconnection() throws Exception {
// TODO Auto-generated method stub
int x=jdbcTemplate
.queryForObject("select count(*) from table", Integer.class);
System.out.println(x);
}
我无法检测出什么问题...请您帮帮我...提前致谢!
解决方案
@Bean
public JdbcTemplate jdbcTemplate(Datasource datasource){
JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
return jdbcTemplate;
}
您可以使用数据源配置 jdbcTemplate,然后您可以自动装配它。
您可以将代码块放入配置类
推荐阅读
- reactjs - 如何使用按钮使卡片在 React 中滑动?
- wordpress - 从 Bootstrap 4.0 升级到 4.5
- reactjs - React To-do List 添加类别
- r - 如何计算 R 中的 p 值?
- angular - 使用 angular-oauth2-oidc 的 Angular 和 OAuth 2 授权代码授权流程
- java - 使用基本身份验证在 Java 中获取和发布 API 调用
- arrays - 空手道:我可以迭代 Json 数组响应并执行一些条件语句吗
- c# - 从 base64 超时请求转换文件
- python - 为什么python在执行完成后会丢弃错误
- python - Google Colab - 如何比较两张照片