0

我在我的项目中使用 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 没有任何方法可以获取当前连接的数据库名称。(也许我找不到!)
如何从 producerCollection 方法扫描 MongoClientDefinition 注释?
我想从该注释中设置数据库名称。(替换“样品”)。
注意:我为 MongoClientDefinition 创建了 CDI 扩展。

4

1 回答 1

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);
    }
}
于 2018-09-22T17:50:41.837 回答