Spring Framework自动连接的空指针异常 [英] Spring Framework Autowired Null Pointer Exception
问题描述
我正在学习Spring,但是在尝试建立一个相对基本的Spring项目时遇到了一些问题.我正在创建一个应用程序以简单地从数据库中读取数据,但是我在自动装配方面遇到了问题,或者缺少该问题.我的GetCustomerEvent
类在GetCustomers()
方法中引发了空指针异常,因为CustomerService
变量尚未初始化.有人可以在这里向我指出正确的方向吗?
I'm learning Spring and I'm having some problems trying to set up a relatively basic Spring project. I'm creating an application to simply read from a database, but I'm having problems with Autowiring, or lack thereof. My GetCustomerEvent
class is throwing a null pointer exception in the GetCustomers()
method, as the CustomerService
variable hasn't been initialised. Can someone point me in the right direction here?
Application.class
Application.class
package org.ben.test.main;
@Configuration
@ComponentScan(basePackages={"org.ben.test.persistence", "org.ben.test.main"})
public class Application {
@Bean
public CustomerService customerService() {
return new CustomerService();
}
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dmds = new DriverManagerDataSource();
dmds.setDriverClassName("org.postgresql.Driver");
dmds.setUrl("jdbc:postgresql://localhost:5432/Customers");
dmds.setUsername("postgres");
dmds.setPassword("postgres");
return dmds;
}
@Bean
public JdbcTemplate jdbcTemplate() {
DataSource ds = getDataSource();
JdbcTemplate jdbc = new JdbcTemplate(ds);
return jdbc;
}
public static void main(String[] args) {
GetCustomerEvent ev = new GetCustomerEvent();
ev.GetCustomers();
}
}
CustomerService.class
CustomerService.class
package org.ben.test.persistence;
@Component
public class CustomerService {
@Autowired JdbcTemplate jdbcTemplate;
public CustomerService() {
}
public void getCustomers() {
jdbcTemplate.query("SELECT * FROM Customers", new RowMapper() {
@Override
public Object mapRow(ResultSet arg0, int arg1) throws SQLException {
System.out.println(arg0.getString("firstName"));
return null;
}
});
}
}
GetCustomerEvent.class
GetCustomerEvent.class
package org.ben.test.persistence;
@Component
public class GetCustomerEvent {
@Autowired
CustomerService customerService;
public GetCustomerEvent() {
}
public void GetCustomers() {
customerService.getCustomers();
}
}
推荐答案
您没有初始化Spring容器.
You are not initializing the Spring Container.
您需要创建上下文以使其正常工作.
You need to create your context in order for it to work.
这篇关于Spring Framework自动连接的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!