0

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());
}
xiaokang lin
  • 153
  • 1
  • 10
  • 1
    See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) -- Note: the first link should explain why we need a [mre] and the stack trace in order to be able to help. The second becomes more specific about solving an NPE. – Andrew Thompson Jun 16 '21 at 00:43
  • add null check before invoking method on lamdaHelper, `if(lambdaHelper !=null) {lambdaHelper.invokeSomeMethod();}` – sanjeevRm Jun 16 '21 at 00:43
  • check the value of `lamdaHelper` after the line `this.lambdaHelper = injector.getInstance(LambdaHelper.class);` in `S3Driver` constructor – sanjeevRm Jun 16 '21 at 00:45
  • @AndrewThompson I reopened because NullPointerException are very specific in the Guice context and just a simple wrong configuration item can cause such issue. And since it's configuration and not code, it's hard to find. – Olivier Grégoire Jun 16 '21 at 07:52

1 Answers1

1

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() {
  ...
}
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137