1、读取配置文件:example.setting
[demo] ds.setting.path = config/other.setting driver = com.mysql.jdbc.Driver url = jdbc:mysql://fedora.vmware:3306/extractor user = root${demo.driver} pass = 123456 port = 3306
2、测试代码:
import cn.hutool.setting.Setting; import cn.hutool.setting.dialect.Props; public class SettingTest { public static void main(String[] args) {
//方式一、使用Setting类 //读取配置文件所有的内容 Setting setting = new Setting("example.setting"); System.out.println(setting);
//{demo={ds.setting.path=config/other.setting, driver=com.mysql.jdbc.Driver, url=jdbc:mysql://fedora.vmware:3306/extractor, user=root${demo.driver}, pass=123456, port=3306}} //读取配置文件中键为driver的值 String driver1 = setting.getStr("driver","默认值"); System.out.println(driver1); //默认值 //读取分组为demo里面的键为driver的值 Object driver = setting.getByGroup("driver","demo"); System.out.println(driver); //com.mysql.jdbc.Driver //读取分组为demo里面的键为driver的值 String str = setting.getStr("driver", "demo", "默认值"); System.out.println(str); //com.mysql.jdbc.Driver String driver2 = setting.getWithLog("driver"); System.out.println(driver2); //null String byGroupWithLog = setting.getByGroupWithLog("driver", "demo"); System.out.println(byGroupWithLog); //com.mysql.jdbc.Driver Setting demo = setting.getSetting("demo"); System.out.println(demo);
//{={ds.setting.path=config/other.setting, driver=com.mysql.jdbc.Driver, url=jdbc:mysql://fedora.vmware:3306/extractor, user=root${demo.driver}, pass=123456, port=3306}} //在配置文件变更时自动加载 setting.autoLoad(true);
//方式二、使用Props类 //使用Props类,props继承了properties Props props = new Props("example.setting"); String driver3 = props.getProperty("driver"); System.out.println(driver3); //com.mysql.jdbc.Driver String driver4 = props.getStr("driver"); System.out.println(driver4); //com.mysql.jdbc.Driver } }