带有显式模板的SpringBoot mongo配置无法启动

时间:2018-02-13 18:54:16

标签: java spring mongodb spring-boot

我有一个"控制器"类似

MongoController.java:

@EnableMongoRepositories(mongoTemplateRef="mainMongoTemplate")
@RestController
public class MongoController {
    @Autowired
    MongoPersonRepository mrepo;

mongo配置类 MainMongoConfig.java

@Configuration
@ConfigurationProperties(prefix = "main.mongodb")
public class MainMongoConfig extends AbstractMongoConfig {
    @Primary
    @Override
    @Bean(name="mainMongoTemplate")
    public MongoTemplate getMongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory());
    }
}

AbstractMongoConfig是:

public abstract class AbstractMongoConfig {
    private String host;
    private int port;
    private String database;

    public MongoDbFactory mongoDbFactory() throws Exception {
        return new SimpleMongoDbFactory(new MongoClient(host, port), database);
    }

    abstract public MongoTemplate getMongoTemplate() throws Exception;
}

MongoPersonRepository只是一个带有一些findBy的简单类......没什么特别的。

public interface MongoPersonRepository extends MongoRepository<MongoPerson, String> {
    public MongoPerson findByName(String name);
    public List<MongoPerson> findByAge(int age);
}

application.properties:

main.mongodb.uri=mongodb://localhost:27017/main

启动时无法启动,因为:

2018-02-13 13:44:59.918  WARN 32194 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean
with name 'mongoController': Unsatisfied dependency expressed through field 'mrepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoPersonRepository': Cannot resolve reference to bean 'mainMongoTemplate'
 while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainMongoTemplate' defined in class path resource [hello/mongo/MainMongoConfig.class]: Bean instantiation via fac
tory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'getMongoTemplate' threw exception; nested exception is java.lang.IllegalArgumentEx
ception: Database name must not be empty!

抱怨什么?数据库名称不为空...我是否正确配置参数前缀?最后,我想拥有多个MongoConfig,并使用存储库或在mongoTemplate上使用@Qualifier。

看起来我需要以某种方式覆盖AbstractMongoConfig中的配置参数。

1 个答案:

答案 0 :(得分:1)

所以,问题是你需要为Abstract类提供普通的旧setter。将其更改为使用URI:

private String uri;

public void setUri(String uri) {
    this.uri = uri;
}

public MongoDbFactory mongoDbFactory() throws Exception {
    return new SimpleMongoDbFactory(new MongoClientURI(uri));
}

abstract public MongoTemplate getMongoTemplate() throws Exception;

此外,似乎无法禁用“默认”mongo连接。如果你将配置中的main.mongodb.uri设置为其他东西,它仍然会尝试连接到localhost。