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();
}
}
You need to create the application context no matter if you are using xml or annotation based configuration. If your application is a web application, see this post Loading context in Spring using web.xml to load the application context
Once you have the application you can get the bean using
context.getBean()
methodAlso, spring container does not manage the objects you create using new operator. In your example you need to autowire the GetCustomerEvent bean
Problem is with below line
You manually created instance using "new". Spring does not have idea about this object. See Why is my Spring @Autowired field null? for details.
You are not initializing the Spring Container.
You need to create your context in order for it to work.