I have a spring service that needs to import some data into mongo given the reportKey and the report content. The issue is that the reportKey given indicates db_name/collection_name
which means those 2 need to be set at runtime, when calling the restore method.
Service
@Service
class RestoreServiceImpl {
MongoArchiveRepository toArchiveRepository;
@Autowired
public SnapshotRestoreServiceImpl(MongoArchiveRepository toArchiveRepository) {
this.toArchiveRepository = toArchiveRepository;
}
@Override
public void restore(String reportKey, String reportData) {
toArchiveRepository.save(reportData));
}
}
MongoClient
@Configuration
@EnableMongoRepositories(basePackageClasses = MongoArchiveRepository.class)
public class MongoConfiguration {
private final MongoDataStoreConfiguration mongoDbConfiguration;
@Bean
public MongoClient mongoClient() {
// builder returning a MongoClient instance
}
@Bean
public MongoTemplate mongoTemplate(final MongoClient mongoClient) {
return new MongoTemplate(mongoClient, "db_name");
}
}
MongoRepository
@EnableRetry
@Repository
public interface MongoArchiveRepository extends MongoRepository<Snapshot, String> {}
and model
@Document(collection = "collection_name")
public class Snapshot implements Serializable {
@MongoId(value = FieldType.OBJECT_ID)
@Field("_id")
private String id;
@Field("snapshot")
private String data;
//setters&getters
}
The code works fine if the db name is hardcoded in the mongoTemplate and the collection name specified in the model annotation. Is there a way to set those dynamically after the restore method has been called? Any advice?