Issue
I am trying to use an instance of object instantiated through @Autowire
inside a class with Runnable, but I am getting Null Pointer Exception
I went through href="https://stackoverflow.com/questions/38026330/autowired-not-working-inside-a-runnable">this thread but all the solution I tried and still its the same problem.
Sharing my code :
@Component
public class MyClass{
@Autowired
private ServiceA serviceA;
private String a;
private String b;
public MyClass() {
}
public MyClass(String a, String b) {
this.a = a;
this.b = b;
}
public Runnable newRunnable() {
return new Runnable() {
@Override
public void run() {
serviceA.innerMethod(a, b); //got NPE here
}
};
}
}
And I am calling this class runnable like this from other class
executor.submit(new MyClass("abc", "def").newRunnable());
So, am I doing something wrong, or is there any way where I could use the object
Solution
you are seeing NPE, coz ServiceA
is not injected in to your MyClass. And that is becoz you created MyClass
through new
keyword i.e new MyClass("abc", "def")
Try getting MyClass
also from container i.e
@Autowired MyClass myClass;
and use myClass
in the executor.
executor.submit(myClass.newRunnable());
Answered By - samshers
Answer Checked By - Senaida (JavaFixing Volunteer)