我有以下代码示例。
public interface Calculator {
public int compute(int a);
}
public class Adder implements Calculator {
private int n = 0;
@Override public int compute(int a) {
int result = a + n;
++n;
return result;
}
}
public class X {@Inject public void run(Calculator c) {
System.out.println(c.compute(500));
}
}
public class FirstModule extends AbstractModule {@Override protected void configure() {
bind(Calculator.class).to(Adder.class);
}
}
public static void main(String[] args) {
Injector inj = Guice.createInjector(new FirstModule());
X x1 = inj.getInstance(X.class);
x1.run(inj.getInstance(Calculator.class));
X x2 = inj.getInstance(X.class);
x2.run(inj.getInstance(Calculator.class));
System.out.println(x1 == x2);
}
我预计输出是:
500
500
False
相反,它是:
500
500
500
500
False
似乎实例化行(如X x1 = inj.getInstance(X.class);
)执行该run()
方法。这是为什么?