主要介绍读取properties文件的使用。
它也可以读取xml文件,请参考链接:https://commons.apache.org/proper/commons-configuration/userguide/quick_start.html
导入依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
理论上只要导入 commons-configuration2
,但是不导入 commons-beanutils
会报错。 😞😞
在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吧。这库贼难用!