gpt4 book ai didi

java - Spring+Hibernate应用程序的环境特定配置

转载 作者:行者123 更新时间:2023-11-30 03:22:14 25 4
gpt4 key购买 nike

我正在努力使用不同的 hibernate .properties 文件来配置我的 Spring 应用程序。我的计划是创建一个 Maven 属性,该属性将反射(reflect)我想要选择的环境,通过配置文件选择。然后在我的 hibernate.cfg.xml 上将加载属性变量。

文件:hibernate.cfg.xml:

.... <property name="hbm2ddl.auto">${hibernate.hbm2ddl.auto}</property>  ...

文件:persistence-dev.properties:

... hibernate.hbm2ddl.auto = create ...

文件:spring-context.xml:

... <context:property-placeholder location="classpath*:*persistence-${envTarget}.properties" /> ...

我在这里缺少什么?

最佳答案

hibernate.cfg.xml 不由 Spring 管理。

尝试使用 PropertyPlaceholderConfigurer(或其替代品 PropertySourcesPlaceholderConfigurer)来过滤它是没有用的。

您可以做的是使用 Maven 资源过滤支持:

<profiles>
<profile>
<id>dev</id>
<properties>
<hibernate.hbm2ddl.auto>dev</hibernate.hbm2ddl.auto>
</properties>
</profile>

<profile>
<id>prod</id>
<properties>
<hibernate.hbm2ddl.auto>validate</hibernate.hbm2ddl.auto>
</properties>
</profile>
</profiles>

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>

您还可以将其与 Spring 配置文件支持结合使用(假设您愿意在构建时将 Spring 配置文件名称传递给 Maven,而不仅仅是使用运行时,如果您从 Maven 运行与 Spring 配置文件相关的测试,您无论如何都会这样做) :

    <profile>
<activation>
<property>
<name>spring.profiles.active</name>
<value>dev</value>
</property>
</activation>
<properties>
<hibernate.hbm2ddl.auto>dev</hibernate.hbm2ddl.auto>
</properties>
</profile>
...

关于java - Spring+Hibernate应用程序的环境特定配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31082079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com