Inheritance in Spring Boot: @Autowired fields are null (need autowiring in non spring managed class - multiple instances)

Viewed 5882

i've got Spring Boot with annotation based configuration running, but I#m pretty new to spring. I really could not find a solution to my problem elsewhere. I've got Task objects with the following inheritance structure:

  • ParentTask
    • SystemTask
    • UserTask
      • SpecificUserTask

Now I want to autowire some Repository to the SystemTask. Also I want to autowire the Repository and some Service to the UserTask (and all of its children).

How do I do this? With the following code I get a Null Pointer Exception.

the parent:

public abstract class ParentTask implements Runnable {

    // some fields

    protected ParentTask(/*fields*/) {
        //this.fields = fields;
    }

    @Override
    public abstract void run();

}

the first child:

public class SystemTask extends ParentTask {

    @Autowired
    protected SomeService someService;

    protected SystemTask(/*fields*/) {
        super(fields);
        //set some other fields
    }

    @Override
    public void run() {
        someService.doSomething(); // <-- nullPointerException
    }
}

the second child:

public abstract class UserTask extends ParentTask {

    @Autowired
    protected SomeService someService;
    @Autowired
    protected SomeRepository someRepository;

    protected UserTask(/*fields*/) {
        super(fields);
    }

    @Override
    public abstract void run();

}

child of UserTask (shall have the autowired ressources of UserTask)

public class SpecificUserTask extends UserTask{

    private SpecificUserTask (/*fields*/) {
        super(fields);
        //set some other fields
    }

    @Override
    public void run() {
        // do something
    }
}

My Repository is a standard mongo repository imlpementation and should not have any errors. My "someService" looks something like this:

@Service
public class SomeService{

    // some fields

    @Autowired
    private someOtherRepository someOtherRepository;

    // some methods

    public void doSomething() {
        //...
    }
}

So again my questions:

  1. How do I resolve the NullPointerException?
  2. How do I autowire fields in UserTask so they are available in SpecificUserClass?

Thank you all in advance.

EDIT: this is how I create a new Task whenever needed:

@Service
public class TaskAdministration {

    private final TaskAdministrationRepository taskAdministrationRepository;

    public void commissionSystemTask(fields) {

        SystemTask task = new SystemTask(fields);
        taskScheduler.schedule(task, taskTrigger);

        // persist task to restore if necessary
        taskAdministrationRepository.save(task);
    }
}
2 Answers
Related