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

Spring Boot内嵌Mongo测试:Repository注入为Null求排查

Hey there, let's troubleshoot why your MyRepository is coming up null in your Spring Boot app with Embedded Mongo! Here are the key things to check:

1. Ensure Spring detects your repository

Your repository interface is missing the @Repository annotation, and if your main Spring Boot application class isn't in a parent package that covers the repository, Spring won't scan it automatically.

  • Add the @Repository annotation to your repository interface:
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface MyRepository extends CrudRepository<Test, String> {
    // Add your custom query methods here if needed
}
  • Double-check your main application class (the one annotated with @SpringBootApplication). It should sit in a root package that includes your controller and repository subpackages. For example:
    • If your controller is in com.example.controller and repo in com.example.repository, your main class should be in com.example (so @SpringBootApplication auto-scans all subpackages). If your package structure is different, explicitly specify the scan range with @SpringBootApplication(scanBasePackages = "com.your-root-package") or use @EnableMongoRepositories(basePackages = "com.your-root-package.repository") to target the repository directly.
2. Switch to constructor injection (more reliable than field injection)

Field injection with @Autowired can sometimes lead to null beans if the controller is initialized before the repository bean is ready. Constructor injection is the recommended approach in Spring and avoids this issue:

@RestController
public class MyController {
    private final MyRepository myRepo;

    // No need for @Autowired here in Spring 4.3+ - constructor injection is auto-detected
    public MyController(MyRepository myRepo) {
        this.myRepo = myRepo;
    }

    @RequestMapping(method= RequestMethod.GET, value="/test")
    public Iterable<Test> findAll() {
        return myRepo.findAll();
    }
}
3. Verify your Embedded MongoDB dependencies & setup

Make sure you have the correct dependencies in your build file:
For Maven (pom.xml):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
    <!-- Remove <scope>test</scope> if you're using Embedded Mongo in your main application -->
    <scope>test</scope>
</dependency>

If you're using Embedded Mongo outside of test scope, add a configuration class to initialize it properly:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.MongodConfig;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;

@Configuration
public class EmbeddedMongoConfig {
    @Bean
    public MongodExecutable mongodExecutable() {
        MongodStarter starter = MongodStarter.getDefaultInstance();
        MongodConfig mongodConfig = MongodConfig.builder()
            .version(Version.Main.PRODUCTION)
            .net(new Net("localhost", 27017, false))
            .build();
        return starter.prepare(mongodConfig);
    }
}
4. Confirm you're launching the app correctly

Make sure you're running the application via your main class annotated with @SpringBootApplication, not just executing the controller directly. Spring needs to bootstrap its context and create all beans properly for dependency injection to work.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:30:06