The issue is here
public ToDoItemDaoImpl() {
// dataSource is null here
insert = new SimpleJdbcInsert(dataSource).withTableName("toDoItem").usingGeneratedKeyColumns("id");
}
Spring can only autowire fields after the object has been created. That happens after the constructor is finished.
Spring will use reflection, ie. something like Class.forName(yourClass).newInstance()
, to create your bean and then again use reflection to set each property.
However, in your constructor, the field is still null
as that is the default value for all uninitialized fields of reference types.
One solution is to leave the constructor empty and add a @PostConstruct
annotated method
@PostConstruct
public void init() {
insert = new SimpleJdbcInsert(dataSource).withTableName("toDoItem").usingGeneratedKeyColumns("id");
}
Another solution is to add that initialization inside the setDataSource()
method.