Search code examples
javanullpointerexceptionguice

Nullptr exception after Guice injection


I am kinda new to Guice injection. And I got nullptr exception in my project.

I suspect it is because I do not set up Injecting dependencies correctly.

After investigation, it is caused by invokeSomeMethod in S3Driver.java file, specifically lambdaHelper.invokeSomeMethod().

Could you shed some hints about what went wrong?

Thank you

S3Driver.java

// Constructor
public S3Driver() {
             Injector injector = createInjector(new LambdaHelperModule(), new S3Module());
             this.lambdaHelper = injector.getInstance(LambdaHelper.class);
}

...
lambdaHelper.invokeSomeMethod(); // Nullptr Exception

This is my project setup:

LambdaHelper.java

// Constructor
public LambdaHelper(S3Class s3Class) {
  this.s3Class = s3Class;
}

S3Class.java

...
// Constructor
public S3Class(S3Presigner p, S3Client s) {this.p = p; this.s = s;};

LambdaHelperModule.java

public LambdaHelper provideLambdaHelper() {
             S3Class s3Class = S3Class.builder()
                                         .s3Presigner(S3Presigner.builder().build())
                                         .s3Client(S3Client.builder().build())
                                         .build();
             return new LambdaHelper(s3Class);
}

S3Module.java

public S3Class provideS3Class() {
             return new S3Class(S3Presigner.builder().build(),
                                 S3Client.builder().build());
}

Solution

  • Add @Provides to your provider methods

    Your methods provideLambdaHelper() and provideS3Class() should definitely be annotated with @Provides. This will allow Guice to know that they're supposed to be your provider, so Guice will call them when you want to inject such instances.

    So your code should be:

    @Provides
    public LambdaHelper provideLambdaHelper() {
      ...
    }
    

    And

    @Provides
    public S3Class provideS3Class() {
      ...
    }