title: Autowire MongoRepository in Spring MVC
body: <p>I want to Autowire MongoRepository into my service class, and I'm not able to do this. I'm using java config.
  This is my repository class:</p>
  
  <pre><code>@Repository
  public interface UserRepository extends MongoRepository&lt;User, String&gt; {
  
      public User findByFirstName(String firstName);
      public List&lt;User&gt; findByLastName(String lastName);
  
  }
  </code></pre>
  
  <p>This is the Service which uses UserRepository:</p>
  
  <pre><code>@Service
  public class TestService {
  
      @Autowired
      private UserRepository repository;
  
      public void save(User user) {
          repository.save(user);
      }
  }
  </code></pre>
  
  <p>This is part of my Controller which uses service:</p>
  
  <pre><code>@Controller
  public class TestController {
  
      @Autowired
      private TestService service;
  </code></pre>
  
  <p>My main java config class looks like this:</p>
  
  <pre><code>@Configuration
  @EnableWebMvc
  @EnableMongoRepositories
  @Import({MjurAppConfig.class, MongoConfiguration.class})
  @ComponentScan({"prv.makro.mjur.controller"})
  public class MjurWebAppConfig extends WebMvcConfigurerAdapter {
  </code></pre>
  
  <p>MjurAppConfig:</p>
  
  <pre><code>@Configuration
  @ComponentScan({"prv.makro.mjur.dao", "prv.makro.mjur.repository"})
  public class MjurAppConfig {
  
      @Bean
      public User getUser() {
          return new User();
      }
  
      @Bean
      public TestService getTestService() {
          return new TestService();
      }
  }
  </code></pre>
  
  <p>And mongo config:</p>
  
  <pre><code>@Configuration
  public class MongoConfiguration {
  
      @Bean
      public MongoFactoryBean mongo() {
          MongoFactoryBean mongo = new MongoFactoryBean();
          mongo.setHost("localhost");
          mongo.setPort(27017);
          return mongo;
      }
  
      @Bean
      public MongoTemplate mongoTemplate() throws Exception{
          return new MongoTemplate(mongo().getObject(),"mjur");
      }
  }
  </code></pre>
  
  <p>Exception:</p>
  
  <pre><code>    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private prv.makro.mjur.repository.UserRepository 
  prv.makro.mjur.service.impl.FirstService.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
  No qualifying bean of type [prv.makro.mjur.repository.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 
  Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  </code></pre>
  
  <p>I was searching for resolution for this problem but I couldn't find anything.
  IMO Component scan should find the repository and it should bind it to spring context. Sadly it's not working like that.</p>