Continue to original output, click on the top of the blue word to follow me


preface

Since using Spring Boot, my favorite is the configuration file of Spring Boot. Compared with Spring Boot, Spring Boot is more flexible, and some configurations are more convenient to modify.

Spring Boot provides two common configuration file formats: Properties and YML. Compared to Properties, YML is younger and more hierarchical.

This article introduces the syntax of the Configuration file for Spring Boot and how to value values from the configuration file.

Properties format

This configuration file format is also used in Spring. The syntax structure is simple: key=value. Details are as follows:

userinfo.name=myjszl
userinfo.age=25
userinfo.active=true
userinfo.created-date=2018/03/31 16:54:30
userinfo.map.k1=v1
userinfo.map.k2=v2
Copy the code

The entity classes in the configuration file are as follows:

@Data
@ToString
public class UserInfo {
    private String name;
    private Integer age;
 private Boolean active;  private Map<String,Object> map;  private Date createdDate;  private List<String> hobbies; } Copy the code

The structure is very simple, nothing more than the form of key=value, which is also used in the development of a more common format.

Introduction to YML format

Control the hierarchy by indentation of Spaces. The number of Spaces is not important, as long as the left space is aligned, it is considered the same level. Note that you cannot use tabs instead of Spaces. And case sensitive. Support literal value, object, array three kinds of data structure, also support composite structure.

Literals: string, Boolean, value, date. Strings are not quoted by default. Single quotes escape special characters. The date format is YYYY /MM/ DD HH: MM: SS

Object: consists of key-value pairs, such as key (space)value. Spaces after colons are mandatory. Each pair of keys and values occupies a line with the same degree of indentation. You can also use inline notation: {k1: v1,…. kn: vn}

Array: Consists of data of the form -(space)value. The space after the dash is mandatory. Each group of data occupies one line with the same indentation. You can also use inline notation: [1,2…n]

Composite structure: Any combination of the above three data structures

How to use

Create an application.yml file in the SRC/Resources folder. The main supported types are string, string with special characters, Boolean types, values, sets, inline sets, inline objects, collection objects these common data formats.

Specific examples are as follows:

userinfo:
    age: 25
    name: myjszl
    active: true
 created-date: 2018/ 03/31 16: 54:30
 map: {k1: v1,k2: v2}  hobbies:  - one  - two  - three Copy the code

The entity classes corresponding to the configuration files are as follows:

@Data
@ToString
public class UserInfo {
    private String name;
    private Integer age;
 private Boolean active;  private Map<String,Object> map;  private Date createdDate;  private List<String> hobbies; } Copy the code

conclusion

YML is a new format with distinct hierarchies, which I prefer to use. Note the following:

  1. The character string can be unquoted. If double quotation marks are added, special characters are output. If single quotation marks are not added, special characters are escaped
  2. Array type with a space after a dash; Object type, followed by a colon
  3. YAML controls hierarchy by the degree to which Spaces are indented, but it cannot replace Spaces with the TAB key, which is case-sensitive

How to obtain a value from a configuration file?

All configurations are for values. Spring Boot also provides several values, which are described below.

@ConfigurationProperties

This annotation is used to value values from configuration files and supports complex data types, but does not support SPEL expressions.

This annotation contains a prefix attribute, which is used to specify the prefix to be configured. After all, there are many attributes in the configuration file, and many have the same name, you must use a prefix to distinguish them.

This annotation can be annotated on a class or a method, which means that it has two ways of getting values.

1. Annotation on entity class

This method is used to value from the entity class and assign the value to the corresponding attribute. Use as follows:

/ * * * @Component: injected into the IOC container * @ConfigurationProperties: Reads the file from the configuration file* /
@Component
@ConfigurationProperties(prefix = "userinfo") @Data @ToString public class UserInfo {  private String name;  private Integer age;  private Boolean active;  private Map<String,Object> map;  private Date createdDate;  private List<String> hobbies; } Copy the code

Annotation on methods in the configuration class

Annotation on a method on a configuration class is also an attribute that assigns values from the configuration file to the return value. Use as follows:

    / * *     * @BeanInject the returned result into the IOC container     * @ConfigurationProperties: Indicates the value in the configuration file     * @return
* /
 @ConfigurationProperties(prefix = "userinfo")  @Bean  public UserInfo userInfo(a){  return new UserInfo();  } Copy the code

conclusion

The @configurationProperties annotation can be easily evaluated from a configuration file with the following advantages:

  1. Supports batch injection properties, requiring only a prefixprefix
  2. Support complex data types, such asList,Map
  3. There are low requirements for attribute name matching, such asuser-name.user_name.userName.USER_NAMEI can take values
  4. Supports JAVA JSR303 data verification

Note:@ConfigurationPropertiesThis annotation only supports values from the Spring Boot default configuration file, for exampleapplication.properties,application.yml.

@Value

Spring supports SPEL expressions and does not support complex data types, such as List. Use as follows:

    @Value("${userinfo.name}")
    private String UserName;
Copy the code

How to obtain a value from a custom configuration file?

XXX and Bootsrap. XXX will be automatically loaded when Spring Boot is started. However, you sometimes need to define a customized configuration file to distinguish between them. This is used with the @propertysource annotation.

Just annotate @propertysource on the configuration class and specify your custom configuration file. As follows:

@SpringBootApplication
@PropertySource(value = {"classpath:custom.properties"})
public class DemoApplication {
Copy the code

valueProperty is an array that can specify multiple configuration files to be imported at the same time.

@PropertySourceThe default loadxxx.propertiesType configuration file, cannot be loadedYMLFormat configuration file, how to break??

How do I load a customized YML configuration file?

@ PropertySource annotation has an attribute factory, the default value is PropertySourceFactory. Class, this is used for loading the properties configuration file format, we can customize a configuration file to load YML format, as follows:

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
 import java.io.IOException; import java.util.Properties;  public class YmlConfigFactory extends DefaultPropertySourceFactory {  @Override  publicPropertySource<? > createPropertySource(String name, EncodedResource resource)throws IOException { String sourceName = name ! =null ? name : resource.getResource().getFilename();  if(! resource.getResource().exists()) { return new PropertiesPropertySource(sourceName, new Properties());  } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {  Properties propertiesFromYaml = loadYml(resource);  return new PropertiesPropertySource(sourceName, propertiesFromYaml);  } else {  return super.createPropertySource(name, resource);  }  }   private Properties loadYml(EncodedResource resource) throws IOException {  YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();  factory.setResources(resource.getResource());  factory.afterPropertiesSet();  return factory.getObject();  }  }  Copy the code

The factory attribute is YmlConfigFactory as follows:

@SpringBootApplication
@PropertySource(value = {"classpath:custom.yml"},factory = YmlConfigFactory.class)
public class DemoApplication {
Copy the code

conclusion

@propertysource specifies to load a custom configuration file. By default, only properties can be loaded, but you can specify the Factory property to load a YML configuration file.

conclusion

The above section introduces the syntax of the configuration file in Spring Boot and how to value it from the configuration file. This section is very important and the author tries to make it easy to understand.

Well, I have spent more than two hours, and every article is carefully made by the author. Every like and share from readers is a great support to me, thank you!!