【发布时间】: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