【发布时间】:2021-06-30 16:46:47
【问题描述】:
我有一个问题,我使用 JDBC 驱动程序创建了到 Oracle 数据库的连接。
我在互联网上找到的所有示例都使用如下:
@SpringBootApplication
public class CanalCorSdqsApplication implements CommandLineRunner{
public static void main(String[] args) throws Exception {
SpringApplication.run(CanalCorSdqsApplication.class, args);
}
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void run(String... args) throws Exception {
String sql = "SELECT * FROM USUARIO_WEBSERVICES";
List<UsuarioWebService> students = jdbcTemplate.query(sql,BeanPropertyRowMapper.newInstance(UsuarioWebService.class));
students.forEach(System.out :: println);
System.out.println(students.get(0).getLoginUsuario());
}
这也适用于我,但是当我尝试在另一个班级做同样的事情时,它会抛出
java.lang.NullPointerException:
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class ProcesoPrincipal implements CommandLineRunner {
@Autowired
private JdbcTemplate jdbcTemplate;
public void consulta(){
String sql = "SELECT * FROM USUARIO_WEBSERVICES";
List<UsuarioWebService> students = jdbcTemplate.query(sql,BeanPropertyRowMapper.newInstance(UsuarioWebService.class));
students.forEach(System.out :: println);
}
@Override
public void run(String... args) throws Exception {
String sql = "SELECT * FROM USUARIO_WEBSERVICES";
List<UsuarioWebService> students = jdbcTemplate.query(sql,BeanPropertyRowMapper.newInstance(UsuarioWebService.class));
students.forEach(System.out :: println);
}
在这两种方法中它都会抛出 java.lang.NullPointerException。
您知道发生了什么以及如何解决吗?
这是项目:
【问题讨论】:
-
这是您的整个应用程序吗?或者换句话说,这是minimal reproducible example?您能否也提供整个堆栈跟踪?
-
@MarkRotteveel 它的整个 cus 它现在是非常小的项目。只是一个对象(usuario)、主类和其他类。
-
这能回答你的问题吗? Why is my Spring @Autowired field null?
-
@caco3 我完全不明白。但我尝试了其中一些但不起作用:S。仍然为空。
-
您的代码中有
new ProcesoPrincipal()吗?如果是,那么您可以将new删除,将ProcesoPrincipal标记为@Component和@Autowired将其放到您需要的位置
标签: java spring spring-boot jdbc jdbctemplate