8

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?

java123999
  • 6,974
  • 36
  • 77
  • 121
  • @ElliotFrisch, that post does not fully answer the OP's question. Since it is a spring boot application, the OP can't just create a static instance since injected beans are involved. – Hank D Apr 25 '16 at 13:54
  • Thanks @HankD, what else do you suggest? – java123999 Apr 25 '16 at 13:56
  • @ElliotFrisch, I would refer them to Krzysztof Wolny's answer to http://stackoverflow.com/questions/28199999/how-does-a-spring-boot-console-based-application-work. It shows them how to create a `main()` like non-static `run()` method that could access injected beans. – Hank D Apr 25 '16 at 13:59

1 Answers1

4

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.

Zircon
  • 4,677
  • 15
  • 32