日期:2014-05-16  浏览次数:20457 次

morphia与spring的整合
首先我们需要一个生成和配置mongodb的工厂类:

?

?1?public?class?MongoFactoryBean?extends?AbstractFactoryBean<Mongo>?{
?2?
?3?????//?表示服务器列表(主从复制或者分片)的字符串数组
?4?????private?String[]?serverStrings;
?5?????//?mongoDB配置对象
?6?????private?MongoOptions?mongoOptions;
?7?????//?是否主从分离(读取从库),默认读写都在主库
?8?????private?boolean?readSecondary?=?false;
?9?????//?设定写策略(出错时是否抛异常),默认采用SAFE模式(需要抛异常)
10?????private?WriteConcern?writeConcern?=?WriteConcern.SAFE;
11?
12?????@Override
13?????public?Class<?>?getObjectType()?{
14?????????return?Mongo.class;
15?????}
16?
17?????@Override
18?????protected?Mongo?createInstance()?throws?Exception?{
19?????????Mongo?mongo?=?initMongo();
20?????????
21?????????//?设定主从分离
22?????????if?(readSecondary)?{
23?????????????mongo.setReadPreference(ReadPreference.secondaryPreferred());
24?????????}
25?
26?????????//?设定写策略
27?????????mongo.setWriteConcern(writeConcern);
28?????????return?mongo;
29?????}
30?????
31?????/**
32??????*?初始化mongo实例
33??????*?