Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowire MongoRepository in Spring MVC

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:

@Repository
public interface UserRepository extends MongoRepository<User, String> {

    public User findByFirstName(String firstName);
    public List<User> findByLastName(String lastName);

}

This is the Service which uses UserRepository:

@Service
public class TestService {

    @Autowired
    private UserRepository repository;

    public void save(User user) {
        repository.save(user);
    }
}

This is part of my Controller which uses service:

@Controller
public class TestController {

    @Autowired
    private TestService service;

My main java config class looks like this:

@Configuration
@EnableWebMvc
@EnableMongoRepositories
@Import({MjurAppConfig.class, MongoConfiguration.class})
@ComponentScan({"prv.makro.mjur.controller"})
public class MjurWebAppConfig extends WebMvcConfigurerAdapter {

MjurAppConfig:

@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();
    }
}

And mongo config:

@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");
    }
}

Exception:

    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)}

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.

like image 652
Ma Kro Avatar asked Nov 13 '14 19:11

Ma Kro


Video Answer


1 Answers

Ok, the problem was with @EnableMongoRepositories annotation.

When I have added package name to it's body (so it looked like:

@EnableMongoRepositories({"prv.makro.mjur.repository"}) )

I was able to autowire my UserRepository

like image 121
Ma Kro Avatar answered Sep 19 '22 21:09

Ma Kro