[英]Spring Framework Autowired Null Pointer Exception
我正在學習Spring,但是在嘗試建立一個相對基本的Spring項目時遇到了一些問題。 我正在創建一個應用程序以簡單地從數據庫中讀取數據,但是我在自動裝配方面遇到問題,或者缺少該問題。 我的GetCustomerEvent
類在GetCustomers()
方法中GetCustomers()
了空指針異常,因為尚未初始化CustomerService
變量。 有人可以在這里指出正確的方向嗎?
應用程序類
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
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
package org.ben.test.persistence;
@Component
public class GetCustomerEvent {
@Autowired
CustomerService customerService;
public GetCustomerEvent() {
}
public void GetCustomers() {
customerService.getCustomers();
}
}
問題在於下面的線
GetCustomerEvent ev = new GetCustomerEvent();
您使用“新”手動創建了實例。 Spring沒有關於此對象的想法。 請參閱為什么我的Spring @Autowired字段為空? 有關詳細信息。
您沒有初始化Spring容器。
您需要創建上下文以使其起作用。
無論使用的是xml還是基於注釋的配置,都需要創建應用程序上下文。 如果您的應用程序是Web應用程序,請參閱這篇文章在Spring中使用web.xml加載上下文以加載應用程序上下文
一旦有了應用程序,就可以使用context.getBean()
方法獲取bean。
而且,spring容器不管理使用new運算符創建的對象。 在您的示例中,您需要自動連接GetCustomerEvent bean
@Autowired GetCustomerEvent getCustomerEvent;
//and call
getCustomerEvent.getCustomers();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.