3
我有3個vertex verticle。無法使用Guice和Vertx將同一實例注入到多個Verticles
我創建的類的AIMP1它實現類A如下
@Singleton
public class AImpl implements A {
public LocationServiceImpl() {
System.out.println("initiated once");
}
public void doSomething(){..}
Verticle 1看起來像這樣:
public class MyVerticle1 extends AbstractVerticle {
...
@Inject
private A a;
@Override
public void start(Future<Void> fut) {
Guice.createInjector(new AppInjector()).injectMembers(this);
a.doSomething(..);
..}
MyVerticle2和MyVerticle3看起來相同。
吉斯代碼:
public class AppInjector extends AbstractModule {
public AppInjector() {
}
@Override
protected void configure() {
bind(A.class).to(AImpl.class).in(Singleton.class);
}
現在,當我運行vertx我可以看到,我得到的AIMP1的3種不同的情況:
public static void main(String[] args) throws InterruptedException {
final Logger logger = Logger.getLogger(StarterVerticle.class);
ClusterManager mgr = new HazelcastClusterManager();
VertxOptions options = new VertxOptions().setClusterManager(mgr);
Vertx.clusteredVertx(options, res -> {
if (res.succeeded()) {
Vertx vertx = res.result();
vertx.deployVerticle(new MyVerticle1());
vertx.deployVerticle(new MyVerticle2());
vertx.deployVerticle(new MyVerticle3());
logger.info("Vertx cluster started!");
} else {
logger.error("Error initiating Vertx cluster");
}
});
控制檯:
2015-09-15 16:36:15,611 [vert.x-eventloop-thread-0] INFO - Vertx cluster started!
initiated once
initiated once
initiated once
我是什麼濫用guice?爲什麼我沒有得到相同的AImpl實例?
謝謝, 射線。
感謝您的答覆。你能展示一個具體的例子嗎?我不知道我應該如何創建我的Verticle沒有新的,我應該如何定義在Guice上的tham – rayman
你能解釋一下如何解決這個問題嗎? – rayman
接受是否意味着你明白了,還是應該提供一個例子? –