SoFunction
Updated on 2025-05-23

Java Development Diary: Do you know 5 ways to read yml files in 5 types

Preface

Except for the streets@Valueand@ConfigurationPropertiesIn addition, what other ways can we read the content of the yml configuration file?

1、Environment

There is a class in SpringEnvironment, it can be considered the environment in which the current application is running, it inherits thePropertyResolverinterface, so it can be used as a property parser. First create a yml file, the properties are as follows:

person:
  name: hydra
  gender: male
  age: 18

It's very simple to use, just use it directly@AutowiredYou can inject it into the class you want to use and then call itgetProperty()The method can extract the corresponding value according to the attribute name.

@RestController
public class EnvironmentController {
    @Autowired
    private Environment environment;
    @GetMapping("envTest")
    private void getEnv(){
        ((""));
        ((""));
        Integer autoClose = environment
            .getProperty("", );
        (autoClose);
        String defaultValue = environment
            .getProperty("", , "defaultValue");
        (defaultValue);
    }
}

In the example above, you can see that in addition to simple acquisition,EnvironmentThe provided method can also convert the extracted attribute values ​​and set the default values, call the above interface, and print the result as follows:

hydra
male
18
defaultValue

In addition to obtaining attributes, it can also be used to judge the activated configuration file, and first activate the pro file:

spring:
  profiles:
    active: pro

Can be passedacceptsProfilesMethod to detect whether a configuration file is activated and loaded, or throughgetActiveProfilesMethod to get all activated configuration files. Test interface:

@GetMapping("getActiveEnv")
private void getActiveEnv(){
    (("pro"));
    (("dev"));
    String[] activeProfiles = ();
    for (String activeProfile : activeProfiles) {
        (activeProfile);
    }
}

Print result:

true
false
pro

2、YamlPropertiesFactoryBean

It can also be used in SpringYamlPropertiesFactoryBeanTo read the yml file of the custom configuration without being restricted to other configuration files it activates.

During use, you only need to passsetResources()Method sets the storage path of the custom yml configuration file and then passesgetObject()Method GettingPropertiesThe object can be obtained through it in the future. Let’s take an example:

@GetMapping("fcTest")
public void ymlProFctest(){
    YamlPropertiesFactoryBean yamlProFb = new YamlPropertiesFactoryBean();
    (new ClassPathResource(""));
    Properties properties = ();
    ((""));
    ((""));
    (());
}

View the run results and you can read the specified content:

fcant
female
{=18, =female, =fcant}

However, there is a problem in this use, that is, only the value of this attribute can be obtained in the request of this interface. If you write another interface, you will not use it.YamlPropertiesFactoryBeanRead the configuration file. Even if the previous method has read the yml file once, the second interface still gets a null value. Let's test this process:

@Value("${:null}")
private String name;
@Value("${:null}")
private String gender;
@GetMapping("fcTest2")
public void ymlProFctest2(){
    (name);
    (gender);
}

Call it once firstfcTestInterface, call againfcTest2Prints when the interface isnullvalue:

null
null

It's very simple to solve this problem, you can cooperatePropertySourcesPlaceholderConfigurerUsing it, it implementsBeanFactoryPostProcessorInterface, that is, the implementation of a bean factory post-processor, can load the attribute value of the configuration file into aPropertiesin the file. How to use it is as follows:

@Configuration
public class PropertyConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer 
            = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yamlProFb 
            = new YamlPropertiesFactoryBean();
        (new ClassPathResource(""));
        (());
        return configurer;
    }
}

Call the previous interface again, and the result is as follows, and the properties in progress can be retrieved normally:

fcant
female

In addition to usingYamlPropertiesFactoryBeanParse yml intoPropertiesIn addition, it can be usedYamlMapFactoryBeanparse yml to becomeMap, the usage method is very similar:

@GetMapping("fcMapTest")
public void ymlMapFctest(){
    YamlMapFactoryBean yamlMapFb = new YamlMapFactoryBean();
    (new ClassPathResource(""));
    Map<String, Object> map = ();
    (map);
}

Print result:

{person2={name=fcant, gender=female, age=18}}

3. Listen to events

SpringBoot loads and parses yml files by listening for events, so you can also load custom configuration files in this mode.
First, define a class implementationApplicationListenerThe type of event to listen to isApplicationEnvironmentPreparedEvent, and pass in the constructor method the yml file name to be parsed:

public class YmlListener implements 
    ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    private String ymlFilePath;
    public YmlListener(String ymlFilePath){
         = ymlFilePath;
    }
    //...
}

The interface needs to be implemented in a custom listeneronApplicationEvent()Method, when listeningApplicationEnvironmentPreparedEventThe event will be triggered:

@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = ();
    ResourceLoader loader = new DefaultResourceLoader();
    YamlPropertySourceLoader ymlLoader = new YamlPropertySourceLoader();
    try {
        List<PropertySource<?>> sourceList = ymlLoader
            .load(ymlFilePath, (ymlFilePath));
        for (PropertySource<?> propertySource : sourceList) {
            ().addLast(propertySource);
        }
    } catch (IOException e) {
        ();
    }
}

In the above code, the main implementation is:

  • Get the current environmentEnvironment,whenApplicationEnvironmentPreparedEventWhen the event is triggered, it has been completedEnvironmentloading and being able to passeventEvent acquisition
  • passYamlPropertySourceLoaderLoading and parsing configuration files
  • After parsing itOriginTrackedMapPropertySourceAdd toEnvironmentmiddle

Modify the startup class and add this listener to the startup class:

public static void main(String[] args) {
    SpringApplication application = new SpringApplication();
    (new YmlListener("classpath:/"));
    (args);
}

InenvironmentAdded inpropertySourceAdd a breakpoint before to view the changes in the environment.
After execution is completed, you can see that the configuration file source has been added to the environment.

After starting, call the interface and view the results:

Fcant
female

The value in the configuration file can be correctly retrieved, indicating that the custom listener has taken effect.

4、SnakeYml

The methods introduced above can be accomplished without introducing other dependencies in the Spring environment. The SnakeYml I will introduce next needs to introduce dependencies before use, but it can also be used separately from the Spring environment. First introduce dependency coordinates:

<dependency>
    <groupId></groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.23</version>
</dependency>

Prepare a yml configuration file:

person1:
  name: hydra
  gender: male
person2:
  name: fcant
  gender: female

In useSnakeYmlWhen parsing yml, the most common use isloadloadlAllloadAsMethods, these three methods can load yml files or strings, and finally return the parsed object. Start with the basicsloadMethod start demonstration:

public void test1(){
    Yaml yaml=new Yaml();
    Map<String, Object> map =
            (getClass().getClassLoader()
                    .getResourceAsStream(""));
    (map);
}

Run the above code and print the contents in the map:

{person1={name=hydra, gender=male}, person2={name=fcant, gender=female}}

Next, let’s take a look at the loadAll method, which can be used to load multiple documents connected using the - connector in yml, and modify the above yml file:

person1:
  name: hydra
  gender: male
---
person2:
  name: fcant
  gender: female

After adding the connector, try to use it againloadThe method is parsed, and the error shows that another yml document was found and it cannot be parsed normally.

Modify the above code at this time and useloadAllmethod:

public void test2(){
    Yaml yaml=new Yaml();
    Iterable<Object> objects = 
        (getClass().getClassLoader()
            .getResourceAsStream(""));
    for (Object object : objects) {
        (object);
    }
}

The execution results are as follows:

{person1={name=hydra, gender=male}}
{person2={name=fcant, gender=female}}

You can see,loadAllThe method returns an iteration of an object, and each object in it corresponds to a document in yml, and the modified yml file is parsed into two independent maps.
Let's take a look nextloadAsMethod, it can specify the type during yml parsing process and directly encapsulate it into an object. Directly reuse the above, create two entity class objects for reception before parsing:

@Data
public class Person {
    SinglePerson person1;
    SinglePerson person2;
}
@Data
public class SinglePerson {
    String name;
    String gender;
}

Use belowloadAsWhen the method loads yml, pay attention to the second parameter of the method, which is the entity type used to encapsulate yml.

public void test3(){
    Yaml yaml=new Yaml();
    Person person = 
        (getClass().getClassLoader().
            getResourceAsStream(""), );
    (());
}

View execution results:

Person(person1=SinglePerson(name=hydra, gender=male), person2=SinglePerson(name=fcant, gender=female))

In fact, if you want to encapsulate yml into an entity object, you can also use another method. When creating a Yaml object, pass in a constructor object with the specified entity class and then directly call itloadThe method can be implemented:

public void test4(){
    Yaml yaml=new Yaml(new Constructor());
    Person person = (getClass().getClassLoader().
            getResourceAsStream(""));
    (());
}

The execution result is the same as above:

Person(person1=SinglePerson(name=hydra, gender=male), person2=SinglePerson(name=fcant, gender=female))

SnakeYml actually implements a lot of functions, so I won’t list them here. Interested friends can check the document by themselves. In fact, at the bottom of SpringBoot, yml parsing operations are also performed with the help of SnakeYml.

5、jackson-dataformat-yaml

Compared to the scenario where people usually use jackson, it is used to process json. In fact, it can also be used to process yml. Dependencies need to be introduced before use:

<dependency>
    <groupId></groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.12.3</version>
</dependency>

Reading yml using jackson is also very simple, and the commonly used ones are used here.ObjectMapper, in creationObjectMapperObjects are specified to use YAML factory, and then you can simply map yml to the entity:

public void read() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    InputStream input =
        new FileInputStream("F:\\Work\\yml\\src\\main\\resources\\");
    Person person = (input, );
    (());
}

Running results:

Person(person1=SinglePerson(name=hydra, gender=male), person2=SinglePerson(name=fcant, gender=female))

If you want to generate a yml file, you can call itObjectMapperofwriteValueMethod implementation:

public void write() throws IOException {
    Map<String,Object> map=new HashMap<>();
    SinglePerson person1 = new SinglePerson("Trunks", "male");
    SinglePerson person2 = new SinglePerson("Goten", "male");
    Person person=new Person(person1,person2);
    ("person",person);
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    objectMapper
            .writeValue(new File("F:\\Work\\yml\\src\\main\\resources\\"),map);
}

Looking at the generated yml file, you can see that Jackson strictly adds quotes to the string type and adds the yml link character at the beginning of the document. As for other complex functions of jackson reading and writing yml, you can explore and use it yourself at work.

Summarize

Here are 5 ways to read yml configuration files. The first three depend on the Spring environment, andSnakeYmlandJacksonThen they can be used independently from the environment, so they can be said to be correct@Valueand@ConfigurationPropertiesSupplements to the use of annotations. The use scenarios of these methods are different, and each has its own advantages, and each has some special usages. In more cases, one solution should be selected or used in combination according to the specific purpose.

This is the article about Java development diary: Do you know the 5 great yml file reading methods? This is all about this article. For more related Java yml file reading methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!