【问题标题】:JdbcTemplate is null in Springboot application using Oracle 10gJdbcTemplate 在使用 Oracle 10g 的 Springboot 应用程序中为空
【发布时间】:2023-01-08 01:00:40
【问题描述】:

使用弹簧引导 2.7.2 错误 -java.lang.NullPointerException:无法调用“org.springframework.jdbc.core.JdbcTemplate.query(String, org.springframework.jdbc.core.RowMapper)”因为“this.jdbcTemplate”为空


@Service
public class UserServiceImpl implements UserService {
.....
    @Autowired
    private UserDao userDao;

}

@Component
public class UserDaoImpl implements UserDao {
    
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public UserDaoImpl(JdbcTemplate jdbcTemplatn) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    @Override
    public  List<AttributeData> getAttributes() {
        String query = "select attributeid, ....";
        List<AttributeData> attributes = jdbcTemplate.query(query, new AttributeMapper());
        return attributes;
    }
}

application.properties :
# Oracle db related
spring.datasource.url=jdbc:oracle:thin:@localhost....
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

# JPA related
oracle.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none

【问题讨论】:

    标签: java oracle spring-boot


    【解决方案1】:

    只是意味着您没有定义 JdbcTemplate 的 @Bean,例如

    @Bean
    public JdbcTemplate jdbcTemplate() throws SQLException {
        final JdbcTemplate template = new JdbcTemplate();
        template.setDataSource(dataSource());
        template.afterPropertiesSet();
        return template;
    }
    

    【讨论】:

      【解决方案2】:

      表示尝试在 JdbcTemplate 实例上调用查询方法时抛出 NullPointerException,但实例变量 jdbcTemplate 为 null。

      要解决此问题,您需要在尝试使用之前初始化 jdbcTemplate 字段。这可以通过使用 @Autowired 注释将 JdbcTemplate bean 注入到您的类中或通过使用适当的构造函数创建 JdbcTemplate 的新实例来完成。

      下面是一个示例,说明如何将 JdbcTemplate bean 注入到您的类中:

      @Autowired
      private JdbcTemplate jdbcTemplate;
      

      下面是一个示例,说明如何创建 JdbcTemplate 的新实例:

      private JdbcTemplate jdbcTemplate = new JdbcTemplate();
      

      正确初始化 jdbcTemplate 字段后,您应该能够调用查询方法而不会遇到 NullPointerException。

      我建议查看 JdbcTemplate 和 @Autowired 注释的文档,以获取有关如何使用这些类的更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-26
        • 2010-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多