我正在尝试读取数据库属性文件以初始化我的数据库,并且我正在使用maven。所以我在pom.xml中指定了以下插件:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-1</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${basedir}/src/resources/database.properties</file>
<file>${basedir}/src/resources/databaseTest.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
但是我不知道如何在代码中正确地加载它,我在这里将“ /database.properties”作为参数发送给我的加载方法,但是它不起作用:
public static DatabaseSetting loadSettings(String dbPropertiesName) {
String dbPropertiesPath = DatabaseSetting.class.getResource
(dbPropertiesName).getPath();
Properties dbProperties = new Properties();
try {
dbProperties.load(new FileInputStream(new File(dbPropertiesPath)));
String host = dbProperties.getProperty("host");
String username = dbProperties.getProperty("username");
String password = dbProperties.getProperty("password");
String databaseName = dbProperties.getProperty("databaseName");
String table = dbProperties.getProperty("table");
return new DatabaseSetting(databaseName, host, username,
password, table);
} catch (IOException e) {
throw new RuntimeException("Error loading database configuration " +
"file.");
}
}
这在IntelliJ中工作正常,但是当我将其打包在maven中并运行时,出现以下错误:
线程“ AWT-EventQueue-0”中的异常java.lang.RuntimeException:
加载数据库配置文件时出错。
最佳答案
我认为您可能误解了Maven属性插件的要点,我认为这里没有必要,但稍后会介绍更多。
有了您发布的内容,我可以猜测一下为什么它没有加载属性文件。
捕获的IOException
很可能是FileNotFoundException
。似乎您已将属性文件放置在src/resources
中,但是对于Maven convention,它们应位于src/main/resources
中。
将属性文件移到那里,它们现在应该正确地位于类路径上。另外,可能有一种更干净的方法来检索属性:
dbProperties.load(DatabaseSetting.class.getResourceAsStream(dbPropertiesName));
Maven属性插件
因为看起来好像您只是在尝试从文件中加载属性以在运行时使用,所以此处不需要Maven属性插件。按照配置,此插件将仅将属性加载到Maven构建上下文中,但对以任何方式加载程序中的属性都没有帮助。您可以安全地从pom中删除插件声明。