How to inject Injector?

You should not be using the Injector directly. Rather pass in the Provider<FooClass> instead. Also, you should be injecting the provider in the places where you use FooClass. private final Provider<FooClass> provider; @Inject public ClassWhereFooIsUsed(Provider<FooClass> provider) { this.provider = provider; } …. somewhere else FooClass f = provider.get(); // This is lazy

Guice best practices and anti-patterns

I have always felt that constructor injection to final fields is a best practice. It minimizes mutable state and makes the class easier to understand by making the class’s formal dependencies explicit. public class MyClass { private final MyDependency dependency; @Inject public MyClass(MyDependency dependency) { this.dependency = dependency; } }

Java Dependency injection: XML or annotations

I can only speak from experience with Guice, but here’s my take. The short of it is that annotation-based configuration greatly reduces the amount you have to write to wire an application together and makes it easier to change what depends on what… often without even having to touch the configuration files themselves. It does … Read more

How to bind one implementation to a few interfaces with Google Guice?

Guice’s wiki has a documentation about this use case. Basically, this is what you should do: // Declare that the provider of DefaultSettings is a singleton bind(DefaultSettings.class).in(Singleton.class); // Bind the providers of the interfaces FirstSettings and SecondSettings // to the provider of DefaultSettings (which is a singleton as defined above) bind(FirstSettings.class).to(DefaultSettings.class); bind(SecondSettings.class).to(DefaultSettings.class); There is no … Read more

Injecting Collection of Classes with Guice

What you want for this is Multibindings. Specifically, you want to bind a Set<Action> (not a List, but a Set is probably what you really want anyway) like this: Multibinder<Action> actionBinder = Multibinder.newSetBinder(binder(), Action.class); actionBinder.addBinding().to(FooAction.class); actionBinder.addBinding().to(BarAction.class); Then you can @Inject the Set<Action> anywhere.