Guice Beginner - How to bind concrete classes?

倖福魔咒の 提交于 2019-12-03 06:28:59

问题


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.

EDIT

Just tried this out, and it doesn't seem to work:

1) Binding points to itself.
  at de.tarent.guice.ex._1.HouseModule.configure(HouseModule.java:10)

EDIT 2

It seems like no binding is needed at all:

Injector injector = Guice.createInjector();
House house = injector.getInstance(House.class);

Also seems to work.


回答1:


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() {
    }
}



回答2:


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 behavior. You may still want to use this if you prefer your Module class to serve as an explicit manifest for the services it provides. Also, in rare cases, Guice may be unable to validate a binding at injector creation time unless it is given explicitly.

Concrete classes with constructor marked as @Inject are automatically available for injection. But it helps the developer (you) know what is configured in the module.




回答3:


Binding is needed to link Interface and Implementation class (to change to other implementation in test env for example). But since you have concrete classes, no need for binding to, just bind classes



来源:https://stackoverflow.com/questions/8486437/guice-beginner-how-to-bind-concrete-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!