如何在springboot中自动连接jdbcTemplate?

时间:2019-05-08 17:33:46

标签: java spring-boot jdbctemplate

尝试在SpringBoot 2.1.4.RELEASE中使用JdbcTemplate访问Oracle数据库,但出现空指针异常

下面根据SpringBoot文档进行了尝试,但仍然出现空指针异常。

@Component
public class DataAccessObject {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public DataAccessObject(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // ...

}

在getCircleCount()中引发了空指针异常

@Component
public class DataAccessObject {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void getCircleCount() {
        int count = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM CIRCLE", Integer.class);
        System.out.println(count);
    }
}

我在这里得到圈数

@SpringBootApplication
@ComponentScan("org.vinodh.camunda")
public class DatabaseDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DatabaseDemoApplication.class, args);
        DataAccessObject dao = new DataAccessObject();
        dao.getCircleCount();
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext context) {
        JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
        int count = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM CIRCLE", Integer.class);
        System.out.println(count);
        return null;
    }

}

实际上我不应该在两个地方都得到计数吗?

1 个答案:

答案 0 :(得分:1)

在main方法中,您可以自己实例化DataAccessObject。没有Spring参与对象的创建,因此自动装配不起作用。

public static void main(String[] args) {
    SpringApplication.run(DatabaseDemoApplication.class, args);
    DataAccessObject dao = new DataAccessObject();
    dao.getCircleCount();
}

请尝试以下代码:

public static void main(String[] args) {
    ApplicationContext context = SpringApplication.run(DatabaseDemoApplication.class, args);
    DataAccessObject dao = context.getBean(DataAccessObject.class);
    dao.getCircleCount();
}