I came across this article in a foreign forum where someone was teasing a colleague about the long and bloated way to get values from configuration files

Github Demo address: springboot-yml-value

1. What are YML files

Application. Yml replaces application. Properties to make the configuration data more readable, especially if we have made a lot of hierarchical configurations. Yml supports the declaration of map, array, list, string, Boolean, numeric, NULL, date, basically meets all the configuration in the development process.

Here is a very basic YML file:

server:
    url: http://localhost 
    myapp:
        name: MyApplication
        threadCount: 4.Copy the code

Equivalent to the following application.properties file:

server.url=http://localhost
server.myapp.name=MyApplication
server.myapp.threadCount=4.Copy the code

The yML files in Demo are as follows:

server:
    url: http://myapp.org 
    app:
        name: MyApplication
        threadCount: 10
        users: 
          - Jacob
          - James
Copy the code

2. Obtain the configuration of the YML attribute

One way to access yML attributes is to use @value (“${property}”) annotations, but as the configuration tree structure and number increases, code readability decreases, making it harder to manage beans. The authors found another elegant way to ensure the management of strongly typed beans and make it easier to validate our program configuration.

To do this, we’ll create a @ConfigurationProperties class ServerProperties that maps a set of related properties:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.ArrayList;
import java.util.List;

/ * * *@program: simple-demo
 * @description: Mapping attribute (Server node) *@author: CaoTing
 * @date: 2019/6/3 * * /
@Data
@ConfigurationProperties("server")
public class ServerProperties {
 
    private String url;
 
    private final App app = new App();
 
    public App getApp(a) {
        return app;
    }
 
    public static class App {
 
        private String name;
        private String threadCount;
        private List<String> users = new ArrayList<>();
        // TODO getter and setter}}Copy the code

Note that we can create one or more @ConfigurationProperties classes.

Define our SpringBoot registration configuration class ApplicationConfig:

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/ * * *@program: simple-demo
 * @description{} Separate multiple attribute classes * by commas@author: CaoTing
 * @date: 2019/6/3 * * /
@Configuration
@EnableConfigurationProperties({ServerProperties.class})
public class ApplicationConfig {}Copy the code

Here has been mentioned to registered in @ EnableConfigurationProperties attribute class list.

3. Access the YML attributes

You can now access the YML properties by using the @ConfigurationProperties bean you created. These property beans can be injected just like any regular Spring bean, with the following test classes:

import com.caotinging.ymldemo.application.YmlValueApplication;
import com.caotinging.ymldemo.config.ServerProperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/ * * *@program: simple-demo
 * @description: Unit test class *@author: CaoTing
 * @date: 2019/6/3 * * /
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = YmlValueApplication.class)
public class AppYmlValueTest {

    @Autowired
    private ServerProperties config;

    @Test
    public void printConfigs(a) {
            System.out.println(this.config.getUrl());
            System.out.println(this.config.getApp().getName());
            System.out.println(this.config.getApp().getThreadCount());
            System.out.println(this.config.getApp().getUsers()); }}Copy the code

The test results are as follows:

Added 4.

Because some friends are not quite clear about the specific purpose. The author adds the advantages and disadvantages of both.

Spring Boot uses the ConfigurationProperties annotation to get properties from the configuration file. As you can see from the above example, the ConfigurationProperties annotation specifies the data to be imported in batches by setting the prefix. Support for retrieving complex data such as literals, collections, maps, objects, etc. Any other features of the ConfigurationProperties annotation? How is it different from Spring’s Value annotation?

ConfigurationProperties and @Value

Advantages and disadvantages of the ConfigurationProperties annotations

You can batch inject properties from configuration files.

Second, support to obtain complex data types;

3. There is a low requirement for matching attribute names, such as user-name, user_name, userName, user_name.

Iv. Support JAVA JSR303 data verification;

The disadvantage is that it does not support SpEL expressions.

Ensure the management of strongly typed beans and more convenient configuration of validators;

The Value annotation has the opposite advantage. It can only configure the injected values one by one. Complex data types such as arrays and collections are not supported. Data verification is not supported. There are strict requirements for attribute name matching. The biggest feature is the support for SpEL expressions, making it more functional.

Answer your questions in the comments section

What if the first property is an array?

The following is an example of YML

orgs:
    - math
    - chinese
    - english
Copy the code

All you need is a bean like the one below.

/ * * *@program: simple-demo
 * @description: maps the Org attribute *@author: CaoTing
 * @date: 2019/6/6 * * /
@Data
@ConfigurationProperties
public class OrgProperties {
    private List<String> orgs;
}
Copy the code

But don’t forget to register in the registration class

@EnableConfigurationProperties({ServerProperties.class, OrgProperties.class})
Copy the code

The Github repository has also updated this part of the code, welcome to the test oh, the address is at the top of the article.

Maps and other more complex data structures can be implemented, so I won’t test them individually.

Original is not easy, reprint please attach the original link, if there is a favor, pen core.