在persistence.xml文件中读取环境变量 [英] Read Environment Variables in persistence.xml file

查看:705
本文介绍了在persistence.xml文件中读取环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取persistence.xml文件中的环境变量。

想法是我不希望我的数据库详细信息是从属性文件中读取,因为获取属性文件覆盖更改。我想从环境变量中读取详细信息。

Idea is that i don't want my database details to be read from properties file as there is a change of getting properties file override.Instead i want to read details from environment variables.

有没有办法达到此标准。

Is there any way to achieve this criteria.

Iam使用Spring 3我的独立应用程序将部署在unix机器中。

Iam using Spring 3 my standalone application will be deployed in unix machine.

推荐答案

您可以通过提供Map来更新持久性单元中的属性(请参阅这个)。

You can update properties in a persistence unit by supplying a Map (see this).

方便的是,环境变量可以作为Map检索(参见这个)。

Conveniently, environment variables can be retrieved as a Map (see this).

把两个在一起,您可以动态更新属性带有环境变量的持久性单元。

Put the two together and you can dynamically update properties in your persistence unit with environment variables.

编辑:简单示例...

persistence.xml ...

persistence.xml...

<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
    <provider>
        oracle.toplink.essentials.PersistenceProvider
    </provider>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
        <property name="toplink.logging.level" value="INFO"/>
        <property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
        <property name="toplink.jdbc.url" value="jdbc:oracle:thin:@myhost:l521:MYSID"/>
        <property name="toplink.jdbc.password" value="tiger"/>
        <property name="toplink.jdbc.user" value="scott"/>
    </properties>
</persistence-unit>

使用环境变量更新persistence.xmldefault单元的代码...

code that updates persistence.xml "default" unit with environment variables...

Map<String, String> env = System.getenv();
Map<String, Object> configOverrides = new HashMap<String, Object>();
for (String envName : env.keySet()) {
    if (envName.contains("DB_USER")) {
        configOverrides.put("toplink.jdbc.user", env.get(envName)));    
    }
    // You can put more code in here to populate configOverrides...
}

EntityManagerFactory emf =
    Persistence.createEntityManagerFactory("default", configOverrides);

这篇关于在persistence.xml文件中读取环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆