Step 1: Add “snakeyaml” to maven pom.xml as a dependency
1 2 3 4 5 6 7 | <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.17</version> </dependency> |
Step 2: Define a YAML file under src/main/resources. For example, “logging.yml”
1 2 3 4 5 6 | paths: logsPath: /mylogs packagePrefix: com.myapp |
Step 3: Create a LoggingConfiguration Java POJO class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.util.Map; public class LogConfiguration { private Map<String, String> paths; private String packagePrefix; public Map<String, String> getPaths() { return paths; } public void setPaths(Map<String, String> paths) { this.paths = paths; } public String getPackagePrefix() { return packagePrefix; } public void setPackagePrefix(String packagePrefix) { this.packagePrefix = packagePrefix; } @Override public String toString() { return "LogConfiguration [paths=" + paths + "]"; } } |
Step 4: Finally, the main class that uses the Yaml library to read the configuration from the “logging.yml” file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import java.io.InputStream; import org.yaml.snakeyaml.Yaml; public class TestYaml { public static void main(String[] args) { LogConfiguration config = null; Yaml yaml = new Yaml(); try(InputStream in = ClassLoader.getSystemResourceAsStream("logging.yml")) { config = yaml.loadAs(in, LogConfiguration.class); } catch(Exception ex) { ex.printStackTrace(); } String path = config.getPaths().get("logsPath"); System.out.println("path=" + path); String packagePrefix = config.getPackagePrefix(); System.out.println("packagePrefix=" + packagePrefix); } } |
Output:
1 2 3 4 | path=/mylogs packagePrefix=com.myapp |
Learn YAML basics at YAML with Spring & Java Q&As