1

Trying to understand dependency injection using Guice. In which cases do we use @Provides and which ones do we use the toProvider binding in the module?

durron597
  • 31,968
  • 17
  • 99
  • 158
Rookie
  • 5,179
  • 13
  • 41
  • 65

1 Answers1

2

When you use @Provides, you write one method in your module. When you use toProvider, you actually create an entire class, which has all the complexity of making a class, as opposed to a single method.

Ultimately, both work, and both allow you to pass in injected dependencies. Just choose the one that is most appropriate for the amount of complexity you need in your specific use case.

Remember that @Provides methods cannot throw Exceptions; so exception handling could be one reason to offload the complexity to a full class.

durron597
  • 31,968
  • 17
  • 99
  • 158