【问题标题】:Can I inject objects in regular classes in GWT using GIN?我可以使用 GIN 在 GWT 中的常规类中注入对象吗?
【发布时间】:2016-01-13 04:48:00
【问题描述】:

例如,我有一个包含 A 类绑定的 GIN 模块。在 B 类中(B 不使用 GIN 绑定),我可以简单地使用:

@Inject private A a;

注入A类?我在我的项目中尝试过,看起来我得到了对象 a 的空指针。不知道为什么。

【问题讨论】:

    标签: gwt dependency-injection guice gwt-gin


    【解决方案1】:

    因为你还需要用 GIN 实例化你的 B 类。

    例如,您可以使用@UiFields(如果为真),然后将它们注入构造函数中,如下所示:

        /*Class B is not binded by GIN*/
        public class B {
            @Inject
            C cInstance; //C is binded by GIN
        }
    
    /*Class A is binded with GIN*/
        public class A extends ViewImpl{
    
                    @UiField(provided=true)
                    B myWidget;
    
                    //and then
    
                    @Inject
                    public A (UiBinder binder, B myWidget){
                       this.myWidget = myWidget;  //cInstance inside of it is injected!
                    }
            }
    

    在 B 的这种注入之后,B 内部的所有 @Inject 注释都应该按预期解析。

    如果您使用 GWT.create / new 关键字实例化 A - B 实例的 myWidget 引用也将为 null

    【讨论】:

    • 另外,您的 Ginjector 可以有一个 void 方法,该方法将 B 作为唯一参数,并将注入其成员。它的行为类似于(并且可能应该命名为)Guice 的 Injector.injectMembers。
    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    相关资源
    最近更新 更多