Guice Beginner - How to bind concrete classes?

后端 未结 3 622
庸人自扰
庸人自扰 2021-02-01 13:13

I have this class:

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

    @Inject
    public House(         


        
相关标签:
3条回答
  • 2021-02-01 13:47

    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() {
        }
    }
    
    0 讨论(0)
  • 2021-02-01 13:57

    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.

    0 讨论(0)
  • 2021-02-01 13:59

    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

    0 讨论(0)
提交回复
热议问题