In the face, is there a difference between @provides and bind ()?

I am wondering what the difference is between using the @provides method and using bind() in my modules.


I usually override AbstractModule.configure () and bind all my implementations to my interfaces as follows:

 public class MyModule extends AbstractModule { @Override protected void configure() { this.bind(myIface.class).to(myIfaceImpl.class); this.bind(myOtherIface.class).to(myOtherIfaceImpl.class).asEagerSingleton(); } ... } 

However, I noticed a template in the code base I'm working with now, where implementations are not explicitly linked, they are returned from such providers:

 public class MyModule extends AbstractModule { @Provides @Singleton myIface iFaceProvider() { return new myIfaceImpl(); } ... } 

Is there any reason to prefer each other? Are there any cases that invoke a particular method?

+7
java dependency-injection guice
source share
1 answer

If you do

 bind(MyInterface.class).to(MyImplementation.class) 

Guice creates an instance for you. This allows you to store things like AOP. If you do

 @Provides MyInterface provideMyInterface() { return new MyImplementation(); } 

Guice did not instantiate then, so AOP will not work. In addition, MyImplementation requires an accessible constructor. Typically, this form is used when you cannot edit MyImplementation to make it compatible with Guice.

There is a third form:

 @Provides MyInterface provideMyInterface(MyImplementation impl) { return impl; } 

which is almost completely equivalent to the form bind(...).to(...) . It is commonly used in forms like Dagger, which do not have bind syntax.

+8
source share

All Articles