Home > Net >  How do I fix "Could not autowire. No beans of 'MyRepository' type found"?
How do I fix "Could not autowire. No beans of 'MyRepository' type found"?

Time:02-15

I have this hierarchy in my project:

▼ server
  ▼ myproject
    ▼ src
      ▼ main
        ▼ java
          ▼ rest
            ▼ repository
              Ⓘ MyRepository
        ▶ resources
      ▼ test
        ▼ java
          ▼ rest
            Ⓒ MyRepositoryTest

This is the MyRepository interface:

public interface MyRepository extends MongoRepository<String, Integer> {
}

This is the MyRepositoryTest test class:

@ExtendWith(SpringExtension.class)
public class AdminEvaluatorTest {
    ...
    @Autowired MyRepository myRepository;
    ...
}

The error occurs on the autowired myRepository instance in the test class. It says Could not autowire. No beans of 'MyRepository' type found. I've searched a bit and tried to add @Component, @Repository and so on, but nothing really helps. How do I fix this issue?

CodePudding user response:

You could try this, set your package in @ComponentScan of the class AppConfig:

@ContextConfiguration(classes = AppConfig.class)
@ExtendWith(SpringExtension.class)
public class AdminEvaluatorTest {
    @Autowired MyRepository myRepository;

    @Configuration
    @ComponentScan("com.<your-package>")
    public static class AppConfig {
    }
}

CodePudding user response:

Do you have @EnableAutoConfiguration under your @SpringBootApplication at the main class? Try to set it.

@SpringBootApplication
@EnableAutoConfiguration
....
public class MyProject{

    public static void main(String[] args) {
        SpringApplication.run(MyProject.class, args);
    }

}
  • Related