標籤:style blog color java os io 資料 for
1. 有了上一篇的Mongo後,串連資料庫我們還需要更多的資訊,比如資料庫名字,使用者名稱和密碼等。
我們可以繼續來配置MongoDbFactory的執行個體。
public interface MongoDbFactory { DB getDb() throws DataAccessException; DB getDb(String dbName) throws DataAccessException;}
然後我們可以繼續用MongoDbFactory來建立MongoTemplate的執行個體。
public class MongoApp { private static final Log log = LogFactory.getLog(MongoApp.class); public static void main(String[] args) throws Exception { MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new Mongo(), "database")); mongoOps.insert(new Person("Joe", 34)); log.info(mongoOps.findOne(new Query(where("name").is("Joe")), Person.class)); mongoOps.dropCollection("person"); }}
其中的SimpleMongoDbFactory是MongoDbFactory的實現。
2.1 通過Java based metadata來進行配置
@Configurationpublic class MongoConfiguration { public @Bean MongoDbFactory mongoDbFactory() throws Exception { return new SimpleMongoDbFactory(new Mongo(), "database"); }}
如果需要認證的話,多加一個參數。
@Configurationpublic class MongoConfiguration { public @Bean MongoDbFactory mongoDbFactory() throws Exception { UserCredentials userCredentials = new UserCredentials("joe", "secret"); return new SimpleMongoDbFactory(new Mongo(), "database", userCredentials); } public @Bean MongoTemplate mongoTemplate() throws Exception { return new MongoTemplate(mongoDbFactory()); }}
2.2 通過xml進行配置
簡單用法(Mongo用預設的主機和連接埠號碼)
<mongo:db-factory dbname="database">
提供主機和連接埠配置的例子
<mongo:db-factory id="anotherMongoDbFactory" host="localhost" port="27017" dbname="database" username="joe" password="secret"/>
如果需要配置更多的options,我們可以用mongo-ref來指向一個已有的bean。
<context:property-placeholder location="classpath:/com/myapp/mongodb/config/mongo.properties"/><mongo:mongo host="${mongo.host}" port="${mongo.port}"> <mongo:options connections-per-host="${mongo.connectionsPerHost}" threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}" auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}" socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}" write-number="1" write-timeout="0" write-fsync="true"/></mongo:mongo><mongo:db-factory dbname="database" mongo-ref="mongo"/><bean id="anotherMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/></bean>