I have 2 classes in my Spring-Boot
application:
-Tasks
-Runner
The runner class contains my main
method where I try to call a method from my Tasks class:
Runner:
@Component
public class Runner {
Tasks tasks;
@Autowired
public void setTasks(Tasks tasks){
this.tasks=tasks;
}
public static void main(String[] args){
//error being caused by below line
tasks.createTaskList();
}
Tasks Class:
@Service
public class Tasks {
public void createTaskList() {
//my code
}
//other methods
}
In my Runner, when I try to call the createTaskList() method in the Tasks class I get the following error:
Non static field 'tasks' cannot be referenced from a static context
How can I solve this?
The main method is static
meaning that it belongs to the class and not some object. As such, it a static context cannot reference an instance variable because it wouldn't know what instance of Runner
it would use if there even was one.
In short, the solution is to make your Tasks
object static
in the Runner
class.