我的应用程序使用在不同实例上托管的具有相同集合(不同数据)的两个mongo模式。我有一个用于领域事物的ThingsRepository。
public class Thing {
private String id;
private String name;
private String type;
// etc...
}
public interface ThingRepository extends MongoRepository<Thing, String>, ThingRepositoryCustom {
Thing save(Thing Thing);
}
public class ThingRepositoryCustomImpl implements ThingRepositoryCustom {
...
}
我的应用程序已连接到ThingsRepository中,并从其中一个模式随机地连接了存储库。我想注入一个可以返回的工厂,并使用该工厂通过schema1 / schema2来获取仓库。我遇到了Customizing Spring Data repository bean names for use with multiple data sources,该解决方案为每个架构的每个存储库实例定义了bean,我有很多集合,并探讨是否有更好的方法。感谢您提供任何反馈意见。
这是Spring bean的配置
<!-- for schema1 -->
<mongo:mongo-client id="mongo1" replica-set="${mongodb.replication.set.1}" credentials="${MONGO_USER_1}@${mongodb.dbname.1}" >
<mongo:client-options max-connection-idle-time="${mongodb.max.connection.idle.1:300000}" />
</mongo:mongo-client>
<mongo:db-factory id="mongoDbFactory1" dbname="${mongodb.dbname.1}" mongo-ref="mongo1" />
<bean id="mongoTemplate1" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory1" />
<constructor-arg ref="mongoConverter1" />
</bean>
<bean id="mongoConverter1" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg ref="mongoDbFactory1" />
<constructor-arg>
<bean class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
</constructor-arg>
<property name="mapKeyDotReplacement" value="%2E" />
</bean>
<mongo:repositories base-package="com.xyz.pkg" repository-impl-postfix="CustomImpl" mongo-template-ref="mongoTemplate1" />
<!-- for schema2 -->
<mongo:mongo-client id="mongo2" replica-set="${mongodb.replication.set.2}" credentials="${MONGO_USER_2}@${mongodb.dbname.2}" >
<mongo:client-options max-connection-idle-time="${mongodb.max.connection.idle.2:300000}" />
</mongo:mongo-client>
<mongo:db-factory id="mongoDbFactory2" dbname="${mongodb.dbname.2}" mongo-ref="mongo2" />
<bean id="mongoTemplate2" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory2" />
<constructor-arg ref="mongoConverter2" />
</bean>
<bean id="mongoConverter2" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg ref="mongoDbFactory2" />
<constructor-arg>
<bean class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
</constructor-arg>
<property name="mapKeyDotReplacement" value="%2E" />
</bean>
<mongo:repositories base-package="com.xyz.pkg" repository-impl-postfix="CustomImpl" mongo-template-ref="mongoTemplate2" />