djechlin
djechlin

Reputation: 60768

If a module provides a class, why might that class need a constructor with @Inject?

Getting error

Could not find a suitable constructor in Foo.java. Classes must have either one (and only one) constructor annoted with @Inject or a zero-argument constructor that is not private.

I get this error when I add to class Bar

// constructor
@Inject
Bar(Foo foo) { /* ... */ }

Formerly, Bar was a no-arg constructor without @Inject. This worked (the server could start up).

All along I have a *Module.java class that @Provides a copy of Foo.

I haven't simply added an @Inject to Foo because Foo has two constructors. My Module class's @Provides method uses either.

So it's unclear to me why I need to add @Inject to this class that's already being provided. The Injector should be able to instantiate it from the @Provides method without relying on Foo's constructors, no?

Upvotes: 0

Views: 128

Answers (1)

djechlin
djechlin

Reputation: 60768

Things were not as they appeared.

My @Provides method returned an Optional<Foo>. To the compiler and runtime, this is of course quite different. Solved by having Bar accept Optional<Foo>.

Upvotes: 1

Related Questions