This is the 11th day of my participation in the First Challenge 2022

SpringBoot allows you to externalize the configuration so that you can use the same code in different environments. You can externalize the configuration using properties files, YAMl files, environment variables, and command-line arguments. Using the @Value annotation, you can inject property values directly into beans and then access them through Spring’s Environment abstraction or through the @ConfigurationProperties binding to structured objects.

SpringBoot has designed a very special order for loading specified property files (@propertysource) to allow proper overwriting of property values. Properties are set in the following order:

  • The devTools global setting property in the home directory (~/. Spring-boot-devtools. properties, if DevTools is active).
  • Annotation @testpropertysource on the test case.
  • Annotation @springBoottest #properties on the test case.
  • Command line arguments.
  • Properties from SPRING_APPLICATION_JSON (inline JSON embedded in environment variables or system properties).
  • ServletConfig Initialization parameters.
  • ServletContext initialization parameter.
  • JNDI properties from Java :comp/env.
  • Java System properties (system.getProperties ()).
  • Operating system environment variables.
  • RandomValuePropertySource, contains only random. * the properties.
  • Profile-specific application properties (application-{Profile}. Properties and YAML variables) are not typed into the JAR package.
  • Type profile-specific application properties (application-{Profile}. Properties and YAML variables) into the JAR package.
  • Application configurations (application.properties and YAML variables) that are not typed into the JAR package.
  • Punch the application configuration (application.properties and YAML variables) into the JAR package.
  • @propertysource annotation on the @Configuration class.
  • Default attributes (use SpringApplication setDefaultProperties specified).

1. Configure random values

SpringBoot supports configuration to generate random numbers at system load time, such as when generating keys or for testing purposes, which can be very useful.

(1) in the SRC/main/resources/config/new random. The properties file, add content is as follows:

Secret =${random.value} # random int number user.random.intNumber=${random.int} # random long number User.random. longNumber=${random.long} # random uuid user.random.uuid=${random.uuid} # random number up to 10 User.random. lessTen=${random.int(10)} # range=${random.int[1024,65536]}Copy the code

(2) Create a configuration binding class

springboot/src/main/java/com/xcbeyond/springboot/config/RandomConfig.java

package com.xcbeyond.springboot.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * Random number configuration class * @author xcbeyond */ @component // @configurationProperties (prefix="user.random") // Load the specified configuration file, obtain the corresponding key-value, @propertysource (value="config/random.properties") public class RandomConfig {private String secret; private int intNumber; private int lessTen; private int range; private long longNumber; private String uuid; public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public int getIntNumber() { return intNumber; } public void setIntNumber(int intNumber) { this.intNumber = intNumber; } public int getLessTen() { return lessTen; } public void setLessTen(int lessTen) { this.lessTen = lessTen; } public int getRange() { return range; } public void setRange(int range) { this.range = range; } public long getLongNumber() { return longNumber; } public void setLongNumber(long longNumber) { this.longNumber = longNumber; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; }}Copy the code

(3) Add a test method to Control to verify.

springboot/src/main/java/com/xcbeyond/springboot/controller/ControllerDemo.java

@requestMapping ("/randomSecret") public String randomSecret() {return randomConfig.getSecret(); }Copy the code

Visit http://localhost:8888/randomSecret, shows as follows:

51b9dfe08dccf728abdcc4f971a0bffe
Copy the code

2. Application. Properties file

SpringApplication will load the application.properties files sequentially from the following directories and add them to the Spring environment:

  • The /config subdirectory in the current directory.
  • Current directory.
  • Classpath /config package.
  • Classpath Root path (root).

Note: you can use ‘.yml ‘files instead of’.properties’.

If you prefer not to use the default application.properties as the profile name, you can customize the properties profile name and load it in the SpringApplication.

3. Profile-specific attributes

In addition to the application.properties file, profile-specific properties can also be defined using the naming convention application-{profile}.properties. Environment (Spring’s Environment abstraction interface) has a default set of profiles (default [default]) that are used when active profiles are not set (for example, if active profiles are not explicitly specified, Properties in application-default.properties will be loaded). Profile-specific properties are loaded in the same path as standard application.properties, and profile-specific files always overwrite non-specific files, Whether profile-specific files are packaged into jars or not. If multiple profiles are defined, the last one wins. For example, profiles defined by spring.profiles.active are added to profiles defined through the SpringApplicationAPI and therefore take higher precedence.

Note: If you have defined all files (not directories) under spring.config.location, those profile-specific files will not be considered. If you want to use the profile-specific property, use the directory under spring.config.location.

4. Property placeholder

When using a property defined in the application.properties configuration file, Spring first looks for the property in an existing environment variable, so you can use the property placeholder “${}” to refer to the defined value (for example, system properties) :

user.random.secret= ${random.value}  ${random.value} 
Copy the code

5. Use YAML instead of Properties

Yaml, an intuitive, computer-readable data serialization format, is also a convenient format for defining hierarchical configuration data.

In Eclipse, you can directly convert properties to YAML through the Spring plug-in. The transformation results are as follows:

(Right-click convert.properties to.yaml in the application.properties file to Convert.)

druid: driver-class: com.mysql.jdbc.Driver initial-size: 1 max-active: 20 min-idle: 1 password: 123456 test-on-borrow: True url: JDBC: mysql: / / 192.168.0.20:3306 / test username: root server: port: 8888Copy the code