Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

java - Reading properties file from Maven POM file

I have Maven POM file with some configuration and in the section plugins, I have maven tomcat plugin with some configuration like this:

<configuration>
   <url>http://localhost:8080/manager/html</url>
   <server>tomcat</server>
</configuration>

I'd like to export url setting to some property file for example tomcat.properties with that key:

url=http://localhost:8080/manager/html

And how can I read this key back in my POM file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Maven allows you to define properties in the project's POM. You can do this using a POM file similar to the following:

<project>
    ...
    <properties>
        <server.url>http://localhost:8080/manager/html</server.url>
    </properties>
    ...
    <build>
        <plugins>
            <plugin>
            ...
                <configuration>
                    <url>${server.url}</url>
                    <server>tomcat</server>
                </configuration>
            ...
            </plugin>
        </plugins>
    </build>
</project>

You can avoid specifying the property within the properties tag, and pass the value from the command line as:

mvn -Dserver.url=http://localhost:8080/manager/html some_maven_goal

Now, if you don't want to specify them from the command line and if you need to further isolate these properties from the project POM, into a properties file, then you'll need to use the Properties Maven plugin, and run it's read-project-properties goal in the initialize phase of the Maven lifecycle. The example from the plugin page is reproduced here:

<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-2</version>
        <executions>
           <!-- Associate the read-project-properties goal with the initialize phase, to read the properties file. -->
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>etc/config/dev.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...