The premise

This article is the “fourth” article in the SpringBoot2.x Introduction album, using SpringBoot version 2.3.1.RELEASE with JDK version 1.8.

This section describes some common properties of SpringBoot configuration files, loading priorities of configuration files, and precautions related to configuration.

Configuration files about SpringBoot

The structure of a standards-based Maven project that introduces SpringBoot components is as follows:

Root (project Root)  - src
   - main
    - java
-resources # <-- this is the directory where the resources files are stored - target  pom.xml Copy the code

Resource files are stored in SRC /main/resouces, and configuration files are resource files by nature, so “in-project” configuration files are stored in that directory. The implementation of SpringBoot’s PropertySourceLoader PropertySourceLoader currently supports Properties and Yaml configuration file types. Each has its own advantages: The configuration Properties of Yaml are more flexible, while the configuration of Properties is less prone to errors. (The technical specification of my previous company specified that SpringBoot applications must use Properties configuration files, because operation and maintenance or development colleagues used Yaml files for production configuration. Serious production glitches due to whitespace issues during editing). The Properties configuration file is used as an example below.

SpringBoot profiles use the concept of profiles, which can be likened to identifiers that distinguish different environments. A SpringBoot application can use multiple profiles. So the configuration file must be in application-${profile} format. File suffixes such as:

src/main/resources
   - application.properties
- application-dev.properties # <-- profile = dev, development environment configuration- application-test.properties # <-- profile = test, test environment configurationCopy the code

The application. Properties file without the profile identifier can be interpreted as the “master profile”, that is, the SpringBoot configuration file is actually inherited, when the project starts, the master configuration file will be loaded first anyway. The profile identified by the activated profile is then loaded. You can specify which profile to activate using the property spring.profiles.active, for example:

Specify load application-dev.properties spring.profiles.active=dev or load both application-dev.properties and application-test.properties spring.profiles.active=dev,testCopy the code

Spring.profiles. active is typically specified in the main configuration file application.properties, Active =prod app.jar or java-jar app.jar –spring.profiles.active=prod).

Can automatic assembly org. Springframework. Core. The env. The Environment, through Environment# getActiveProfiles () gets the current active profile array, such as:

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment; import java.util.Arrays;  @Slf4j @SpringBootApplication public class Ch2Application implements CommandLineRunner {   @Autowired  private Environment environment;   public static void main(String[] args) {  SpringApplication.run(Ch2Application.class, args);  }   @Override  public void run(String... args) throws Exception {  log.info("Active profiles:{}", Arrays.toString(environment.getActiveProfiles()));  } } Copy the code

The running results are as follows:


The CommandLineRunner interface is used as an example, and its use will be described in a later article.

Common basic configuration properties

Spring-boot-starter-web is typically introduced to develop Web projects, and there are a few basic configurations that I consider necessary. The application name and default profile should be identified in the main profile application.properties. For example, the main profile for API gateway is as follows:

spring.application.name=api-gateway
spring.profiles.active=dev
Copy the code

In addition, there should be some non-volatile properties in the middle of the main configuration, such as the Mapper scan path for Mybatis, configuration properties for the template engine Freemarker, etc. The profile identified by the profile should be configured with some configurations that change with the environment or frequently change properties, such as MySQL data source configuration, Redis connection configuration, etc., so that the middleware connection properties or third party configuration of different environments can be directly switched through spring.profiles. In Hello World projects, server.port specifies the container’s startup port, as in application-dev.properties:

server.port=8081
Copy the code

Configure file loading priority and attribute overrides

In addition to the master profile taking precedence over the profile identified, SpringBoot also supports loading configuration files from the file system, which may not necessarily be in the project (or rather, in the package that the project has been compiled and printed out), but may also exist in specific disk paths. This point can be referred to the official SpringBoot document 2.Externalized Configuration section:


The default configuration file loading priorities are as follows:

  1. file:./config/(The same directory as the project deployment packageconfigIn the directoryapplication-[profile].[properties,yaml]File)
  2. file:./config/*/(The same directory as the project deployment packageconfigAny subdirectory in the directoryapplication-[profile].[properties,yaml]File)
  3. file:./Of the directory where the project deployment package residesapplication-[profile].[properties,yaml]File)
  4. classpath:/config/(in the classpath of the project deployment packageconfigIn the directoryapplication-[profile].[properties,yaml]File)
  5. classpath:/(in the classpath of the project deployment packageapplication-[profile].[properties,yaml]File)

“Sharp-eyed partners may find that the configuration files added under the Resources directory in your project have the lowest loading priority (equivalent to item 5 when packaged).” By spring. Config. The location attribute to cover the above sequence, such as spring. The config. The location = classpath: /, the classpath: / config /, generally do not recommend to change the default configuration order, unless there is a special usage scenarios.

Alternatively, you can specify additional paths to search profiles via the spring.config.additional-location property “with a higher priority than the default configuration order.” If only spring.config.additional-location=classpath:/custom-config/,file:./custom-config/

  1. file:./custom-config/(The same directory as the project deployment packagecustom-configIn the directoryapplication-[profile].[properties,yaml]File)
  2. classpath:custom-config/(in the classpath of the project deployment packagecustom-configIn the directoryapplication-[profile].[properties,yaml]File)
  3. file:./config/(The same directory as the project deployment packageconfigIn the directoryapplication-[profile].[properties,yaml]File)
  4. file:./config/*/(The same directory as the project deployment packageconfigAny subdirectory in the directoryapplication-[profile].[properties,yaml]File)
  5. file:./Of the directory where the project deployment package residesapplication-[profile].[properties,yaml]File)
  6. classpath:/config/(in the classpath of the project deployment packageconfigIn the directoryapplication-[profile].[properties,yaml]File)
  7. classpath:/(in the classpath of the project deployment packageapplication-[profile].[properties,yaml]File)

Based on this feature, o&M partners can configure the configuration files of the production environment for services on the production server without connecting to the configuration center:

#Suppose this is the file path of the production server
/data/apps/api-gateway
     - api-gateway.jar
     - config
       - application-prod.properties
Copy the code

In writing the script when you only have to specify the profile for prod, application will read/data/apps/API – gateway/config/application – prod. The properties of the attribute, so it can avoid the production configuration or leaked sensitive attributes to the developers.

Another important issue here is that if a configuration file defines the same attribute in multiple paths, the attribute will be overwritten in a priority order. In addition to configuration files, SpringBoot also supports command lines, JNDI properties, system properties, and so on.

  1. Attribute parameters on the command line.
  2. Outside of the project deployment packageapplication-profile.[properties,yaml]File.
  3. Within the project deployment packageapplication-profile.[properties,yaml]File.
  4. Outside of the project deployment packageapplication.[properties,yaml]File.
  5. Within the project deployment packageapplication.[properties,yaml]File.

For example, if you add –app.author=throwable to the startup parameter and app.author=throwable-x to the application. App. author=throwable-y; app.author=throwable-y; app.author=throwable-y;


All configuration files are parsed to form a composite PropertySource. Parsed parameters are always at the top level, and properties are always fetched from the top level first.

Custom configuration properties for IDE affinity

Sometimes you need to configure custom properties, which will appear in the IDE will not be recognized and “yellow” scenarios. IDE affinity can be applied at this point. In mainstream ides like Eclipse and IntelliJ IDEA, Json or Additional – spring-spring-configuration-metadata. json. Provides directory boot jump function, no longer “yellow”. To do this, import the property metadata description file in the resources/ meta-INF directory of your project and write the property description:

// resources/META-INF/spring-configuration-metadata.json
{
  "properties": [
    {
      "name": "app.author". "type": "java.lang.String". "description": "The author of app."  }  ] } Copy the code

The format of the spring-configuration-metadata.json file can refer to the existing files in SpringBoot’s multiple starter files.

summary

This article briefly summarizes the configuration file loading priority order and configuration attributes override priority order, these two points need to be fully mastered, you can change the configuration file through some examples to familiarize yourself. Problems with configuration attribute overwriting can easily lead to production failures. If you know the content of this section, you can quickly locate and resolve SpringBoot configuration attribute problems. Code repository:

  • Github:https://github.com/zjcscut/spring-boot-guide/tree/master/ch2-profile

(C-2-D E-A-20200705)

Technical official account Throwable Digest (ID: Throwable – DOge) will push the author’s original technical articles from time to time (never plagiarize or reprint) :


This article is formatted using MDNICE