[英]Spring Boot with Morphia Configuration: BeanCreationException
[英]Spring Boot configuration with Morphia?
我不想利用Spring DATA MongoDB支持。 我想利用名為Morphia的MongoDB的ORM。
https://github.com/mongodb/morphia
我想用Spring Boot配置Morphia。 我想以一種遵循Spring Boot理念的方式外化Morphia的配置。
我想利用環境變量來配置Morphia屬性。
實現這一目的的Spring Boot方法是什么?
在一個簡單的主程序中會做以下事情以使Morhpia ORM正常工作。
private Morphia morphia;
private MongoClient mongoClient;
morphia = new Morphia();
// Person is an entity object with Morphia annotations
morphia.map(Person.class);
// THESE properties MUST be read from environment variables in Spring BOOT.
final String host = "localhost";
final int port = 27017;
mongoClient = new MongoClient(host, port);
//Set database
// this instance would be autowired all data access classes
Datastore ds = morphia.createDatastore(mongoClient, "dataStoreInstanceId");
// this is how instance would be used in those data accesses classes
Person p = ds.find(Person.class, "username", "john").get();
類似Spring Boot的方法是創建一個具有所需屬性的AutoConfiguration,它創建一個Datastore
實例作為bean。
在參考指南中,您將了解如何設置屬性並連接到MongoDB。
Morphia的AutoConfiguration可能如下所示:
@Configuration
public class MorphiaAutoConfiguration {
@Autowired
private MongoClient mongoClient; // created from MongoAutoConfiguration
@Bean
public Datastore datastore() {
Morphia morphia = new Morphia();
// map entities, there is maybe a better way to find and map all entities
ClassPathScanningCandidateComponentProvider entityScanner = new ClassPathScanningCandidateComponentProvider(true);
entityScanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
for (BeanDefinition candidate : scanner.findCandidateComponents("your.basepackage")) { // from properties?
morphia.map(Class.forName(candidate.getBeanClassName()));
}
return morphia.createDatastore(mongoClient, "dataStoreInstanceId"); // "dataStoreInstanceId" may come from properties?
}
}
然后,您可以通常的方式在其他Spring bean中自動裝配數據存儲區:
@Autowired
private Datastore datastore;
如果某些點不正確或不清楚,請查看Spring Boot中現有的*AutoConfiguration
類。
我正在為春季啟動工作,這是回購。 很容易使用,在某些日子里會在maven中心更新它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.