Search code examples
javadependency-injectionnullpointerexceptionjerseyhk2

@inject doesn't seem to work NPE when injecting an object


I've been struggling with this issue for a while now, so I came here to share it with you. First I have a class in which I want to inject an Object:

public class MyClass {
 @javax.inject.Inject
 private MyInterface interface
       /.../
public void myMethod(){
interface.doTask();
}

The MyInterface :

public interface MyInterface {

    public abstract void doTask() throws Exception;
}

is an interface which I bind to its implementation:

public class MyInterfaceImpl implements MyInterface{
  @Inject
   public MyInterfaceImpl(...) {
       /.../
    }
  @Override
   public void doTask() throws Exception{
      /.../
}

in the Config:

public class ApplicationConfig extends ResourceConfig {
 private Config config = new Config();

    public ApplicationConfig() {
        super();
        register(new MainBinder());
}
    private class MainBinder extends AbstractBinder {
         @Override
         protected void configure() {
      bind(MyInterfaceImpl.class).to(MyInterface.class).in(Singleton.class);
        }
    }
}

So, when I run the app and try to execute the method I have a NPE on:

interface.doTask();

Voilà, I am sorry to ask but I need some help on that, plus I've tried to be as generic as possible hoping it didn't impact your comprehension.

Edit:
Forgot to mention that the class MyClass() is called in another class like this: new MyClass()

So I think the problem might be there.


Solution

  • So I figure it out! I was creating a new instance of myClass => new MyClass() thus the injection couldn't work! So I injected the MyClass() instead of creating a new instance and bound it in the ApplicationConfig. This worked fine.