0
votes

I'm using Guice for dependency injection but In my specific use case it is giving me this error:

Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private

I've spent a lot of time on this but I'm still unable to understand why it's not able to inject dependency. Can anyone have a look at it?

My class structure is as follows:

interface A {
}

Class B implements A

Class B implements A {

  @Inject
  B(String para1, MyClass B) {
     // do something
  }

}

Guice Module is as:

@AllArgsConstructor
public class GuiceModule extends AbstractModule {

@Override
protected void configure() {

    bind(A.class).to(B.class);

}

@Provides
public MyClass provideMyClass() {
    return new MyClass();
}


@Provides
public String provideString() {
    return "string";
}
}

In Some other class I'm doing:

@Inject A a;
1
I tried to run your code from main method: A a = Guice.createInjector(new GuiceModule())(A.class); Everything is OK. Maybe problem is in class, where you are trying to inject A? Can your provide code of this class too? - Andrei Koch

1 Answers

0
votes

your constructor should be public so guice can see it and inject into it .

here is some reference to guice docs

Class B implements A {

  @Inject
  ***public***  B(String para1, MyClass B) {
     // do something
  }
}