【问题标题】:Why is my @Autowired DataSource and JdbcTemplate getting null? [duplicate]为什么我的 @Autowired DataSource 和 JdbcTemplate 为空? [复制]
【发布时间】:2019-04-21 22:09:04
【问题描述】:

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

在我的配置类中

@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 通过自动装配来管理所有实例。

【问题讨论】:

  • 在实例创建和初始化之前,Spring 不能注入任何东西。在 Spring 有机会对实例进行操作之前,您的 createList 已被调用。

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


【解决方案1】:

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


private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

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

【讨论】:

  • 嗨@konstantin。我刚刚尝试了您的解决方案,但我仍然遇到同样的问题。两个 bean 在控制器类中仍然为空。
猜你喜欢
  • 2014-06-21
  • 2022-01-04
相关资源
最近更新 更多