在spring-data-rest中启用mongo异常转换

时间:2015-02-13 11:43:27

标签: java spring spring-boot spring-data-mongodb spring-data-rest

关注此tutorial,使用complete代码,如何为mongo启用异常转换?

当我的mongo db关闭时,我从com.mongodb.MongoServerSelectionException收到500错误。这不应该与MongoExceptionTranslator一起转换为DataAccessResourceFailureException吗?我应该以某种方式注册这个豆吗?我试过了:

@Bean
public MongoExceptionTranslator mongoExceptionTranslator() {
    return new MongoExceptionTranslator();
}

但仍未改变

修改

我已根据demo的建议创建了Stackee007,但仍无法使其生效

1 个答案:

答案 0 :(得分:0)

如果您的配置注册MongoExceptionTranslatorMongoFactoryBean,则已注册

SimpleMongoDbFactory。您可以配置类似下面的mongo注册SimpleMongoDbFactory

@Configuration
@EnableMongoRepositories
public class ApplicationConfig extends AbstractMongoConfiguration {

    @Override
    protected String getDatabaseName() {
        return "yyy";
    }

    @Override
    protected UserCredentials getUserCredentials() {
        return new UserCredentials("abc", "***");
    }

    @Override
    @Bean
    public Mongo mongo() throws Exception {
        List<ServerAddress> seeds = new ArrayList<ServerAddress>();
        seeds.add(new ServerAddress("xxxx"));
        seeds.add(new ServerAddress("xxx"));
        seeds.add(new ServerAddress("xx"));

        MongoClient mongo = new MongoClient(seeds);
        mongo.setReadPreference(ReadPreference.secondaryPreferred());
        mongo.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        return mongo;
    }

    @Bean
    public GridFsTemplate gridFsTemplate() throws Exception {
        return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
    }

}