Используя Spring Data MongoDB, вам придется переопределить метод ensureIndex
для IndexOperations
через DefaultIndexOperations
и вернуть его для MongoOperations#indexOps(...)
.
Таким образом вы сможете захватить весь индекссоздание, а также аннотации на основе.
@Configuration
public class Config extends AbstractMongoConfiguration {
@Override
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory(), mappingMongoConverter()) {
@Override
public IndexOperations indexOps(Class<?> entityClass) {
return new DefaultIndexOperations(this, getCollectionName(entityClass), entityClass) {
@Override
public String ensureIndex(IndexDefinition indexDefinition) {
if(indexDefinition instanceof Index) {
((Index)indexDefinition).background();
}
return super.ensureIndex(indexDefinition);
}
};
}
};
}
// ...
}
Для аннотаций вы также можете использовать свою собственную пользовательскую аннотацию, прикрепляющую атрибут background
к фиксированному значению без возможности переопределить его, открывая изменяемые значения с помощью @AliasFor
.
Что-токак в примере ниже, работает без настройки MongoOperations
/ IndexOperations
.
@Indexed(background = true) // fix attribute values here
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
public @interface ComposedIndexedAnnotation {
@AliasFor(annotation = Indexed.class, attribute = "unique")
boolean unique() default false;
@AliasFor(annotation = Indexed.class, attribute = "name")
String indexName() default "";
}