-1

Trying to access Oracle database using JdbcTemplate with SpringBoot 2.1.4.RELEASE, but I am getting a null pointer exception

Tried below as per the SpringBoot documentation I still got null pointer exception.

@Component
public class DataAccessObject {

    private final JdbcTemplate jdbcTemplate;

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

    // ...

}

Null Pointer Exception is thrown in 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);
    }
}

whereas I am getting the circle count here

@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;
    }

}

Actually shouldn't I be getting the count at both the places ?

Number945
  • 4,631
  • 8
  • 45
  • 83
Beginner
  • 335
  • 2
  • 6
  • 17

1 Answers1

1

In the main method, you instantiate the DataAccessObject yourself. There is no Spring involved in the object creation and therefore autowiring doesn't work.

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

Try the following code instead:

public static void main(String[] args) {
    ApplicationContext context = SpringApplication.run(DatabaseDemoApplication.class, args);
    DataAccessObject dao = context.getBean(DataAccessObject.class);
    dao.getCircleCount();
}
Ilya Zinkovich
  • 4,082
  • 4
  • 25
  • 43