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

Spring Boot集成MongoDB启动提示authorMongoRepository找不到Bean问题求助

问题根因&解决方案

1. 修正MongoRepository扫描配置

你在启动类上配置的@EnableMongoRepositories注解参数错误,basePackages要求传入存储Repository类的包路径,但你填成了AuthorMongoRepository类的全限定名,导致Spring扫描不到该Repository,无法生成对应的Bean。
修改启动类注解:

// 原错误配置:@EnableMongoRepositories(basePackages = "com.example.SpringReturnObject.Rest.Controller.AuthorMongoRepository")
// 修改为包路径
@EnableMongoRepositories(basePackages = "com.example.SpringReturnObject.Rest.Controller")

2. 修正Controller注解配置

Spring的@RestController注解不支持继承,你把它加在MongoController接口上不会生效,需要移到实现类上,否则AddNewDoc不会被Spring识别为Bean,类内部的@Autowired注入也不会生效。
首先修改MongoController接口,移除类上的@RestController:

package com.example.SpringReturnObject.Rest.Controller;

import com.example.SpringReturnObject.Mongo.Model.Author;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

public interface MongoController {
    @GetMapping("/author")
    List<Author> getAllList();
}

然后在AddNewDoc实现类上加@RestController注解:

package com.example.SpringReturnObject.Mongo.Implementation;

// 省略导入
@RestController
public class AddNewDoc implements MongoController {
    // 原有代码保持不变
}

3. 清理启动类冗余注解(可选,避免配置冲突)

@SpringBootApplication注解本身已经包含@Configuration、@EnableAutoConfiguration、@ComponentScan三个注解的功能,你额外添加的这三个注解属于冗余配置,可以直接删除,避免后续配置冲突,修改后的启动类参考:

package com.example.SpringReturnObject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@EnableMongoRepositories(basePackages = "com.example.SpringReturnObject.Rest.Controller")
@EntityScan({"com.example.*"})
@SpringBootApplication
public class SpringReturnObjectApplication  {
    public static void main(String[] args) {
        SpringApplication.run(SpringReturnObjectApplication.class, args);
    }
}

完成以上修改后重启项目即可解决Bean找不到的报错。


内容的提问来源于stack exchange,提问作者Büşra Ceylan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 05:48:02