2015-09-15 18 views
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实例?

谢谢, 射线。

回答

1

您正在使用guice错误的方式。您正在通过new创建MyVerticle实例,并在其开始消息内创建注入器。因此,你最终得到3个注射器,每个注射器都持有一个单体。

你必须在你的main()方法创建一次进样器,然后让吉斯处理MyVerticles的创建:

Injector injector = Guice.createInjector(....); 
... 
vertx.deployVerticle(injector.getInstance(MyVerticle1.class); 

现在的喷射器的AIMP1只创建一个实例,并再次用于所有@Inject AImpl位置。完全从开始方法中移除注射器。与吉斯工作时拇指

2个规则:

  1. 忌用new
  2. 尽量只使用一个单一的喷油器位于您的main()方法
+0

感谢您的答复。你能展示一个具体的例子吗?我不知道我应该如何创建我的Verticle没有新的,我应该如何定义在Guice上的tham – rayman

+0

你能解释一下如何解决这个问题吗? – rayman

+0

接受是否意味着你明白了,还是应该提供一个例子? –

相关问题