Java 在maven spring项目中将不同的属性文件加载到persistence.xml中
我有一个场景,需要根据部署应用程序的环境将不同的方言、提供者加载到persistence.xml文件中 例如 在一个环境中我使用Oracle11g,在另一个环境中我使用MySql8。 我希望persistence.xml看起来像这样Java 在maven spring项目中将不同的属性文件加载到persistence.xml中,java,spring,maven,Java,Spring,Maven,我有一个场景,需要根据部署应用程序的环境将不同的方言、提供者加载到persistence.xml文件中 例如 在一个环境中我使用Oracle11g,在另一个环境中我使用MySql8。 我希望persistence.xml看起来像这样 <persistence-unit name="firstPU" transaction-type="RESOURCE_LOCAL"> <provider>${somekey.provider}</provider>
<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,并使用my pom.xml中的build profile选择其中一个。例如-
<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。不再是了
我是不是遗漏了什么,还是有更好的方法来做这类事情
更新-
这对于读取方言值非常有效。但是,我无法阅读提供程序
也可以从属性文件读取提供程序值吗?您可以在属性文件和构建脚本中定义所有这些数据库详细信息,而不是在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);
有关更多详细信息,请参阅此文件放弃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时可以重用此配置,Spring Boot支持所有这些现成的配置 问题是如何使用Spring实现这一点。您不需要加载自己的属性,因为Spring提供了开箱即用的支持。这对于读取方言信息非常有用。但是没有从属性文件加载提供程序。请参阅更新的帖子。您的持久性提供程序必须相同。您可以单独初始化它