我将javaee 8用于我的项目,并具有以下类:
public class PersonRepository {
@Inject
@Mongo(collection = "users")
private MongoCollection collection;
// define some methods ....
}
@ApplicationScoped
public class MongoProducer {
@Inject
private MongoClient mongoClient;
@Produces
@Mongo
protected MongoCollection produceCollection(InjectionPoint ip) {
Mongo mongo = getMongoAnnotation(ip);
return mongoClient.getDatabase("sample").getCollection(mongo.collection());
}
private Mongo getMongoAnnotation(InjectionPoint ip) {
return ip.getAnnotated().getAnnotation(Mongo.class);
}
}
@MongoClientDefinition(
name = "mongoClient",
dbName = "sample",
username = "admin",
password = "adminpass"
)
public class MongoConnectionConfig {
}
不幸的是,mongoClient目前没有任何方法来获取与其连接的数据库名称。 (也许我找不到!)
如何从ProduceCollection方法扫描MongoClientDefinition批注?
我想从该注释设置数据库名称。 (替换“样本”)。
注意:我为MongoClientDefinition创建了CDI扩展。
答案 0 :(得分:0)
简单的想法是BeanManager:
我修改了扩展名,并为dbName添加了getter方法。
github
@ApplicationScoped
public class MongoProducer {
@Inject
private MongoClient mongoClient;
@Inject
private BeanManager bm;
@Produces
@Mongo
protected MongoCollection produceCollection(InjectionPoint ip) {
String dbName = bm.getExtension(MongoClientExtension.class).getDatabaseName();
Mongo mongo = getMongoAnnotation(ip);
return mongoClient.getDatabase(dbName).getCollection(collectionName,mongo.collection());
}
private Mongo getMongoAnnotation(InjectionPoint ip) {
return ip.getAnnotated().getAnnotation(Mongo.class);
}
}