Java Guice - 方法toProvider不适用于参数

时间:2013-12-22 11:22:37

标签: java dependency-injection guice

我从这里关注Guice文档: http://code.google.com/p/google-guice/

我坚持使用toProvider方法。当我尝试这样做时:

bind(Shape.class).toProvider(ShapeProvider.class);

我收到此错误:

The method toProvider(Provider<? extends Shape>) in the type LinkedBindingBuilder<Shape> is not applicable for the arguments (Class<ShapeProvider>)

我的代码如下:

配置类

public class Configuration extends AbstractModule{
    @Override
    protected void configure(){
        bind(Shape.class).toProvider(ShapeProvider.class);
        bind(Triangle.class).to(IsoTriangle.class);
    }

ShapeProvider类

public class ShapeProvider implements Provider<Shape> {
    private int length;
    @Inject
    public ShapeProvider(int length){
        this.length = length;
    }
    public Shape get(){
        Shape triangle = new Triangle(length);
        return triangle;

    }
}

形状界面

public interface Shape {

}

三角课

public class Triangle implements Shape{
    int length;
    public Triangle(){
    }
    public Triangle(int lenght){
        this.length = lenght;
    }
}

我是否遗漏了某些内容或文档中未提及的内容?

更新

提供商界面:

public interface Provider<T> {
    T get();
}

2 个答案:

答案 0 :(得分:1)

如果您使用toProvider,则必须提供Provider个实例。请参阅LinkedBindingBuilder.toProvider

的javadoc
bind(Shape.class).toProvider(new ShapeProvider());

或者您应该使用to作为参数。另请参见LinkedBindingBuilder.to()

的javadoc
bind(Shape.class).to(ShapeProvider.class);

修改

我无法重现你的问题。我创建了一些类来模拟问题(因为我现在不想设置guice),但是当我考虑到时......没有编译器错误。

以下代码与guice api等效,并且编译。

public class Main {

    public static void main(String[] args) {
        LinkedBindingBuilder<Shape> linkedBindingBuilder = new LinkedBindingBuilder<Shape>();
        linkedBindingBuilder.toProvider(new ShapeProvider());
    }

    public static class ShapeProvider implements Provider<Shape> {
        public Shape get() {return null;}
    }

    public static class Shape {}

    public static class LinkedBindingBuilder<T> {

        public ScopedBindingBuilder toProvider(Provider<? extends T> provider) {
            return null;
        }
    }

    private static interface Provider<T> {
        T get();
    }

    private static class ScopedBindingBuilder {}
}

答案 1 :(得分:0)

我发现了什么问题。我认为我需要自己实现提供程序界面,如Google / Guice文档中所示,但它显示了该界面的外观。所以我不小心覆盖了原始的Provider接口。当我删除我的Provider界面时,一切都解决了。