java - 使用maven属性插件读取数据库信息

标签 java maven intellij-idea

我正在尝试读取数据库属性文件来初始化我的数据库,并且我正在使用 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 中并运行它时,出现以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Error loading database configuration file.

最佳答案

我认为您可能误解了 Maven 属性插件的意义,并且我认为这里没有必要,稍后会详细介绍。

根据您发布的一点信息,我可以猜测为什么它没有加载属性文件。

捕获的IOException很可能是FileNotFoundException。看起来您已将属性文件放置在 src/resources 中,但按照Maven convention ,它们应该位于 src/main/resources 中。

将属性文件移到那里,它们现在应该正确地位于类路径上。此外,可能有一种更简洁的方法来检索属性:

dbProperties.load(DatabaseSetting.class.getResourceAsStream(dbPropertiesName));

Maven 属性插件

因为,看起来您只是尝试从文件加载属性以在运行时使用,所以此处不需要 Maven 属性插件。根据配置,此插件只会将属性加载到 Maven 构建上下文中,但它不会以任何方式帮助加载程序中的属性。您可以安全地从 pom 中删除插件声明。

关于java - 使用maven属性插件读取数据库信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48096634/

相关文章:

java - 在Java中,是否可以清除位?

java - Java 中的抑制异常

java - dependency-check-maven - 抑制不起作用

java - 使用 Git 查找 TODO 的日期

java - WebSocket 服务器 (Java) 无法读取但发送到 C# (Unity) 客户端

java - org.springframework.web.WebApplicationInitializer 未找到

java - 使用一个项目作为另一个项目的 Maven 依赖项

java - 禁用 IntelliJ IDEA 中的所有提示

debugging - 如何调试已部署的 Grails 应用程序

C# ArrayList 的 Java 等效项