Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring data mongo - No bean named 'mongoTemplate' is defined

i have a spring data mongo repository class

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

in the test configuration i use the EnableMongoRepositories annotation

@EnableMongoRepositories(basePackages={"com.mypackage.repository.mongodb"})
public class ServiceTestConfiguration {

when i try to test a service class that uses this repository it throws an exception

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] ... 57 common frames omitted

like image 660
austin Avatar asked Feb 29 '16 21:02

austin


Video Answer


1 Answers

The @EnableMongoRepositories annotation will trigger creation of repository beans on startup, but you still need to register a MongoDB connection and create the MongoTemplate instance that is injected into these repositories. See the Spring Data MongoDB documentation. Here is an example:

@Configuration
@PropertySource({ "classpath:mongodb-data-source.properties" })
public class MongodbDataSourceConfig extends AbstractMongoConfiguration {

    @Autowired Environment env;

    @Override
    public String getDatabaseName(){
        return env.getRequiredProperty("mongo.name");
    }

    @Override
    @Bean
    public Mongo mongo() throws Exception {

        ServerAddress serverAddress = new ServerAddress(env.getRequiredProperty("mongo.host"));
        List<MongoCredential> credentials = new ArrayList<>();
        credentials.add(MongoCredential.createScramSha1Credential(
                env.getRequiredProperty("mongo.username"),
                env.getRequiredProperty("mongo.name"),
                env.getRequiredProperty("mongo.password").toCharArray()
        ));
        MongoClientOptions options = new MongoClientOptions.Builder()
            .build();
        return new MongoClient(serverAddress, credentials, options);
    }

}
like image 72
woemler Avatar answered Nov 05 '22 00:11

woemler