我不想利用 Spring DATA MongoDB 支持。
我想利用名为 Morphia 的 MongoDB ORM。
https://github.com/mongodb/morphia 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
作为豆子。
In the 参考指南 http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-mongodb您将了解如何设置属性并连接到 MongoDB。
Morphia 的自动配置可能如下所示:
@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;
如果有些观点不正确或不清楚,请查看现有的*AutoConfiguration
Spring Boot 中的类。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)