1

首先,做这样的事情是一种好习惯吗?我尝试了对我来说似乎正确的方法,但没有成功:

public class FormViewImpl extends CompositeView implements HasUiHandlers<C>, FormView {
    public interface SettlementInstructionsSearchFormViewUiBinder extends UiBinder<Widget, SettlementInstructionsSearchFormViewImpl> {}

    @Inject
    static FormViewImpl uiBinder;

    @Inject
    static Provider<DateEditorWidget> dateEditorProvider;

    @UiField(provided = true)
    MyComponent<String> myComp;

    @UiField
    DateEditorWidget effectiveDateFrom;

    // .. other fields

    @Inject
    public FormViewImpl () {
        myComp = new MyComponent<String>("lol");

        if (uiBinder == null)
            uiBinder = GWT.create(SettlementInstructionsSearchFormViewUiBinder.class);

        initWidget(uiBinder.createAndBindUi(this));
    }

    @UiFactory
    DateEditorWidget createDateEditor() {
        return dateEditorProvider.get();
    }
}

除了没有参数的类之外还需要什么?在我公司的项目中,相同类型的代码在其他地方也可以使用。抱歉,这里的菜鸟水平很高……如果你们有任何指示,那就太好了。

谢谢

4

2 回答 2

4

两个问题:

首先,你的两个@Inject 字段是静态的——你有没有做任何事情来注入静态字段?当 Gin(或 Guice)创建新实例时,不会设置静态字段,这些必须设置一次并完成。因为它们是静态的,所以它们永远不会被垃圾收集——这对你来说可能没问题,或者可能是个问题,你应该将它们更改为实例字段。如果你想让它们保持静态,那么你必须requestStaticInjection在你的模块中调用来让 Gin 在创建 ginjector 时初始化它们。

接下来,如果您确实选择删除静态,则该uiBinder字段在该构造函数中仍然必须为 null,因为这些字段还不能被注入!如何在尚未创建的对象上设置字段?这就是您期望 Gin 能够做到的。相反,请考虑将其作为参数传递给@Inject修饰的构造函数。您甚至不需要将其保存为字段,因为小部件只会使用一次。

于 2013-08-23T21:16:39.780 回答
1

要有一个由 GIN 生成的类(不管它是否是 uiBinder),它没有必要有一个默认的构造函数(即没有参数的构造函数)。您要注入的类必须具有使用@Inject 注解的构造函数:

@Inject
public InjectMeClass(Object a, Object b)

另一个被注入的类,假设它是一个 UiBinder,必须将注入的字段用 @UiField(provided=true) 注释:

public class Injected extends Composite {

    private static InjectedUiBinder uiBinder = GWT
            .create(InjectedUiBinder.class);

    interface InjectedUiBinder extends UiBinder<Widget, Injected> {
    }

    @UiField(provided=true)
    InjectMeClass imc;

    public Injected(final InjectMeClass imc) {
        this.imc=imc;
        initWidget(uiBinder.createAndBindUi(this));
    }

所以,回到你的情况:

    @UiField(provided = true)
    MyComponent<String> myComp;

    @Inject
    public FormViewImpl (MyComponent<String> myComp) {
        this.myComp = myComp;

例如:

   public class MyComponent<T> extends Composite {
        private T value;

        @Inject
        public MyComponent(T t) {
            this.value = t;
            ...
        }
        ...
    }

在 GIN 模块中,您可以有一个提供者:

    @Provides
    @Singleton
    public MyComponent<String> createMyComponent() {
        return new MyComponent<String>("lol");
    }
于 2013-08-23T21:24:52.457 回答