Spring Integration

将 ReactiveMongoTemplate 的映射、集合命名和反应式生命周期与 MongoExecutionContext 适配器连接,而不引入 Spring Data MongoDB 作为核心依赖。


Spring Data MongoDB 由应用程序维护

build.gradle
text
dependencies {
  implementation("com.byeolnaerim:reactive-mongo-dsl:1.0.0")
  implementation("org.springframework.boot:spring-boot-starter-data-mongodb-reactive")
}

核心库不直接依赖 Spring Data MongoDB。要使用现有 Spring 应用程序的 ReactiveMongoTemplate 设置,需在应用层提供 MongoExecutionContext 适配器。

SpringReactiveMongoExecutionContext 适配器

SpringReactiveMongoExecutionContext.java
java
public class SpringReactiveMongoExecutionContext implements MongoExecutionContext {

  private final ReactiveMongoTemplate reactiveMongoTemplate;
  private final MongoClient mongoClient;
  private final MongoConverter mongoConverter;
  private final ReactiveEntityCallbacks entityCallbacks;

  public SpringReactiveMongoExecutionContext(
      ReactiveMongoTemplate reactiveMongoTemplate,
      MongoClient mongoClient,
      ReactiveEntityCallbacks entityCallbacks
  ) {
    this.reactiveMongoTemplate = Objects.requireNonNull(reactiveMongoTemplate);
    this.mongoClient = Objects.requireNonNull(mongoClient);
    this.mongoConverter = reactiveMongoTemplate.getConverter();
    this.entityCallbacks = Objects.requireNonNull(entityCallbacks);
  }

  @Override
  public Mono<MongoDatabase> getDatabase() {
    return reactiveMongoTemplate.getMongoDatabase();
  }

  @Override
  public Mono<ClientSession> startSession() {
    return Mono.from(mongoClient.startSession());
  }

  @Override
  public String getCollectionName(Class<?> entityClass) {
    return reactiveMongoTemplate.getCollectionName(entityClass);
  }

  @Override
  public Document write(Object source) {
    Document document = new Document();
    mongoConverter.write(source, document);
    return document;
  }

  @Override
  public <T> T read(Class<T> targetType, Document source) {
    return mongoConverter.read(targetType, source);
  }

  @Override
  public Object getId(Object entity) {
    MongoPersistentEntity<?> persistentEntity =
        mongoConverter.getMappingContext().getPersistentEntity(entity.getClass());

    if (persistentEntity == null || !persistentEntity.hasIdProperty()) {
      return null;
    }

    Object id = persistentEntity.getIdentifierAccessor(entity).getIdentifier();
    if (id == null) return null;

    Document document = new Document();
    mongoConverter.write(entity, document);
    return document.get("_id");
  }

  @Override
  @SuppressWarnings({ "rawtypes", "unchecked" })
  public void setId(Object entity, Object id) {
    MongoPersistentEntity persistentEntity =
        mongoConverter.getMappingContext().getPersistentEntity(entity.getClass());

    if (persistentEntity == null || !persistentEntity.hasIdProperty()) return;

    MongoPersistentProperty idProperty =
        (MongoPersistentProperty) persistentEntity.getRequiredIdProperty();

    Object targetId = id;
    if (id instanceof ObjectId objectId && idProperty.getType() == String.class) {
      targetId = objectId.toHexString();
    } else if (
        id != null
            && !idProperty.getType().isInstance(id)
            && mongoConverter.getConversionService()
                .canConvert(id.getClass(), idProperty.getType())
    ) {
      targetId = mongoConverter.getConversionService()
          .convert(id, idProperty.getType());
    }

    PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(entity);
    accessor.setProperty(idProperty, targetId);
  }

  @Override
  public <T> Mono<T> beforePersist(T entity, String collectionName) {
    return entityCallbacks.callback(
        ReactiveBeforeConvertCallback.class,
        entity,
        collectionName
    );
  }

  @Override
  public <T> Mono<T> afterPersist(
      T entity,
      Document document,
      String collectionName
  ) {
    return entityCallbacks.callback(
        ReactiveAfterSaveCallback.class,
        entity,
        document,
        collectionName
    );
  }

  @Override
  public Object getSessionScope() {
    return mongoClient;
  }

  @Override
  public Object getNative() {
    return reactiveMongoTemplate;
  }

  @Override
  public <T> T getNative(Class<T> nativeType) {
    if (nativeType.isInstance(reactiveMongoTemplate)) {
      return nativeType.cast(reactiveMongoTemplate);
    }
    if (nativeType.isInstance(mongoClient)) {
      return nativeType.cast(mongoClient);
    }
    return MongoExecutionContext.super.getNative(nativeType);
  }
}

在实际实现中,向上述类添加所需的 Spring/MongoDB 导入。关键是将实体的读/写与 MongoConverter、集合名称与 ReactiveMongoTemplate、会话启动与相应的 MongoClient 连接起来。

Resolver 和 DSL Bean 注册

MongoTemplateNameResolver.java
java
@Component
public class MongoTemplateNameResolver
    implements MongoTemplateResolver<MongoTemplateName> {

  private final MongoExecutionContext frontExecutionContext;
  private final MongoExecutionContext backExecutionContext;

  public MongoTemplateNameResolver(
      @Qualifier("frontMongoTemplate") ReactiveMongoTemplate frontTemplate,
      @Qualifier("frontMongoClient") MongoClient frontMongoClient,
      @Qualifier("backMongoTemplate") ReactiveMongoTemplate backTemplate,
      @Qualifier("backMongoClient") MongoClient backMongoClient,
      ApplicationContext applicationContext
  ) {
    ReactiveEntityCallbacks callbacks =
        ReactiveEntityCallbacks.create(applicationContext);

    this.frontExecutionContext = new SpringReactiveMongoExecutionContext(
        frontTemplate, frontMongoClient, callbacks
    );
    this.backExecutionContext = new SpringReactiveMongoExecutionContext(
        backTemplate, backMongoClient, callbacks
    );
  }

  @Override
  public MongoExecutionContext getTemplate(MongoTemplateName key) {
    return switch (key) {
      case FRONT -> frontExecutionContext;
      case BACK -> backExecutionContext;
    };
  }
}
ReactiveMongoDslConfiguration.java
java
@Bean
public ReactiveMongoDsl<MongoTemplateName> reactiveMongoDsl(
    MongoTemplateResolver<MongoTemplateName> resolver
) {
  return new ReactiveMongoDsl<>(resolver);
}

适配器连接的范围

@Document / 集合名称

使用 ReactiveMongoTemplate#getCollectionName(...)。

@Id / @Field / 自定义转换

使用 MongoConverter 进行实体 ↔ Document 转换。

反应式审计

将 beforePersist(...) 连接到 ReactiveBeforeConvertCallback,在 save() 系列中应用反应式审计回调。

ReactiveAfterSaveCallback

在写入成功后可以在 afterPersist(...) 中调用。

Spring QueryMapper

不适用。DSL 字符串字段路径基于实际 MongoDB 文档字段名称。

Spring DataAccessException

不自动转换。实际操作由 Reactive Streams Driver 执行。

使用 @Field 的情况

java
@Field("user_name")
private String userName;

// MongoDB document field 이름을 사용
.fields(pair("user_name", "kim"))

实体保存/查询转换应用 Spring 映射,但 DSL 条件的字符串路径不经过 Spring QueryMapper。但准确的 id 路径段会根据 DSL 自身规则规范化为 _id。

Spring 事务和 DSL 事务是分开的

© 2026 Byeolnaerim. 保留所有权利.介绍隐私政策