You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Data MongoDB中@Aggregation注解使用异常问题求助

Spring Data MongoDB @Aggregation注解启动异常排查

环境

  • Spring Boot版本:3.1.5
  • Spring Data MongoDB版本:3.1.5
  • MongoDB版本:6.0

代码示例

自定义仓库接口继承CrudRepository,包含@Query和@Aggregation注解方法:

import com.myproject.resource.AccountEntity;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MyCustomRepository extends CrudRepository<AccountEntity, String> {
    @Query(value = "{ '_id': ?0 }")
    AccountEntity myOtherCustomAccount(String id );

    @Aggregation("{ '$project': { '_id' : '$lasName' } }")
    List<String> myCustomAggregation();
}

遇到的异常

应用启动时创建仓库实例抛出异常:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property 'myCustomAggregation' found for type 'AccountEntity'

启动日志片段:

2023-11-28T14:03:19.910+01:00 DEBUG 38160 --- [  restartedMain] o.s.d.r.c.s.RepositoryFactorySupport     : Initializing repository instance for com.sword.signature.model.repository.resource.MyCustomRepository…

额外上下文

  • @Query注解方法myOtherCustomAccount正常工作,MongoDB仓库基础配置无问题
  • 异常仅出现在@Aggregation注解方法myCustomAggregation
  • 已确认Spring Data MongoDB依赖、配置正确,仓库被Spring正确扫描
  • 当前版本Spring Data MongoDB支持@Aggregation注解

解决思路

  1. 修正聚合语句拼写错误:代码中$lasName应为$lastName,虽然这不是启动异常的直接原因,但会导致后续聚合逻辑执行失败。

  2. 确保@Aggregation注解被正确识别

    • 检查注解导入:确认使用的是org.springframework.data.mongodb.repository.Aggregation,避免导入其他包的同名注解
    • 改用管道数组格式:将@Aggregation参数改为数组形式,符合官方推荐写法:
      @Aggregation(pipeline = {
          "{$project: {'_id': '$lastName'}}"
      })
      List<String> myCustomAggregation();
      
  3. 更换仓库父接口:将CrudRepository替换为MongoDB专用的MongoRepository,专用接口对MongoDB注解的处理更完善:

    public interface MyCustomRepository extends MongoRepository<AccountEntity, String> {
        // ... 方法保持不变
    }
    
  4. 清理构建缓存并重新编译:项目构建缓存可能导致注解处理异常,执行Maven/Gradle的清理编译命令(如mvn clean install或gradle clean build)后重启应用。

  5. 检查实体类映射配置:确认AccountEntity类上的@Document注解正确指定了集合名,实体类属性与MongoDB字段映射无误,避免映射问题干扰仓库代理生成。

  6. 排查自定义配置干扰:如果项目中有自定义的RepositoryFactoryBean或仓库相关配置类,检查是否覆盖了默认的注解处理逻辑,导致@Aggregation未被正确解析。


内容的提问来源于stack exchange,提问作者Richard N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 02:12:37