spring data mongo - 没有名为&mongoTemplate的bean#39;已定义

时间:2016-02-29 21:10:41

标签: java spring mongodb spring-data spring-data-mongodb

我有一个spring数据mongo存储库类

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

在测试配置中,我使用EnableMongoRepositories注释

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

当我尝试测试使用此存储库的服务类时,它会抛出异常

  

引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为&mongoTemplate的bean#39;被定义为       在org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698)〜[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]       在org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175)〜[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]       在org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)〜[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]       在org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)〜[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]       在org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)〜[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]       ...省略了57个常见帧

1 个答案:

答案 0 :(得分:2)

@EnableMongoRepositories注释将在启动时触发存储库bean的创建,但您仍需要注册MongoDB连接并创建注入这些存储库的MongoTemplate实例。请参阅Spring Data MongoDB documentation。这是一个例子:

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

}