In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to understand Yaml, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
In the world of Java, configuration is left to Properties, and the module dates back to the ancient JDK1.0.
"Oh, my God, this is from 20 years ago. I can't believe I'm still using Properties..."
However, the protagonist of this article is not Properties, but Yaml. This is the darling of the micro-service architecture in the new era, and compared with Properties, Yaml appears to be a bit of a trendsetter.
In most previous projects, we can find traces of Properties configuration files, including those used for business attribute configuration, machine interface, internationalization, and so on.
In a few cases, there are also some "hybrid" practices, such as:
Use Xml to represent some templates
Use a Json-formatted string
Streaking text format, applying self-parsing
...
Mixed configuration methods often appear in some projects full of "bad smell", because the code is outdated, people have died and other reasons, it is difficult to form a unified way.
However, in addition to the simple configuration of Properties properties files, other methods are nothing more than to adapt to the complex and diversified requirements of configuration.
In that case, Yaml is created in response to this scenario, and there is a lot of space in the official document of SpringBoot that uses the configuration format of the Yaml syntax.
Let's take a look at Yaml and how it is used.
What is Yaml
Definition from encyclopedia:
"Yaml is a highly readable and easy-to-use data serialization format first published by Clark Evans in 2001."
It can be seen that Yaml is not a very new thing, but not many people have come into contact with it in the past. In addition, Yaml is also supported by various programming languages and frameworks with high versatility.
In the Java system, the general micro-service framework supports or even preferentially recommends Yaml as the preferred configuration language.
What are the characteristics of Yaml itself? Take a look at the following example:
Environments: dev: url: https://dev.example.com name: Developer Setup prod: url: https://another.example.com name: My Cool App
The syntax equivalent Properties for this paragraph is:
Environments.dev.url= https://dev.example.comenvironments.dev.name=Developer Setupenvironments.prod.url= https://another.example.comenvironments.prod.name=My Cool App
It can be seen that yaml is relatively more structured and more suitable for expressing an object.
It has the following grammatical features:
Case sensitive
Use space indentation to express hierarchical relationships and abandon the use of the Tab key, which is mainly due to the need for alignment when displaying text on different platforms
The number of indented spaces does not matter, as long as the elements at the same level are aligned to the left
Start with # as a comment line
Use the start of the connector (-) to describe array elements
Contrast Properties
Properties can well implement the configuration of Key-Value, including configuration as some international content.
However, it is difficult for Properties to show multi-level nesting relationship, so using Yaml can make up for this deficiency.
Contrast Json
Yaml and Json themselves do not have many advantages and disadvantages, both are structured expression languages, but the design of Json focuses on the features of easy to use and convenient transmission.
Yaml, on the other hand, focuses on readability (more about appearance) and can almost think of Yaml as a "superset" of Json, a structured format that is more readable (more beautiful).
In addition, Json is easier to generate and parse, suitable for transmission and interaction in a variety of cross-language, distributed environments; at the same time, Yaml is generally only used for more configurations.
The definition of Yaml can be accessed at the following address:
Http://www.yaml.org/spec/1.2/spec.html
Second, the grammar of Yaml
Yaml is very simple and defines only three elements:
Object: a collection of key-value pairs corresponding to HashMap in Java
Array: a sequential set of values that correspond to List in Java
Single value: a single, inseparable value, such as 3, "Jackson"
How objects are represented
The attributes and nesting relationships of an object are represented by space indentation alignment, as follows:
Article: title: a person's confession author: name: Chen Ling gender: female
How to represent an array
The elements of the array are represented by the connector (-), as follows:
Article: title: a man's confession tags:-Biography-Society-characters
The basic units that make up the contents of objects and arrays are single values. There are seven types of single values supported by Yaml, as follows:
Type sample string Bob Boolean value true Integer 19.91 Null ~ time 2001-12-14T22:14:09.10+08:00 date 2019-01-09
Among them, the date and time are in the ISO 8601 international standard format. For its definition, please refer to:
Https://www.w3.org/TR/NOTE-datetime
Typically, a single value ends in a row. However, if you encounter a string with multiple lines, you can use some special characters to represent it.
For example:
Text: | Hello World
The corresponding results are:
{text: 'Hello\ nWorld\ n'}
You can use + to retain the newline at the end of the string, and-to delete the newline at the end of the string:
Text1: | + Hellotext2: |-Hello
The corresponding results are:
{text1: 'Hello\ n\ n\ n, text2:' Hello'}
In addition, Yaml can also support advanced usage such as references, functions, regular expressions, and so on, but it is rarely used in projects.
Third, operate Yaml
Currently, the common component used to manipulate Yaml is Snake Yaml, which supports the standard Yaml version 1.1.
The SpringBoot official documentation also describes how to integrate the framework, refer to the following address:
Https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-loading-yaml
An example of integrating SnakeYaml into a project is provided below.
a. Introduction of framework
Add to the pom.xml file of Maven:
Org.yaml snakeyaml 1.21B. Code snippet
Implement loading configuration file
As in the following code, the yaml configuration content is loaded from the classpath config.yml file:
InputStream inputStream = YamlUtil.class.getClassLoader () .getResourceAsStream ("config.yml"); Yaml yaml = new Yaml (); Map objectMap = yaml.load (inputStream); System.out.println (objectMap.get ("path"))
Implement object conversion
Define the following Pojo object:
Public static class A {private String name = "hello"; private List bs = new ArrayList (); public String getName () {return name;} public void setName (String name) {this.name = name;} public List getBs () {return bs;} public void setBs (List bs) {this.bs = bs } public static class B {private String id = UUID.randomUUID () .toString (); public String getId () {return id;} public void setId (String id) {this.id = id;}}
Output the object to code in Yaml format through SnakeYaml:
AA = new A (); a.getBs (). Add (new B ()); a.getBs (). Add (new B ()); Yaml yaml = new Yaml (); String aString = yaml.dumpAsMap (a); System.out.println (aString)
The output is as follows:
Bs:- id: b3688f05mure7eMur436bc9aMus9c5df555c7fd-id: 7906224d-8ecc-43b8-bc3b-07985bc18ebdname: hello
At this point, if you want to convert the Yaml text to an An object in turn, you can execute the following code:
An A1 = new Yaml (). ParseToObject (aString, A.class);. C. Complete case
Finally, we can encapsulate the operation of the Yaml document into a tool class to facilitate integration in the business code.
YamlUtil.java
Public class YamlUtil {/ * loads the content from the resource file and parses it to the Map object * * @ param path * @ return * / public static Map loadToMap (String path) {if (StringUtils.isEmpty (path)) {return Collections.emptyMap ();} InputStream inputStream = YamlUtil.class.getClassLoader () .getResourceAsStream (path) Yaml yaml = new Yaml (); Map objectMap = yaml.load (inputStream); return objectMap;} / * * parse a string into a Map object * * @ param content * @ return * / public static Map parseToMap (String content) {if (StringUtils.isEmpty (content)) {return Collections.emptyMap () } Yaml yaml = new Yaml (); Map objectMap = yaml.load (content); return objectMap } / * parse strings into class objects * * @ param content * @ param clazz * @ param * @ return * / public static T parseToObject (String content, Class clazz) {if (StringUtils.isEmpty (content) | | clazz = = null) {return null;} Yaml yaml = new Yaml (new Constructor (clazz)) T object = yaml.load (content); return object;} / * * format object * * @ param object * @ return * / public static String format (Object object) {Yaml yaml = new Yaml (); return yaml.dumpAsMap (object);}}
At this point, we have finished reading and writing Yaml.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.