Pass parameter to constructor with Guice

All the “Guice Constructor Parameter” answers seem to be incomplete in some way. Here is a complete solution, including usage and a visual: interface FooInterface { String getFooName(); } // Annotate the constructor and assisted parameters on the implementation class class Foo implements FooInterface { String bar; @Inject Foo(@Assisted String bar) { this.bar = bar; … Read more

Guice and properties files

You can bind properties using Names.bindProperties(binder(), getProperties()), where getProperties returns a Properties object or a Map<String, String> (reading the properties file as a Properties object is up to you). You can then inject them by name using @Named. If you had a properties file: foo=bar baz=true You could inject the values of those properties anywhere … Read more

Lombok – retain field’s annotation in constructor input params

In version v1.18.4 Lombok added support for copying specific annotations. Meaning, that if you put following setting to lombok.config: lombok.copyableAnnotations += com.google.inject.name.Named and apply following Lombok annotations to your class: @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class Hello { @NonNull @Named(“my-name”) String name; } the @Named annotation should be copied to your generated constructor argument. Limitations: this … Read more

Java error: Found interface … but class was expected

This happens when your runtime classpath is different than your compile time classpath. When your application was compiled, a class (named SomeInterface in your question) existed as a class. When your application is running at compile time, SomeInterface exists as an interface (instead of a class.) This causes an IncompatibleClassChangeError to be thrown at runtime. … Read more

How to bind concrete classes?

This is the way to go: protected void configure() { bind(Door.class); bind(Window.class); bind(Roof.class); } Since they are concrete classes, as Guice says, you can’t bind them to themselves 🙂 Check out the Binder docs, it notes: bind(ServiceImpl.class); This statement does essentially nothing; it “binds the ServiceImpl class to itself” and does not change Guice’s default … Read more

The guice AbstractModule install method

install allows for composition: Within its configure method, FooModule may install FooServiceModule (for instance). This would mean that an Injector created based only on FooModule will include bindings and providers in both FooModule and FooServiceModule. You may see install used to split a Module into logical sub-modules for ease of readability or testing, or for … Read more