为什么我的@Autowired DataSource和JdbcTemplate变为null?

时间:2019-04-21 22:09:05

标签: java spring-boot dependency-injection spring-jdbc

我正在尝试在配置类中定义数据源和jdbctemplate bean。每当我将它们自动连接到Restcontroller类中时,它们两个都将变为null。为什么?

在我的配置类中

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

}

内部restcontroller类

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


}

每次我尝试编译时,即使我没有手动实例化任何东西,也只是让spring通过自动装配管理所有实例,我都会从自动装配字段中得到空指针异常。

1 个答案:

答案 0 :(得分:0)

您尝试放入构造函数。并将它们设为私有。这样


private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

@Autowired
TestController (DataSource dataSource, JdbcTemplate jdbcTemplate){
    this.dataSource = dataSource;
    this.jdbcTemplate = jdbcTemplate;
}