![](/img/trans.png)
[英]loading .properties in spring-context.xml and persistence.xml
[英]Loading different properties files into persistence.xml in a maven spring project
我有一種情況,我必須根據要部署應用程序的環境將不同的方言,提供程序加載到我的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。 ( 不再 )
我在這里錯過了什么嗎?還是有更好的方法來做這種事情?
更新-
這對於讀取方言值工作正常。 但是,我看不懂提供者!
是否可以從屬性文件中讀取提供者值?
LocalEntityManagerFactory
persistence.xml
並使用占位符使用Spring配置LocalEntityManagerFactory
。 這樣,您可以簡單地添加屬性文件並更改內容,而無需重新創建工件。
創建一個application.properties
文件(或您喜歡的任何名稱)並添加以下內容
spring.jpa.database-platform=org.hibernate.dialect.OracleDialect
然后,假設您使用的是基於Java的配置,請添加一個@PropertySource
以從外部位置加載該文件(可選)。
@Configuration
@PropertySource("file:/conf/application.properties")
public class MyConfiguration {
@Autowired
private Environment env;
@Bean
public LocalContainerEntityManagerFactory entityManagerFactory(DataSource ds) {
LocalContainerEntityManagerFactory emf = new LocalContainerEntityManagerFactory();
emf.setDataSource(ds);
emf.setJpaVendorAdapater(jpaVendorAdapter());
// Other settings
return emf;
}
@Bean
public HibernateJpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabasePlatform(env.getRequiredProperty("spring.jpa.database-platform"));
return adapter;
}
}
現在,您可以將方言(和其他屬性,如果需要)更改為您喜歡的任何內容。
注意:選擇的屬性名稱與Spring Boot中的屬性名稱相同,以便在切換到支持所有現成功能的Spring Boot時可以重用此配置。
您可以在屬性文件中定義所有這些數據庫詳細信息,而不必在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);
請參閱此鏈接以獲取更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.