Catalog
- Loading property order
- Random attribute
- Command Line Properties
- Application property file
- Profile-specific attributes
- Placeholders in attributes
- YAML attribute
- Access attribute
- Multi-profile configuration
- Disadvantages of YAML
- Attribute prefix
- Loose binding rules for attributes
- Attribute transformation
- Time Unit Conversion
- Data Size Conversion
- Check attribute
Loading property order
Spring Boot loads property in the following order:
- Devtools global configuration (When devtools are activated \/. spring-boot-devtools.properties).
- ="https://docs.spring.io/spring/docs/5.1.3.RELEASE/javadoc-api/org/springframework/test/context/TestPropertySource.html "> Test Property Source Annotation Configuration in Test Environment
- properties in the test environment: @SpringBootTest Sum Test notes.
- Command line parameters
- SPRING_APPLICATION_JSON attribute
- ServletConfig initialization parameters
- ServletContext initialization parameters
- JNDI attributes from configures JNDI attributes via java:comp/env
- Java System Properties (System.getProperties())
- Operating system environment is better than that
- Random Value Property Source loads properties in the form of random. *
- application-{profile}.properties or application-{profile}.yml configuration outside the jar package
- application-{profile}.properties or application-{profile}.yml configuration in the jar package
- application.properties or application.yml configuration outside the jar package
- application.properties or application.yml configuration in the jar package
- @ Configuration of Property Source Binding
- Default properties (specified by SpringApplication.setDefaultProperties)
Random attribute
The RandomValuePropertySource class is used to configure random values.
Example:
my.secret=${random.value} my.number=${random.int} my.bignumber=${random.long} my.uuid=${random.uuid} my.number.less.than.ten=${random.int(10)} my.number.in.range=${random.int[1024,65536]}
Command Line Properties
By default, Spring Application takes -- parameters (for example -- server.port=9000) and adds this property to Spring's Environment.
If you don't want to load command line properties, you can disable them by SpringApplication.setAddCommandLineProperties(false).
Application property file
Spring Application automatically loads the application.properties configuration file in the following path and reads the properties into Spring's Environment.
- The / config subdirectory of the current directory
- current directory
- /config package under classpath path path path
- classpath root path
The configuration files listed above will be in order, and the configuration in the latter order will override the configuration in the former order.
You can choose. YAML(yml) Replace the properties configuration file with the configuration file.
If you don't like application.properties as a configuration file name, you can replace it with spring.config.name environment variable:
$ java -jar myproject.jar --spring.config.name=myproject
The configuration file path can be specified using the spring.config.location environment variable:
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
Profile-specific attributes
If you define a configuration file in the form of application-{profile}.properties, it will be considered a specific configuration in the profile environment.
The profile can be activated by the spring.profiles.active parameter. If no profile is activated, the configuration in application-default.properties will be loaded by default.
Placeholders in attributes
Values in application.properties are filtered by the Environment, so you can refer to previously defined properties.
app.name=MyApp app.description=${app.name} is a Spring Boot application
YAML attribute
Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean loads YAML as Properties and the YamlMapFactoryBean loads YAML as a Map.
The Spring framework has two classes that support loading YAML files.
- Yaml Properties FactoryBean loads the configuration of the YAML file as Properties.
- YamlMapFactoryBean loads the configuration of the YAML file as Map.
Example 1
environments: dev: url: http://dev.example.com name: Developer Setup prod: url: http://another.example.com name: My Cool App
Equivalent to:
environments.dev.url=http://dev.example.com environments.dev.name=Developer Setup environments.prod.url=http://another.example.com environments.prod.name=My Cool App
YAML supports tabular form and is equivalent to [index] in property:
my: servers: - dev.example.com - another.example.com
Equivalent to
my.servers[0]=dev.example.com my.servers[1]=another.example.com
Access attribute
The YamlPropertySourceLoader class converts the YAML configuration into PropertySource in the Spring Environment class. Then, you can use the same properties as in the properties file. @Value Annotations to access the properties configured in YAML.
Multi-profile configuration
server: address: 192.168.1.100 --- spring: profiles: development server: address: 127.0.0.1 --- spring: profiles: production & eu-central server: address: 192.168.1.120
Disadvantages of YAML
Note: Attributes in YAML annotations cannot be accessed through the @PropertySource annotation. So, if you use some custom property files in your project, it is recommended not to use YAML.
Attribute prefix
package com.example; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix="acme") public class AcmeProperties { private boolean enabled; private InetAddress remoteAddress; private final Security security = new Security(); public boolean isEnabled() { ... } public void setEnabled(boolean enabled) { ... } public InetAddress getRemoteAddress() { ... } public void setRemoteAddress(InetAddress remoteAddress) { ... } public Security getSecurity() { ... } public static class Security { private String username; private String password; private List<String> roles = new ArrayList<>(Collections.singleton("USER")); public String getUsername() { ... } public void setUsername(String username) { ... } public String getPassword() { ... } public void setPassword(String password) { ... } public List<String> getRoles() { ... } public void setRoles(List<String> roles) { ... } } }
Equivalent to supporting configuration of the following attributes:
- acme.enabled
- acme.remote-address
- acme.security.username
- acme.security.password
- acme.security.roles
Then, you need to inject the attribute class into the configuration class using the @EnableConfiguration Properties annotation.
@Configuration @EnableConfigurationProperties(AcmeProperties.class) public class MyConfiguration { }
Loose binding rules for attributes
Spring Boot attribute names are loosely bound.
The following attributes key are equivalent:
Property Noteacme.my-project.person.first-name-separated acme.myProject.person.first Name hump named acme.my_project.person.first_name_separated ACME_MYPROJECT_PERSON_FIRSTNAME capital letters
Attribute transformation
If type conversion is required, you can provide a Conversion Service bean (a bean called Conversion Service) or a custom attribute configuration (a Custom Editor Configurer bean) or a custom Converters (a Bena modified by the @Configuration Properties Binding annotation).
Time Unit Conversion
Spring uses the java.time.Duration class to represent the time size. The following scenarios apply:
- Unless @Duration Unit is specified, a long represents milliseconds.
- ISO-8601 Standard Format( java.time.Duration The implementation refers to this standard.
- You can also use the following support units:
- ns nanosecond
- us - microsecond
- ms milliseconds
- s sec
- m - points
- h - time
- d - day
Example:
@ConfigurationProperties("app.system") public class AppSystemProperties { @DurationUnit(ChronoUnit.SECONDS) private Duration sessionTimeout = Duration.ofSeconds(30); private Duration readTimeout = Duration.ofMillis(1000); public Duration getSessionTimeout() { return this.sessionTimeout; } public void setSessionTimeout(Duration sessionTimeout) { this.sessionTimeout = sessionTimeout; } public Duration getReadTimeout() { return this.readTimeout; } public void setReadTimeout(Duration readTimeout) { this.readTimeout = readTimeout; } }
Data Size Conversion
Spring uses the DataSize class to represent the data size. The following scenarios apply:
- long value (default is byte)
- You can also use the following support units:
- B
- KB
- MB
- GB
- TB
Example:
@ConfigurationProperties("app.io") public class AppIoProperties { @DataSizeUnit(DataUnit.MEGABYTES) private DataSize bufferSize = DataSize.ofMegabytes(2); private DataSize sizeThreshold = DataSize.ofBytes(512); public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public DataSize getSizeThreshold() { return this.sizeThreshold; } public void setSizeThreshold(DataSize sizeThreshold) { this.sizeThreshold = sizeThreshold; } }
Check attribute
@ConfigurationProperties(prefix="acme") @Validated public class AcmeProperties { @NotNull private InetAddress remoteAddress; @Valid private final Security security = new Security(); // ... getters and setters public static class Security { @NotEmpty public String username; // ... getters and setters } }
You can also customize a checker Bean called configurationProperties Validator. The method to get this @Bean must be declared static.
Usage method:
mvn clean package cd target java -jar sbe-core-property.jar
I organize Java advanced materials for free, covering Java, Redis, MongoDB, MySQL, Zookeeper, Spring Cloud, Dubbo, high concurrent and distributed tutorials, a total of 30G, need to collect.
Portal: https://mp.weixin.qq.com/s/JzddfH-7yNudmkjT0IRL8Q