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 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
newin any framework with dependency injection (so Spring Boot but also Quarkus, CDI, etc.) nothing will get injected. The framework doesn't hook itself in constructors, it calls those constructors when you inject instances of these classes.new MyClass("abc", "def"). If you want to inject dependency you need to injectabcanddefas properties and letSpringto createMyClassinstance.