java – 使用@Document的mongodb多语言拼写

前端之家收集整理的这篇文章主要介绍了java – 使用@Document的mongodb多语言拼写前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这与.有关
@L_404_0@

这是我创建mongo模板的方式

@Bean
public MongoDbFactory mongoDbFactory() throws UnknownHostException {
    String dbname = getCustid();
    return new SimpleMongoDbFactory(new MongoClient("localhost"),"mydb");
}

@Bean
MongoTemplate mongoTemplate() throws UnknownHostException {
    MappingMongoConverter converter = 
            new MappingMongoConverter(mongoDbFactory(),new MongoMappingContext());
    return new MongoTemplate(mongoDbFactory(),converter);
}

我有一个租户提供者类

@Component("tenantProvider")
public class TenantProvider {

    public String getTenantId() {
      --custome Thread local logic for getting a name
    }
}

和我的域名课程

    @Document(collection = "#{@tenantProvider.getTenantId()}_device")
     public class Device {
    -- my fields here
    }

如你所见,我已经按照帖子中的说明创建了我的mongotemplate,但我仍然得到以下错误

Exception in thread “main” org.springframework.expression.spel.SpelEvaluationException: EL1057E:(pos 1): No bean resolver registered in the context to resolve access to bean ‘tenantProvider’

我究竟做错了什么?

最佳答案
终于弄明白我为什么会遇到这个问题.

使用Servlet 3初始化时,请确保将应用程序上下文添加到mongo上下文中,如下所示

    @Autowired
private ApplicationContext appContext;

public MongoDbFactory mongoDbFactory() throws UnknownHostException {
    return new SimpleMongoDbFactory(new MongoClient("localhost"),"apollo-mongodb");
}

@Bean
MongoTemplate mongoTemplate() throws UnknownHostException {
    final MongoDbFactory factory = mongoDbFactory();

    final MongoMappingContext mongoMappingContext = new MongoMappingContext();
    mongoMappingContext.setApplicationContext(appContext);

    // Learned from web,prevents Spring from including the _class attribute
    final MappingMongoConverter converter = new MappingMongoConverter(factory,mongoMappingContext);
    converter.setTypeMapper(new DefaultMongoTypeMapper(null));

    return new MongoTemplate(factory,converter);
}

检查上下文的自动装配以及
mongoMappingContext.setApplicationContext(appContext);

通过这两条线,我能够正确连接组件,以便在多租户模式下使用它

猜你在找的Spring相关文章