我有一个 MongoService 课程
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;
}
}
我想创建一个此类的单例 bean,它从文件中读取主机、int、端口、数据库
问题
我将如何实现这一目标?
- 从文件中提供配置参数的最佳方法是什么
- 我如何使它成为单例豆?
我是 Spring 新手,真的不知道如何实现这一点