Access maven properties defined in the pom

前端 未结 5 1277
广开言路
广开言路 2020-11-27 14:30

How do I access maven properties defined in the pom in a normal maven project, and in a maven plugin project?

相关标签:
5条回答
  • 2020-11-27 14:49

    Maven already has a solution to do what you want:

    Get MavenProject from just the POM.xml - pom parser?

    btw: first hit at google search ;)

    Model model = null;
    FileReader reader = null;
    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
    
    try {
         reader = new FileReader(pomfile); // <-- pomfile is your pom.xml
         model = mavenreader.read(reader);
         model.setPomFile(pomfile);
    }catch(Exception ex){
         // do something better here
         ex.printStackTrace()
    }
    
    MavenProject project = new MavenProject(model);
    project.getProperties() // <-- thats what you need
    
    0 讨论(0)
  • 2020-11-27 14:57

    This can be done with standard java properties in combination with the maven-resource-plugin with enabled filtering on properties.

    For more info see http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

    This will work for standard maven project as for plugin projects

    0 讨论(0)
  • 2020-11-27 15:07

    You can parse the pom file with JDOM (http://www.jdom.org/).

    0 讨论(0)
  • 2020-11-27 15:09

    Use the properties-maven-plugin to write specific pom properties to a file at compile time, and then read that file at run time.

    In your pom.xml:

    <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>
    

    And then in .java:

    java.io.InputStream is = this.getClass().getResourceAsStream("my.properties");
    java.util.Properties p = new Properties();
    p.load(is);
    String name = p.getProperty("name");
    String version = p.getProperty("version");
    String foo = p.getProperty("foo");
    
    0 讨论(0)
  • 2020-11-27 15:14

    Set up a System variable from Maven and in java use following call

    System.getProperty("Key");
    
    0 讨论(0)
提交回复
热议问题