不能从静态上下文中引用非静态字段 - Main 方法
Non static field cannot be referenced from a static context- Main method
我的 Spring-Boot
申请中有 2 个 classes:
-任务
-亚军
runner class 包含我的 main
方法,我尝试从我的任务 class:
中调用方法
亚军:
@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();
}
任务Class:
@Service
public class Tasks {
public void createTaskList() {
//my code
}
//other methods
}
在我的 Runner 中,当我尝试在任务 class 中调用 createTaskList() 方法时,出现以下错误:
Non static field 'tasks' cannot be referenced from a static context
我该如何解决这个问题?
主要方法是 static
意味着它属于 class 而不是某个对象。因此,静态上下文不能引用实例变量,因为它不知道 Runner
如果有的话它会使用哪个实例。
简而言之,解决方案是让你的 Tasks
对象 static
在 Runner
class.
我的 Spring-Boot
申请中有 2 个 classes:
-任务
-亚军
runner class 包含我的 main
方法,我尝试从我的任务 class:
亚军:
@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();
}
任务Class:
@Service
public class Tasks {
public void createTaskList() {
//my code
}
//other methods
}
在我的 Runner 中,当我尝试在任务 class 中调用 createTaskList() 方法时,出现以下错误:
Non static field 'tasks' cannot be referenced from a static context
我该如何解决这个问题?
主要方法是 static
意味着它属于 class 而不是某个对象。因此,静态上下文不能引用实例变量,因为它不知道 Runner
如果有的话它会使用哪个实例。
简而言之,解决方案是让你的 Tasks
对象 static
在 Runner
class.