gpt4 book ai didi

java - 带有@Document的mongodb Multi-Tenancy 咒语

转载 作者:IT老高 更新时间:2023-10-28 13:32:37 26 4
gpt4 key购买 nike

这与 MongoDB and SpEL Expressions in @Document annotations

这就是我创建 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);
}

检查上下文的 Autowiring 以及mongoMappingContext.setApplicationContext(appContext);

通过这两行,我能够正确连接组件以在 Multi-Tenancy 模式下使用它

关于java - 带有@Document的mongodb Multi-Tenancy 咒语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19807733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com