【发布时间】:2018-02-13 18:54:16
【问题描述】:
我有一个类似“控制器”的类
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 中的配置参数。
【问题讨论】:
标签: java spring mongodb spring-boot