在Maven Spring项目中将不同的属性文件加载到persistence.xml中

时间:2019-04-25 04:49:00

标签: java spring maven

我有一种情况,我必须根据正在部署应用程序的环境将不同的方言,提供程序加载到我的persistence.xml文件中。

例如

在一个环境中,我正在使用Oracle11g,在另一个环境中,我正在使用MySql8。 我希望我的persistnece.xml看起来像这样。

<persistence-unit name="firstPU" transaction-type="RESOURCE_LOCAL">
        <provider>${somekey.provider}</provider>
        <properties>
            <property name="hibernate.dialect" value="${somekey.dialect}" />
        </properties>
</persistence-unit>

然后有两个单独的属性文件(first.property,second.property),并使用我的pom.xml中的构建配置文件选择其中一个。对于例如-

<profile> 
.
.
.
<build> 
            <resources> 
                <resource> 
                    <directory>src/main/resources/config/${build.profile.id}</directory> 
                    <excludes> 
                    <exclude>**/first.properties</exclude> 
                    </excludes> 
                </resource> 
            </resources> 
        </build>
.
.
.
</profile>

因此,根据所选的配置文件,它将排除一个.property文件,并从另一个文件读取。

所有这一切的问题是值从属性文件中返回为null。 (不再

我在这里错过了什么吗?还是有更好的方法来做这种事情?

更新-

这对于读取方言值很好。但是,我看不懂Provider!

是否可以从属性文件中读取提供者值?

2 个答案:

答案 0 :(得分:0)

抛弃:并使用占位符通过Spring配置persistence.xml。这样,您可以简单地添加属性文件并更改内容,而无需重新创建工件。

创建一个LocalEntityManagerFactory文件(或您喜欢的任何名称)并添加以下内容

application.properties

然后,假设您使用的是基于Java的配置,请添加一个spring.jpa.database-platform=org.hibernate.dialect.OracleDialect ,以(可选)从外部位置加载该文件。

@PropertySource

现在,您可以将方言(和其他属性,如果需要)更改为您喜欢的任何内容。

注意::该属性的名称与Spring Boot中的名称相同,因此您可以在切换到Spring Boot时重用此配置,该配置支持所有这些功能,开箱即用。

答案 1 :(得分:-1)

您可以在属性文件中定义所有这些数据库详细信息,而不必在persistence.xml中定义属性,而在构建脚本中,可以在war / ear中包含相应的属性文件。

final Properties persistenceProperties = new Properties();
InputStream is = null;

try {
    is = getClass().getClassLoader().getResourceAsStream("persistence.properties");
    persistenceProperties.load(is);
} finally {
    if (is != null) {
        try {
            is.close();
        } catch (IOException ignored) {
        }
    }
}

entityManagerFactory = Persistence.createEntityManagerFactory("firstPU", persistenceProperties);

请参阅此link以获取更多详细信息