我正在試用Google Guice(3.0)和Google Reflections(0.9.6)。Guice和罐子文件內的思考
我有以下文件:
Operation.java:
package com.company1.calculator;
public interface Operation {
public int apply(int a, int b);
}
Addition.java:
package com.company1.calculator;
public class Addition implements Operation {
@Override
public int apply(int a, int b) {
return a + b;
}
}
其他各種 「操作」 類分佈在多個包。
CalculatorModule.java:
package com.company1.calculator;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.MapBinder;
import org.reflections.Reflections;
public class CalculatorModule extends AbstractModule {
@Override
protected void configure() {
Reflections reflections = new Reflections("");
MapBinder<String, Operation> map = MapBinder.newMapBinder(binder(), String.class, Operation.class);
for (Class<? extends Operation> o : reflections.getSubTypesOf(Operation.class)) {
map.addBinding(o.getSimpleName()).to(o);
}
}
}
Calculator.java:
package com.company1.calculator;
import com.google.inject.Inject;
import java.util.Map;
public class Calculator {
private Map<String, Operation> operations;
@Inject
public Calculator(Map<String, Operation> operations) {
this.operations = operations;
}
public void printCalculations(int a, int b) {
System.out.println("Calculator: " + a + " " + b);
for (String s : operations.keySet()) {
System.out.print(s + ": ");
System.out.println(operations.get(s).apply(a, b));
}
}
}
最後,App.java:
package com.company1.calculator;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class App {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new CalculatorModule());
Calculator c = injector.getInstance(Calculator.class);
c.printCalculations(3, 3);
}
}
執行App.java內部的IntelliJ的我得到以下輸出,正如所料後:
計算器:3 3
模量:0
部:1
乘法:9
增加: 6
然而,當我打包這個應用程序作爲一個罐子裏我只得到了以下的輸出:
計算器:3 3
這是爲什麼,我該如何解決?我發現的最接近的事情是Issue 48,但說固定爲2011年5月的肯定,將我們已經進入Maven的現在......