I'm trying to perform a .findAll() on a repository interface that extends from CrudRepository. I'm trying to do this inside a @Async method using a @Autowire implementation of the repository. When I run the following code the @Async thread waits forever at the UpdateTasksService
List<Task> tasks = (List<Task>)taskRepo.findAll();
When I remove the @Async annotation from the updateTasks() method, the program runs as expected and prints all .toString() data.
My questions are:
- Why can't I use the
@Autowired TaskRepository taskRepo;inside a@Asyncmethod? - How can I use the repository inside a
@Asyncmethod?
Thank you in advance!
ScheduleComponent
@Component
public class ScheduleComponent {
@Autowired
UpdateTasksService updateTasks;
@PostConstruct
public void update(){
Future<Void> updateTasksFuture = updateTasks.updateTasks();
try {
updateTasksFuture.get();
System.out.println("Done");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
UpdateTaskService
@Service
public class UpdateTasksService {
@Autowired
TaskRepository taskRepo;
@Async
public Future<Void> updateTasks() {
System.out.println("The method starts");
List<Task> tasks = (List<Task>)taskRepo.findAll();
for(Task task: tasks){
System.out.println(task.toString());
}
return new AsyncResult<Void>(null);
}
}
TaskRepository
@Repository
public interface TaskRepository extends CrudRepository<Task, String> {
}