GuiceVerticleFactory implements VerticleFactory { @Override public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception { verticleName = VerticleFactory.removePrefix(verticleName); Class clazz; if (verticleName.endsWith(".java")) { CompilingClassLoader compilingLoader = new CompilingClassLoader(classLoader, verticleName); String className = compilingLoader.resolveMainClassName(); clazz = compilingLoader.loadClass(className); } else { clazz = classLoader.loadClass(verticleName); } return (Verticle) this.injector.getInstance(clazz); } GuiceVerticleFactory(Injector injector); @Override String prefix(); @Override Verticle createVerticle(String verticleName, ClassLoader classLoader); static final String PREFIX; }
@Test public void testCreateVerticle_VerticleWithDependencyInConstructor_VerticleIsCreated() throws Exception { String identifier = GuiceVerticleFactory.PREFIX + ":" + VerticleWithDependency.class.getName(); Verticle verticle = factory.createVerticle(identifier, this.getClass().getClassLoader()); assertThat(verticle).isExactlyInstanceOf(VerticleWithDependency.class); assertThat(((VerticleWithDependency) verticle).getDependency()).isExactlyInstanceOf(DependencyImpl.class); }
@Test public void testCreateVerticle_UncompiledVerticleWithDependencyInConstructor_VerticleIsCreated() throws Exception { this.injector = Guice.createInjector(new VertxModule(this.vertx)); this.factory = new GuiceVerticleFactory(this.injector); this.factory.init(vertx); String identifier = GuiceVerticleFactory.PREFIX + ":UncompiledVerticleWithDependency.java"; Verticle verticle = factory.createVerticle(identifier, this.getClass().getClassLoader()); assertThat(verticle).isNotNull(); }
@Test public void testCreateVerticle_DependencyBindedInSingletonScope_SameInstanceIsUsedByAllVerticles() throws Exception { this.injector = Guice.createInjector(new DependencyAsSingletonModule()); this.factory = new GuiceVerticleFactory(this.injector); this.factory.init(vertx); String identifier = GuiceVerticleFactory.PREFIX + ":" + VerticleWithDependency.class.getName(); String identifier2 = GuiceVerticleFactory.PREFIX + ":" + Verticle2WithDependency.class.getName(); VerticleWithDependency verticle = (VerticleWithDependency) factory.createVerticle(identifier, this.getClass().getClassLoader()); Verticle2WithDependency verticle2 = (Verticle2WithDependency) factory.createVerticle(identifier2, this.getClass().getClassLoader()); assertThat(verticle.getDependency()).isSameAs(verticle2.getDependency()); }