【问题标题】:How to updates values of properties files from pom.xml如何从 pom.xml 更新属性文件的值
【发布时间】:2019-11-30 17:04:22
【问题描述】:

我想在运行 mvn 测试时从 pom.xml 更新 application.properties 文件值。 值必须在运行时从 pom.xml 传递到 application.properties pom.xml

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>    
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M4</version>
                    <configuration>
                        <suiteXmlFiles>
                            <suiteXmlFile>src/test/resources/phomeTestNg.xml</suiteXmlFile>
                        </suiteXmlFiles>
                    </configuration>
                </plugin>    
            </plugins>  
        </pluginManagement>
        <resources>
            <resource>
                <directory>src/test/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build> 

application.properties 文件 gapp=${project.build.sourceEncoding}

java代码

        FileReader reader=new 
        FileReader(System.getProperty("user.dir")+"\\src\\test\\resources\\application.properties");          
        Properties p=new Properties();  
        p.load(reader);           
        System.out.println("Properties  "+p.getProperty("gapp"));  

文件夹结构

【问题讨论】:

  • 这是一个 Spring Boot 应用程序吗?
  • 不,这是简单的 maven 项目
  • 首先通过类路径而不是通过 FileReader 加载您的属性,因为这在 jar 中不起作用...所以最好使用this.getClass().getResourceAsStream("/application.properties)。其次,您希望从 pom 文件中更新哪种值?

标签: java maven pom.xml


【解决方案1】:

有一个名为properties-maven-plugin 的插件。这将创建一个具有您指定名称的属性文件。然后您可以像在任何属性文件中一样直接访问所有变量。这可能不是确切的解决方案。但也许会给你一个方向。 这是一个代码示例,可以查看它。这将是你的 pom:

<properties>
    <name>${project.name}</name>
     <version>${project.version}</version>
     <foo>bar</foo>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>properties-maven-plugin</artifactId>
            <version>1.0.0</version>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>write-project-properties</goal>
                    </goals>
                    <configuration>
                        <outputFile>${project.build.outputDirectory}/my.properties</outputFile>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

从另一个问题得到这个代码。 https://stackoverflow.com/a/26589696/7241652

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2018-06-04
    • 2017-08-28
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多