无法从静态context-Main方法引用非静态字段

jav*_*999 7 java methods static program-entry-point class

我的Spring-Boot应用程序中有2个类:

-任务

-Runner

runner类包含我的main方法,我尝试从Tasks类中调用一个方法:

亚军:

@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();

    }
Run Code Online (Sandbox Code Playgroud)

任务类:

@Service
public class Tasks {

    public void createTaskList() {

    //my code
    }


    //other methods 


}
Run Code Online (Sandbox Code Playgroud)

在我的Runner中,当我尝试在Tasks类中调用createTaskList()方法时,我收到以下错误:

Non static field 'tasks' cannot be referenced from a static context
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

Zir*_*con 4

main 方法static意味着它属于类而不是某个对象。因此,静态上下文无法引用实例变量,因为Runner即使存在实例变量,它也不知道将使用哪个实例。

简而言之,解决方案是将您的Tasks对象放入类staticRunner