主要介绍读取properties文件的使用。

    它也可以读取xml文件,请参考链接:https://commons.apache.org/proper/commons-configuration/userguide/quick_start.html

    导入依赖:

    1. <dependency>
    2. <groupId>org.apache.commons</groupId>
    3. <artifactId>commons-configuration2</artifactId>
    4. <version>2.6</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>commons-beanutils</groupId>
    8. <artifactId>commons-beanutils</artifactId>
    9. <version>1.9.3</version>
    10. </dependency>

    理论上只要导入 commons-configuration2 ,但是不导入 commons-beanutils 会报错。 😞😞

    image.png

    在classpath下新建测试文件config.properties

    database.host = db.acme.com
    database.port = 8199
    database.user = admin
    database.password = ???
    database.timeout = 60000
    

    代码示例:

    import org.apache.commons.configuration2.Configuration;
    import org.apache.commons.configuration2.builder.fluent.Configurations;
    
    public static void main(String[] args) throws Exception{
        Configurations configs = new Configurations();
    
        //classpath下的文件名
        Configuration config = configs.properties("config.properties");
    
        String dbHost = config.getString("database.host");
        int dbPort = config.getInt("database.port");
        String dbUser = config.getString("database.user");
        String dbPassword = config.getString("database.password", "secret");  // provide a default
        long dbTimeout = config.getLong("database.timeout");
    
        System.out.println("dbHost:"+dbHost);
        System.out.println("dbPassword:"+dbPassword);
    
    }
    

    如果需要配置文件自动重载功能的话,还是推荐hutool吧。这库贼难用!