gpt4 book ai didi

java - Maven 读取 .properties 以在 pom.xml 中使用

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:27:56 25 4
gpt4 key购买 nike

我试图让 properties-maven-plugin 从我的 .properties 文件中读取。 Flyway(我正在尝试使用这些属性)只是不断抛出有关 db url 格式错误的错误,但如果我在 pom.xml 本身中设置值而不是使用从文件中读取的属性,则可以正常工作。

我将 eclipse 与 m2e 插件一起使用。

从 .properties 中读取的插件配置

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-2</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>src/main/resources/config.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>

正在使用属性的 Flyway 配置

<plugin>
<groupId>com.googlecode.flyway</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>flyway:migrate</goal>
</goals>
</execution>
</executions>
<configuration>
<driver>${db.driver}</driver>
<url>${db.url}</url>
<user>${db.user}</user>
<password>${db.password}</password>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
</dependencies>
</plugin>

config.properties 位于/src/main/resources/

# Database details
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/dbname
db.user=username
db.pass=password

我尝试查看其他几个 stackoverflow 线程,但似乎没有一个解决方案有效。我是 maven 的新手,整个事情似乎让我很困惑,有人有灯要照亮吗?

最佳答案

基本上有两种方法可以执行 Flyway 迁移目标:

  1. 作为生命周期阶段的一部分:您已将 Flyway 插件配置为在编译阶段执行。这意味着您只需输入 mvn compile,Flyway 将与属于该生命周期阶段和所有先前阶段的所有其他目标一起执行。一切正常,除了你有一个轻微的错误配置:目标不能有前缀。为了解决这个问题,您必须提供不带前缀的目标:

    <goals>
    <goal>migrate</goal>
    </goals>

    现在执行工作了。 Flyway 从 properties-maven-plugin 获取所有参数,因为它是在前一个阶段执行的。

  2. 直接调用:如果您使用 mvn flyway:migrate 执行 Flyway,插件将独立于任何生命周期阶段被调用。由于没有执行任何阶段,properties-maven-plugin 也不会执行,因为它依赖于初始化阶段 - 实际上不设置任何参数。这就是 Flyway 提示缺少参数的原因。

解决方案:如果您希望 properties-maven-plugin 与 Flyway 一起工作,您必须将 Flyway 作为生命周期的一部分执行。如果您不想在每个编译阶段都调用它,您可以创建一个单独的配置文件,并且只在需要使用 mvn compile -PflywayMigration 进行 Flyway 迁移时运行此配置文件:

<profiles>
<profile>
<id>flywayMigration</id>
<build>
<plugins>
<plugin>
<groupId>com.googlecode.flyway</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>migrate</goal>
</goals>
</execution>
</executions>
<configuration>
<driver>${db.driver}</driver>
<url>${db.url}</url>
<user>${db.user}</user>
<password>${db.password}</password>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</profile>
</profiles>

关于java - Maven 读取 .properties 以在 pom.xml 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19049332/

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