我有一个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,它从文件中读取host,int,port,database
问题
我该如何实现这一目标?
我是Spring的新手,并不知道如何实现这个
答案 0 :(得分:4)
默认情况下,Spring bean是单例的..
@Service
public class MongoService
查看How can I inject a property value into a Spring Bean which was configured using annotations?注入属性,它非常漂亮。
答案 1 :(得分:1)
您可以将值传递给构造函数,如下所示
<bean id="mongoService" class="MongoService">
<constructor-arg name="host" type="java.lang.String" value="localhost"/>
<constructor-arg name="port" type="long" value="1234"/>
<constructor-arg name="db" type="java.lang.String" value="dbname"/>
</bean>
注意:这是Spring 3语法,旧版本不支持name
参数,只需删除它。
如果要进一步外部化属性,可以执行此操作。
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="jdbc.properties"/>
</bean>
<bean id="mongoService" class="MongoService">
<constructor-arg name="host" type="java.lang.String" value="${host}"/>
<constructor-arg name="port" type="long" value="${port}"/>
<constructor-arg name="db" type="java.lang.String" value="${db}"/>
</bean>
确保jdbc.properties位于类路径中。
jdbc.properties中的条目
host=localhost
port=1234
db=dbname
编辑:对于第二个问题,这个mongoService
bean默认为Singleton。