在Guice中绑定一个二维数组

时间:2014-12-07 14:32:27

标签: java dependency-injection guice guice-3

我必须使用Guice Dependency注入创建ModelWeights的对象。如何在运行时使用Guice依赖注入绑定double[][]数组?

public class MW {

    private double[][] weights;
    private LogConditionalObjectiveFunction objectiveFunction;

    @Inject
    public MW(double[][] weights, LogConditionalObjectiveFunction func)
    {
        this.weights = weights;
        this.objectiveFunction = func;
    }

    public double[][] getWeights()
    {
        return this.weights;
    }

    public LogConditionalObjectiveFunction getObjectiveFunction()
    {
        return this.objectiveFunction;
    }
}

我尝试了几种方法时得到了这个:

1) No implementation for double[][] was bound.
  while locating double[][]
    for parameter 0 at com.data.MW.<init>(MW.java:13)
  while locating com.data.MW
    for parameter 0 at com.predictor.impl.MEP.<init>(MEP.java:50)
  at     com.ServletDependencyInjector$1.configureServlets(ServletDependencyInjector.java:72)

1 个答案:

答案 0 :(得分:1)

使用Guice常量绑定

@Inject
public ModelWeights(@Named("MyMatrix") double[][] weights, LogConditionalObjectiveFunction func) {
        this.weights = weights;
        this.objectiveFunction = func;
}

并在你的Guice设置代码中

@Override
protected void configure() {
   bind(double[][].class).annotatedWith(Names.named("MyMatrix")).toInstance(MY_MATRIX); 
}