Ankur Adhyapak
Ankur Adhyapak

Reputation: 11

Can we inject a class(who doesnot implement an interface) directly with guice@inject

In Google Guice: can we implement a singleton class with annotation @Singleton which doesn't implement an interface and try to inject it in any other class by using annotation @Inject? Also I haven't configured any bind for that class in an extended class of AbstractModule. is it necessary to implement the class from an interface and also i want to know about binding if i implement the singleton class from an interface then its required to bind because there may be multiple classes implementing the interface .

But if i have a class that doesnot implement an interface , then is it required to bind in the class that implement AbstractModule ??

Upvotes: 0

Views: 2469

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95664

Yes, you can mark an implementation class with a scope annotation like @Singleton and inject it directly.

It is not required to bind that class in an AbstractModule, but you may want to do so with an Untargeted Binding, for a number of reasons:

  • Guice will eagerly load the class and prepare its dependencies when the Injector starts up, which might yield more predictable performance during runtime. This is especially useful for servers, where a Guice application may "warm up" before receiving live traffic.

  • Guice will know about missing dependencies and fail at injector creation time if any dependencies are missing. Without a bind statement, Guice may only encounter your class when it's trying to fulfill it, which means that your application may run for a while before Guice can throw an Exception about the missing dependencies.

  • You may choose to limit which classes can be injected, to make it less likely that developers on your project will unintentionally add an inappropriate binding to the graph. You can enable that check by calling requireExplicitBindings, at which point you will need a bind statement.

Upvotes: 1

Related Questions