【问题标题】:How to use jdbcTemplate in another class than main class?如何在除主类之外的另一个类中使用 jdbcTemplate?
【发布时间】: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


【解决方案1】:

您需要将@Service@Component 添加到ProcesoPrincipal 类中。

【讨论】:

  • 我都试过了,但没有用。你有其他想法吗?
【解决方案2】:

您的新类实现了 CommandLineRunner。为什么?起飞实现 CommandLineRunner。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 2020-10-07
    • 2022-01-12
    • 2013-11-06
    • 2012-09-06
    • 1970-01-01
    • 2013-05-09
    相关资源
    最近更新 更多