I have a MongoService class
public class MongoService {
private final Mongo mongo;
private final String database;
private static final Logger LOGGER = LoggerFactory.getLogger(MongoService.class);
public MongoService(@Nonnull final String host, final int port, @Nonnull final String db) throws UnknownHostException {
mongo = new Mongo(host, port);
database = db;
}
public void putDocument(@Nonnull final DBObject document) {
LOGGER.info("inserting document - " + document.toString());
mongo.getDB(database).getCollection(getCollectionName(document)).insert(document, WriteConcern.SAFE);
}
public void putDocuments(@Nonnull final List<DBObject> documents) {
for (final DBObject document : documents) {
putDocument(document);
}
}
@Nullable
public <T extends DBObject> T getDocument(@Nonnull final T document) {
final DBCollection collection = mongo.getDB(database).getCollection(getCollectionName(document));
collection.setObjectClass(document.getClass());
//noinspection unchecked
return (T) collection.findOne(document);
}
@Nonnull
public <T extends DBObject> List<T> getDocuments(@Nonnull final T document) {
final List<DBObject> documents = new ArrayList<DBObject>();
final DBCollection collection = mongo.getDB(database).getCollection(getCollectionName(document));
collection.setObjectClass(document.getClass());
final DBCursor dbCursor = collection.find();
if (dbCursor != null) {
documents.add(dbCursor.next());
}
//noinspection unchecked
return (List<T>) documents;
}
}
I want to create a singleton bean of this class which reads the host, int, port, database from the file
Question
How shall I go about achieving this?
- What are the best way to provide the configuration params from file
- How do I make it singleton bean?
I am new to Spring and don't really know how to achieve this