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来进行配置
@Configuration
public class MongoConfiguration { public @Bean MongoDbFactory mongoDbFactory() throws Exception {
return new SimpleMongoDbFactory(new Mongo(), "database");
}
}
如果需要认证的话,多加一个参数。
@Configuration
public 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>