1.添加依赖
<dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.24</version> </dependency>
2.新建自定义Prop类
package cn.flyinke.test; import com.jfinal.kit.Prop; import org.yaml.snakeyaml.Yaml; import java.io.InputStream; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; /** * @author flyinke * @time 2019-04-14 * @description */ public class YamlProp extends Prop { public YamlProp(String yamlFile) { setYaml(yamlFile); } private void setYaml(String yamlFile){ LinkedHashMap map = null; Properties properties = new Properties(); InputStream in = null; try { Yaml yaml = new Yaml(); in = YamlProp.class.getClassLoader().getResourceAsStream(yamlFile); map = yaml.loadAs(in, LinkedHashMap.class); } catch (Exception e) { e.printStackTrace(); } setProperties(properties,map,""); this.properties = properties; } private static void setProperties(Properties properties, Map map, String prefix) { for (Object key :map.keySet()){ Object value = map.get(key); if(key == null){ continue; } if(value instanceof Map){ setProperties(properties, (Map) value,prefix+key.toString()+"."); }else { if(value == null){ continue; } //System.out.println(prefix+key.toString()+"="+value.toString()); properties.setProperty(prefix+key.toString(),value.toString()); } } } }
3. JfinalConfig文件中设置下
private static Prop p = loadConfig(); private static Prop loadConfig() { return PropKit.append(new YamlProp("application-local.yml")); }
4. 完成