application.properties फ़ाइल में ऑटो इंडेक्स निर्माण अक्षम करें
spring.data.mongodb.auto-index-creation=false
या application.yml फ़ाइल
spring:
data:
mongodb:
auto-index-creation: false
मोंगोकॉन्फ़िगरेशन व्हाइट @कॉन्फ़िगरेशन एनोटेशन
. क्लास बनाएंइस निर्भरता को इंजेक्ट करें
private final MongoTemplate mongoTemplate;
private final MongoConverter mongoConverter;
और इस विधि को जोड़ें
@EventListener(ApplicationReadyEvent.class)
public void initIndicesAfterStartup() {
log.info("Mongo InitIndicesAfterStartup init");
var init = System.currentTimeMillis();
var mappingContext = this.mongoConverter.getMappingContext();
if (mappingContext instanceof MongoMappingContext) {
MongoMappingContext mongoMappingContext = (MongoMappingContext) mappingContext;
for (BasicMongoPersistentEntity<?> persistentEntity : mongoMappingContext.getPersistentEntities()) {
var clazz = persistentEntity.getType();
if (clazz.isAnnotationPresent(Document.class)) {
var resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);
var indexOps = mongoTemplate.indexOps(clazz);
resolver.resolveIndexFor(clazz).forEach(indexOps::ensureIndex);
}
}
}
log.info("Mongo InitIndicesAfterStartup take: {}", (System.currentTimeMillis() - init));
}
याद रखें कि वर केवल जावा 11+ के लिए है
अंतिम वर्ग, जो लोम्बोक का उपयोग करता है
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver;
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
@Slf4j
@RequiredArgsConstructor
@Configuration
public class MongoConfiguration {
private final MongoTemplate mongoTemplate;
private final MongoConverter mongoConverter;
@EventListener(ApplicationReadyEvent.class)
public void initIndicesAfterStartup() {
log.info("Mongo InitIndicesAfterStartup init");
var init = System.currentTimeMillis();
var mappingContext = this.mongoConverter.getMappingContext();
if (mappingContext instanceof MongoMappingContext) {
MongoMappingContext mongoMappingContext = (MongoMappingContext) mappingContext;
for (BasicMongoPersistentEntity<?> persistentEntity : mongoMappingContext.getPersistentEntities()) {
var clazz = persistentEntity.getType();
if (clazz.isAnnotationPresent(Document.class)) {
var resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);
var indexOps = mongoTemplate.indexOps(clazz);
resolver.resolveIndexFor(clazz).forEach(indexOps::ensureIndex);
}
}
}
log.info("Mongo InitIndicesAfterStartup take: {}", (System.currentTimeMillis() - init));
}
}