How to get the value in spring boot YML more elegantly

Time:2020-2-24

Preface

Occasionally, I saw someone make complaints about the way to get value from the configuration files in foreign forum. Therefore, we have consulted the relevant information and found that there is indeed a more convenient way to manage and get elegant.

GitHub demo address: springboot YML value

1. What is YML file

Application.yml replaces application.properties to make configuration data more readable, especially when we have formulated many hierarchical configurations.

Here is a very basic YML file:


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

Equivalent to the following application.properties file:


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

The YML file in demo is as follows:


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

2. Get configuration of YML attribute

One way to access the properties of YML is to use @ value (“${property}”) annotation, but with the increase of configuration tree structure and quantity, the code readability will decrease, which is not conducive to bean management. The author found another elegant way to ensure the management of strong type beans and more convenient verification of our program configuration.

To achieve this, we will create a @ configurationproperties class serverproperties, which 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() {
  return app;
 }
 
 public static class App {
 
  private String name;
  private String threadCount;
  private List<String> users = new ArrayList<>();
  // TODO getter and setter
 }
 
}

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: register multiple attribute classes by separating them with commas in all mapped attribute classes {}
 * @author: CaoTing
 * @date: 2019/6/3
 **/
@Configuration
@EnableConfigurationProperties({ServerProperties.class})
public class ApplicationConfig {
}

The list of property classes to register in @ enableconfigurationproperties has been mentioned here.

3. Access the YML property

You can now access the YML properties by using the @ configurationproperties bean you created. These attribute beans can be injected like any regular spring bean. The test classes are as follows:

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() {
   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());
 }
}

The test results are as follows:

4. summary

Welcome to GitHub for testing. The address is at the beginning of the article. Like it if you can, refill. For reprint, please attach the original link.

5. supplement

Because there are small partners who don’t know the specific purpose. I would like to add the advantages and disadvantages of the two.

Spring boot obtains properties from the configuration file through the configurationproperties annotation. From the above example, we can see that the configurationproperties annotation can specify the data to be imported in batch by setting prefix. Support to obtain complex data such as literal value, collection, map, object, etc. What are the other features of the configuration properties annotation? What’s the difference between it and spring’s value annotation?

1) Advantages and disadvantages of configurationproperties and @ value

Advantages and disadvantages of configuration properties annotation

1、 You can batch inject attributes from the configuration file;

2、 Support the acquisition of complex data types;

3、 The requirement of attribute name matching is low, for example, user name, user name, user name can all take values;

4、 Support Java’s jsr303 data verification;

5、 The disadvantage is that spel expressions are not supported;

6、 Ensure the management of strong type beans and more convenient configuration of verifier;

The advantages and disadvantages of value annotation are just the opposite. It can only configure injection values one by one; it does not support complex data types such as arrays and collections; it does not support data validation; it has strict requirements for attribute name matching. The biggest feature is to support the spel expression, so that it has more functions.

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.

Recommended Today

Laravel service container must know

The article was forwarded from the professional laravel developer community. Original link: https://learnku.com/laravel/t To learn how to build an application with laravel is not only to learn how to use different classes and components in the framework, but also to remember allartisanCommand or all helper functions (we have Google). Learning to code with laravel is […]