Search code examples
javaguice

How to bind concrete classes?


I have this class:

public class House {
    private final Door door;
    private final Window window;
    private final Roof roof;

    @Inject
    public House(Door door, Window window, Roof roof) {
        this.door = door;
        this.window = window;
        this.roof = roof;
    }
}

Where Door, Window and Roof are concrete classes. Now if I want to implement a Module for this scenario, I would do it like this:

public class HouseModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(Door.class).to(Door.class);
        bind(Window.class).to(Window.class);
        bind(Roof.class).to(Roof.class);
    }
}

But I wonder if this is the right way to bind concrete classes, or if there are easier ways. I feel there is an easier way to this.


Solution

  • Guice's Just-In-Time binding does exactly what you want. Given your Door, Window and Roof meet following requirements (quoted from the Guice documentation):

    either a public, no-arguments constructor, or a constructor with the @Inject annotation

    an empty Module implementation will be sufficient:

    public class HouseModule extends AbstractModule {
        @Override
        protected void configure() {
        }
    }