加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – 使用Morphia的Spring Boot配置?

发布时间:2020-12-15 01:25:04 所属栏目:大数据 来源:网络整理
导读:我不想利用Spring DATA MongoDB支持. 我想利用名为Morphia的MongoDB的ORM. https://github.com/mongodb/morphia 我想用Spring Boot配置Morphia.我想以一种遵循Spring Boot理念的方式外化Morphia的配置. 我想利用环境变量来配置Morphia属性. 实现这一目的的Sp

我不想利用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.

在Reference Guide中,您将找到如何设置属性并连接到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类.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读