0

I'm trying to define datasource and jdbctemplate beans inside a configuration class. How ever whenever I autowire them into Restcontroller class both of them gets null. Why?

inside my config class

@Configuration
@ComponentScan({ "org.airi.airibot.controllers", "org.airi.airibot.configs" })
public class DatabaseConfig {
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgres://localhost:5432/testdb");
        dataSource.setUsername("testuser");
        dataSource.setPassword("testpassword");
        return dataSource;
    }

    @Bean
    public SimpleJdbcCall spCall() {
        SimpleJdbcCall sp_call = new SimpleJdbcCall(dataSource());
        return sp_call;
    }


    @Bean public JdbcTemplate jdbcTemplate() { 
        JdbcTemplate jdbc_template = new JdbcTemplate(dataSource()); 
        return jdbc_template; 
    }

}

inside restcontroller class

@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class TestController {

    @Autowired
    public DataSource dataSource;

    @Autowired
    public JdbcTemplate jdbcTemplate;

    private List<DiscordServer> servers = createList();

    @RequestMapping(value = "/server-emotes", method = RequestMethod.GET, produces = "application/json")
    public List<DiscordServer> getServers() {
        return servers;
    }

    private List<DiscordServer> createList() {
        List<DiscordServer> temp_servers = new ArrayList<>();

        //TODO: logic to add servers

        System.out.println(dataSource);
        return temp_servers;
    }


      public int getCountOfServers() { 
          int server_count = jdbcTemplate.queryForObject( "SELECT COUNT(*) FROM DISCORD_SERVER",Integer.class); 
          return server_count; 
      }


}

Each time I try to compile I get null pointer exception coming from the autowired fields even if I didn't instantiate anything manually and just let spring manage all instances by autowiring.

  • Spring can't inject anything until after the instance has been created and initialized. Your `createList` is being invoked before Spring has had a chance to operate on the instance. – Sotirios Delimanolis Apr 21 '19 at 22:32

1 Answers1

0

Did you try to put to constructor. And make them private. Like that


private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

@Autowired
TestController (DataSource dataSource, JdbcTemplate jdbcTemplate){
    this.dataSource = dataSource;
    this.jdbcTemplate = jdbcTemplate;
}
Konstantin
  • 11
  • 3
  • Hi @konstantin. I've just tried your solution but I'm still getting the same issue. Both of the beans are still null in the controller class. – Marvin Borromeo Apr 21 '19 at 22:31