I write on a VertX Application with multiple verticles, which access a database. Each database-package represents one java-class. Each of those classes can be implemented as a singleton class.
I made a little rep-case: 2 verticles, which are using the database.doLoginUser.
package testInject;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
public class App {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
DeploymentOptions options = new DeploymentOptions().setWorker(true).setInstances(5);
vertx.deployVerticle("java:testInject.Test1",options);
vertx.deployVerticle("java:testInject.Test2",options);
}
}
package testInject;
import com.google.inject.Inject;
public class Test1 extends MyVerticle {
// @Inject
Database db = new Database();
@Override
public void start() throws Exception {
System.out.println("Verticle " + this.getClass().getName() + " " + this);
db.doLoginUser();
}
}
package testInject;
import com.google.inject.Inject;
public class Test2 extends MyVerticle {
// @Inject
Database db = new Database();
@Override
public void start() throws Exception {
System.out.println("Verticle " + this.getClass().getName() + " " + this);
db.doLoginUser();
}
}
package testInject;
import io.vertx.core.Vertx;
import io.vertx.core.Context;
import io.vertx.core.AbstractVerticle;
abstract class MyVerticle extends AbstractVerticle {
@Override
public void init(Vertx vertx, Context context) {
super.init(vertx,context);
/* What to do to inject Database into the verticles ????*/
}
}
package testInject;
import com.google.inject.Singleton;
@Singleton
public class Database {
public void doLoginUser() {
System.out.println("Done");
}
}
To make things a bit easier, I don't want to implement every time the same pattern with Database db = Database.getInstance() or create in every verticle a new instance of this Database-Class (which is waste of memory). Just a "@Inject Database db" would be great.
Since VertX initialize the verticle-Classes over a Class-Name, I could not use the Guice-injector.getInstance(Test1.class) function, which is doing the binding. I didn't figure out, how to automatic bind the Database-Class within the constructor or an init-routine at time the verticle-class is created. Is my idea feasible and if yes how?
Thx Nik