0

I use javaee 8 for my project and have this classes :

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 {
}

Unfortunately mongoClient has not any method for get database name currently connected to that. (maybe i cant find that !)
How can scan MongoClientDefinition annotation from produceCollection method ?
I want set database name from that annotation . (replace "sample") .
Note : I created CDI extension for MongoClientDefinition .

mah454
  • 1,571
  • 15
  • 38
  • Have you tried the normal way? e.g. https://stackoverflow.com/a/4296964/1827453 – Panu Haaramo Sep 22 '18 at 12:45
  • Panu Haaramo: can not do that . maby MongoConnectionConfig renamed . I don't know what class annotated by MongoClientDefinition . – mah454 Sep 22 '18 at 17:37

1 Answers1

0

simple idea is BeanManager :
I modified my extension and add getter method for dbName .
full project on 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);
    }
}
mah454
  • 1,571
  • 15
  • 38