本文介绍了Guice Beginner - 如何绑定具体类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个课程:

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;
    }
}

其中 Window 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.

编辑

刚试过这个,它似乎不起作用:

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)

编辑2

似乎根本不需要绑定:

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

似乎也有效。

推荐答案

Guice的完全符合您的要求。鉴于您的窗口屋顶符合以下要求(引自Guice ):

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):

一个空的模块实现将足够了:

an empty Module implementation will be sufficient:

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

这篇关于Guice Beginner - 如何绑定具体类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 08:51