How to set build properties from a file in Maven POM?

后端 未结 2 1524
无人共我
无人共我 2021-02-09 01:15

I need to read and filter a properties file from a location outside my project, say ${user.home}/my.properties. This properties file looks like this:

res.dir         


        
2条回答
  •  青春惊慌失措
    2021-02-09 02:10

    I think it would be better if you turned the properties file into a template file and take the properties from the pom.xml using maven resource filtering.

    A simple setup might look like this

    pom.xml

    
        4.0.0
    
        com.stackoverflow
        Q12082277
        1.0-SNAPSHOT
    
        ${project.artifactId}-${project.version}
    
        
            /default/stuff/here
            ${res.dir}
            ${resource.dir}/bin
            ${resource.dir}/config
        
    
        
        
        
    
        
            
                
                    src/main/resources
                    true
                
            
        
    
    
    

    src/main/resources/app.properties

    res.dir=${res.dir}
    resource.dir=${resource.dir}
    bin.dir=${bin.dir}
    cfg.dir=${cfg.dir}
    

    src/main/java/com/stackoverflow/Q12082277/App.java

    package com.stackoverflow.Q12082277;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    /**
     * @author maba, 2012-08-23
     */
    public class App {
    
        public static void main(String[] args) throws IOException {
            ClassLoader loader = App.class.getClassLoader();
            InputStream in = loader.getResourceAsStream("app.properties");
            Properties properties = new Properties();
            properties.load(in);
            properties.list(System.out);
        }
    }
    

    System.out

    -- listing properties --
    resource.dir=/default/stuff/here
    cfg.dir=/default/stuff/here/config
    bin.dir=/default/stuff/here/bin
    res.dir=/default/stuff/here
    

    The pom.xml will have the default properties that are used by everybody.

    If you want to override the values then call maven with input parameters:

    mvn install -Dres.dir=/my/stuff/here -Dresource.dir="C:/${res.dir}"
    

    System.out

    -- listing properties --
    resource.dir=C://my/stuff/here
    cfg.dir=C://my/stuff/here/config
    bin.dir=C://my/stuff/here/bin
    res.dir=/my/stuff/here
    

    By doing it this way everybody will have the same view of the properties and you can override them if you want to when running on your own machine.

提交回复
热议问题