【问题标题】:GIN injection of field in abstract class抽象类中字段的 GIN 注入
【发布时间】:2013-01-28 13:30:43
【问题描述】:

我在一些 GWT 应用程序中工作,其中我有一个层次结构,其中我有一个具有派生类的一些常见功能的抽象呈现器。比如:

public abstract class MyAbstractPresenter<T extends MyAbstractPresenter.CustomDisplay> extends Presenter<T>
{
public interface CustomDisplay extends View
{
  //some methods
}

//I want to inject this element
@Inject
private CustomObject myObj;

public MyAbstractPresenter(T display)
{
   super(display);
}
}

所有子类都被正确注入。但是,我希望能够注入该特定字段,而无需将其添加到子类的构造函数中。如您所见,我尝试进行字段注入,但它不起作用,因为注入的是子类。

在不让子类知道该字段的存在的情况下,是否有适当的方法来实现这种注入?

【问题讨论】:

  • Guice 可以在客户端的 GWT 中使用吗?据我所知,存在 Gin 实现 - GWT 客户端的 Guice。
  • 无论如何它都是建立在 guice 之上的,而且由于我的问题适用于其他情况,所以我想让它更笼统。

标签: java gwt dependency-injection guice gwt-gin


【解决方案1】:

显然,就目前而言,GIN 中不支持此类行为。一种解决方法是在具体类构造函数中注入所需的字段,即使它们不需要它。比如:

 public abstract class MyAbstractPresenter<T extends MyAbstractPresenter.CustomDisplay> extends Presenter<T>
 {
   public interface CustomDisplay extends View
   {
     //some methods
   }

   //I wanted to inject this element
   private final CustomObject myObj;

   public MyAbstractPresenter(T display, CustomObject obj)
   {
      super(display);
      myObj = obj;
   }
}

那么在任何扩展这个抽象实现的类中,我都必须在构造时传递它。

public abstract class MyConcretePresenter extends MyAbstractPresenter<MyConcretePresenter.CustomDisplay>
{
  public interface CustomDisplay extends MyAbstractPresenter.CustomDisplay
  {
     //some methods
  }

 @Inject  //it would get injected here instead.
 public MyConcretePresenter(CustomDisplay display, CustomObject obj)
 {
     super(display, obj);
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    相关资源
    最近更新 更多