To avoid object relationship complex, zero also support Simple dependency injection based on JSR 330.
All the vert.x specific object could be inject as following way.
import javax.inject.infix.Mongo;
import javax.inject.infix.MySql;
import javax.ws.rs.BodyParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@EndPoint
public class InjectApi {
@MySql
private transient SQLClient sqlClient;
@Mongo
private transient MongoClient mongo;
// ......
}
The following object is supported by current zero version
-
javax.inject.infix.@Mongo
:io.vertx.ext.mongo.MongoClient
-
javax.inject.infix.@MySql
:io.vertx.ext.sql.SQLClient
Target Class
import io.vertx.ext.mongo.MongoClient;
import io.vertx.up.commune.Envelop;
import javax.inject.infix.Mongo;
public class InjectDao {
@Mongo
private transient MongoClient client;
public void async(final Envelop envelop) {
System.out.println(this.client);
}
}
Inject InjectDao
import javax.inject.Inject;
@Queue
public class InjectWorker {
@Inject
private transient InjectDao dao;
// ......
}
Interface Definition
public interface InjectStub {
}
Implementation Class
public class InjectInstance implements InjectStub {
}
Inject InjectStub -> InjectInstance
import javax.inject.Inject;
@Queue
public class InjectWorker {
@Inject
private transient InjectStub stub;
// ......
}
*: One limitation for this situation is that there are only one implementation of interface InjectStub.
Interface Definition
public interface InjectA {
}
Implementation Class
InjectB
import javax.inject.Named;
@Named("NameInjectA")
public class InjectB implements InjectA {
}
InjectC
@Named
public class InjectC implements InjectA {
}
Inject InjectA -> InjectB
import io.vertx.up.annotations.Qualifier;
import javax.inject.Inject;
@Queue
public class InjectWorker {
@Inject
@Qualifier("NameInjectA")
private transient InjectA injectA;
You can use @Qualifier
to set which implementation should be inject.
- All this kind of classes are initialized with
singleton
mode, you shouldn't inject Value Object, POJO. - All the injection points are based on some part of
JSR330
but not all.