0

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

arqam
  • 3,582
  • 5
  • 34
  • 69
  • 1
    Whenever you use `new` in 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. – Rob Spoor Aug 19 '22 at 14:53
  • It works like this because you created this instance manually - `new MyClass("abc", "def")`. If you want to inject dependency you need to inject `abc` and `def` as properties and let `Spring` to create `MyClass` instance. – Michał Ziober Aug 19 '22 at 14:53
  • @MichałZiober The values in the constructor I get at runtime and I need to spin multiple threads with different values, so multiple instance also I need. Is it possible to do that – arqam Aug 19 '22 at 15:24
  • @arqam, take a look here how to create a prototype bean with params: [Spring Java Config: how do you create a prototype-scoped Bean with runtime arguments?](https://stackoverflow.com/questions/22155832/spring-java-config-how-do-you-create-a-prototype-scoped-bean-with-runtime-argu) – Michał Ziober Aug 19 '22 at 16:48

1 Answers1

1

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());
samshers
  • 1
  • 6
  • 37
  • 84
  • But what if I want to create multiple instances of myClass with different values in the constructor at runtime to pass in the executor. Is it possible to do that? – arqam Aug 19 '22 at 15:22
  • - by default Bean scopes are singleton. But I see your point. I advice you to post a separate Q with the second part of your problem.. that is - `how to get multiple instances of MyClass with different FIELD VALUES when using spring IOC.`. If you do post a Q, plz do leave the link of it here so others viewing this Q will also benefit from it and might even help you. – samshers Aug 19 '22 at 15:47