I am using Spring Data for MongoDB and I need to be able to configure collection at runtime.
My repository is defined as:
@Repository
public interfac
define your entity class like
@Document(collection = "${EventDataRepository.getCollectionName()}")
public class EventData implements Serializable {
Define a custom repository interface with getter and setter methods for "collectionName"
public interface EventDataRepositoryCustom {
String getCollectionName();
void setCollectionName(String collectionName);
}
provide implementation class for custom repository with "collectionName" implementation
public class EventDataRepositoryImpl implements EventDataRepositoryCustom{
private static String collectionName = "myCollection";
@Override
public String getCollectionName() {
return collectionName;
}
@Override
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
}
Add EventDataRepositoryImpl
to the extends list of your repository interface in this it would look like
@Repository
public interface EventDataRepository extends MongoRepository, EventDataRepositoryImpl {
}
Now in your Service class where you are using the MongoRepository
set the collection name, it would look like
@Autowired
EventDataRepository repository ;
repository.setCollectionName("collectionName");