-
preface
-
Introduction to properties format
-
Introduction to YML format
-
How to use
-
summary
-
-
How to get values from a configuration file?
-
@ConfigurationProperties
-
@Value
-
-
How to get values from a user-defined configuration file?
preface
Since using Spring Boot, my favorite is the configuration file of Spring Boot. Compared with Spring, Spring Boot is more flexible and easier to modify some configurations.
Spring Boot officially provides two common configuration file formats: properties and YML. Compared with properties, YML is younger and more hierarchical.
Today's article will introduce the syntax of the Spring Boot configuration file and how to get values from the configuration file.
Introduction to properties format
A common configuration file format, which is also used in Spring. The syntax structure is very simple. The structure is: key=value. The 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
The corresponding entity classes in the above 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; }
The structure is very simple. It is nothing more than the form of key=value. It is also a format commonly used in development.
Introduction to YML format
Controls the hierarchical relationship by the indentation of spaces. The number of spaces is not important. As long as the left space is aligned, it is regarded as the same level. Note that tab s cannot be used instead of spaces. And case sensitive. It supports three data structures: literal value, object and array, and also supports composite structure.
Literal value: string, boolean type, numeric value, date. Strings are not quoted by default. Single quotation marks escape special characters. Date format supports yyyy/MM/dd HH:mm:ss
Object: consists of key value pairs, such as key: (space) value data. The space after the colon is required. Each group of key value pairs occupies one line and the indentation degree should be consistent. You can also use the inline writing method: {K1: V1,.... kn: VN}
Array: consists of data in the form of - (space) value. There must be spaces after the dash. Each group of data occupies one row and the indentation degree should be consistent. You can also use the inline writing method: [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 supported types mainly include string, string with special characters, boolean type, value, set, inline set, inline object, and set object, which are commonly used 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
The entity classes corresponding to the above 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; }
summary
YML is a new format with distinct levels. I prefer to use it. Note the following:
-
Strings can be without quotation marks. If double quotation marks are added, special characters will be output. If single quotation marks are not added or added, special characters will be escaped
-
Array type, there should be a space after the dash; Object type, space after colon
-
YAML controls the hierarchical relationship by the indentation of spaces, but cannot use tab instead of spaces, which is case sensitive
How to get values from a configuration file?
All configurations are for value taking. Spring Boot also provides several value taking methods, which are introduced one by one below.
@ConfigurationProperties
This annotation is used to fetch values from the configuration file. It supports complex data types, but does not support SPEL expressions.
There is an attribute prefix in the annotation, which is used to specify the prefix to be configured. After all, there are many attributes in the configuration file, and there are many duplicate names, which must be distinguished by a prefix.
The annotation can be marked on a class or a method, which means that it has two ways to obtain values.
1. Mark on entity class
This method is used to take values from entity classes and assign values to corresponding attributes. Use the following:
/** * @Component : Inject into IOC container * @ConfigurationProperties: Read file from 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; }
Label on the method in the configuration class
The method marked on the configuration class is also assigned from the value in the configuration file to the attribute of the return value. Use the following:
/** * @Bean : Inject the returned results into the IOC container * @ConfigurationProperties : Take value from configuration file * @return */ @ConfigurationProperties(prefix = "userinfo") @Bean public UserInfo userInfo(){ return new UserInfo(); }
summary
@The ConfigurationProperties annotation can easily take values from the configuration file. Its advantages are as follows:
-
Batch injection attribute is supported. Only a prefix prefix needs to be specified
-
Support complex data types, such as List and Map
-
Lower requirements for attribute name matching, such as user name and user_ name,userName,USER_ Name can be taken
-
Support JAVA JSR303 data verification
Note: @ ConfigurationProperties annotation only supports taking values from the default configuration file of Spring Boot, such as application.properties and application.yml.
@Value
@I'm probably familiar with the annotation Value. The annotation Value from attribute in Spring supports SPEL expressions and does not support complex data types, such as List. Use the following:
@Value("${userinfo.name}") private String UserName;
How to get values from a user-defined configuration file?
Spring Boot will automatically load application.xxx and bootstrap.xxx when it is started. However, in order to distinguish, sometimes a configuration file needs to be customized, so how to get values from the customized configuration file? At this point, it needs to be used in conjunction with the @ PropertySource annotation.
Just mark @ PropertySource on the configuration class and specify your customized configuration file. As follows:
@SpringBootApplication @PropertySource(value = {"classpath:custom.properties"}) public class DemoApplication {
The value attribute is an array that can specify multiple configuration files to be introduced at the same time.
@PropertySource loads configuration files of type xxx.properties by default, but cannot load configuration files in YML format. How to break???
How to load configuration files in custom YML format?
@The PropertySource annotation has a property factory. The default value is PropertySourceFactory.class. This is the configuration file used to load properties format. We can customize a configuration file used 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 public PropertySource<?> 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(); } }
At this time, you only need to specify the factory attribute as YmlConfigFactory, as follows:
@SpringBootApplication @PropertySource(value = {"classpath:custom.yml"},factory = YmlConfigFactory.class) public class DemoApplication {
summary
@PropertySource specifies to load custom configuration files. Only properties format can be loaded by default, but factory property can be specified to load configuration files in YML format.
summary
The above content introduces the syntax of the configuration file in Spring Boot and how to get values from the configuration file. This content is very important. The author is also easy to understand as much as possible. I hope readers can gain something.