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
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();
}
}