Guice链接绑定与@Provides方法的区别

3
我有这个问题。
假设我有类定义如下:
public interface ABCInterface 
{
}

它的实现方式是:
public class ABCImpl 
{       
  @Inject
  private XYZ xyz;
}

当Guice配置如下时:
public class MasterConfig extends AbstractModule 
{    
  @Override
  protected void configure() 
  {
    // TODO Auto-generated method stub
    bind(ABCInterface.class)
    .to(ABCImpl.class);
  }
}

运行它,一切都正常,XYZ被注入其中。
但是当我使用提供者方法时,就像这样:
public class MasterConfig extends AbstractModule {

    @Override
    protected void configure() {
        // TODO Auto-generated method stub
    }

    @Provides
    public ABCInterface abc() {
        return new ABCImpl();
    }
}

在这种情况下,当我尝试使用注入的XYZ时,会出现空指针异常,因为该对象仍然为空。我怀疑这是因为我返回了一个新的ABCImpl对象,因此Guice无法构建依赖关系图。如果我理解有误,请纠正我。

有人能否建议一下如何编写Provider方法,以便像在configure方法中提到的那样正确注入所有内容。

1个回答

3
实际上,当您编写new ABCImpl()时,Guice 没有机会注入其依赖项。 您可以这样做:
@Provides
ABCInterface abc(ABCImpl impl) {
    return impl;
}

但在这种情况下,你可能只需要写 bind(ABCInterface.class).to(ABCImpl.class);,除非你的提供程序方法有一些额外的逻辑。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接