IO /spring-boot…

Introduce the key features of Spring Boot in detail, for students who have a certain springboot foundation.

directory

  • 1 External Configuration
    • 1.1 Configuring A Random Value
    • 1.2 Accessing cli Properties
    • 1.3 Application property files
    • 1.4 Configuration file specific properties
    • Placeholders in 1.5 properties
    • 1.6 Use YAML instead of Properties
      • 1.6.1 load YAML
      • 1.6.2 YAML as a property in the Spring environment
      • 1.6.3 Multiple YAML Files
      • 1.6.4 Disadvantages of YAML
      • 1.6.5 Merging YAML Lists

1. External configuration

Spring Boot allows you to externalize configuration to use the same application code in different environments. You can externalize the configuration using properties files, YAML files, environment variables, and command-line arguments. You can use the @Value annotation to inject property values directly into your bean, accessed through Spring’s Environment abstraction, or bound to structured objects through @ConfigurationProperties.

Spring Boot uses the very special PropertySource command designed to allow intelligent overwriting of values. Attributes are considered in the following order:

    1. Devtools global Settings properties in your home directory (~/.spring-boot-devtools.propertiesWhen DevTools is active).
    1. @TestPropertySourceComments are in your unit tests.
    1. @SpringBootTest #propertiesThe annotation properties are in your unit tests.
    1. Command line arguments.
    1. fromSPRING_APPLICATION_JSON(embedded JSON in environment variables or system properties)
    1. *ServletConfig *init parameter.
    1. *ServletContext *init parameter.
    1. JNDI properties from Java:java:comp/env.
    1. Java System Properties (System. The getProperties ()).
    1. OS environment variables.
    1. aRandomValuePropertySource, only random properties.
    1. Application-specific application properties outside of the packaged JAR (application- {profile} .propertiesAnd YAML variables).
    1. Configuration file specific application properties wrapped in jar (application- {profile} .propertiesAnd YAML variables).
    1. Your packaged JAR (application.propertiesAnd YAML variables).
    1. Application properties are packaged in your JAR (application.propertiesAnd YAML variables).
    1. @PropertySourceComments in your@ConfigurationClass.
    1. Default properties (useSpringApplication.setDefaultPropertiesSpecified).

To provide a concrete example, suppose you develop a @Component that uses the name attribute:

import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*

@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}
Copy the code

In your application classpath (for example, in your JAR), you can have an application.properties that provides a sensible default property value for name. When running in a new environment, you can override the name by providing an application.properties outside of your JAR; For one-time tests, you can start them with a specific command-line switch (for example, java-jar app.jar –name = “Spring”).

Note: The SPRING_APPLICATION_JSON property can provide an environment variable on the command line. For example, in the UN * X shell:

$SPRING_APPLICATION_JSON ='{" foo ": {" bar" : "spam"}}' java-jar myapp.jarCopy the code

In this case, you’ll end up with foo.bar=spam in the springEnvironment. You can also provide JSON in system variables as spring.application. JSON:

Json ='{" foo ":" bar "}'-jar myapp.jarCopy the code

Or command-line arguments:

$java-jar myapp.jar --spring.application.json ='{" foo ":" bar "}'Copy the code

Or as a JNDI variable Java: comp/env/spring.application.json.

1.1 Configuring A Random Value

RandomValuePropertySource can be used for injection of random values (for example, enter the secret or test cases). It can produce integers, long integers, UUID, or strings, for 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 the range = ${random. Int [1024655] 36}Copy the code

Random. Int * The syntax is *OPEN value (, Max) CLOSE *, where OPEN, CLOSE is any character and value, and Max is an integer. If Max is provided, the value is the minimum and Max is the maximum (inclusive only).

1.2 Accessing cli Properties

By default, SpringApplication converts any command-line option argument (starting with a ‘-‘, such as –server.port = 9000) to a property and adds it to Spring’s Environment.

As mentioned above, command line attributes always take precedence over other attribute sources. If don’t want to add command line attribute to the Environment, can use SpringApplication. SetAddCommandLineProperties disable them (false).

1.3 Application property files

SpringApplication loads the properties from the application.properties file at the following location and adds them to the Spring Environment in the current directory:

    1. a/ configSubdirectory.
    1. In the current directory
    1. A classpath/configThe bartender
    1. Class path to the root

The list is sorted by priority (attributes defined in attributes defined in the list are overridden in positions defined in lower positions).

Note: You can also use YAML (‘.yml’) files instead of ‘.properties ‘.

If you don’t like application.properties as a configuration file name, you can switch to another by specifying a spring.config.name environment property. You can also reference explicit locations using the spring.config.location environment property (a comma-separated list of directory locations or file paths).

 $ java -jar myproject.jar --spring.config.name = myproject
Copy the code

or

$Java - jar myproject. Jar - spring. Config. The location = classpath: / default properties, the classpath: / override propertiesCopy the code

Note: Spring. Config. name and spring.

If spring.config.location contains directories (rather than files), they should end with/(and will append the name generated from spring.config.name, including file-specific file names, before loading). The files specified in spring.config.location are used as-is, no config file specific variables are supported, and will be overridden by any config file specific properties.

The default search paths classpath:,classpath:/ config,file:,file:config/are always used regardless of the value of spring.config.location. This search path is sorted from lowest priority (File :config/highest priority).

If you specify your own locations, they take precedence over all default locations and use the same lowest to highest priority ordering. This way, you can set the default value for your application in application.properties (or whatever base name you choose using spring.config.name) and override it with a different file at run time, leaving the default value.

Note: Most operating systems do not allow period-separated key names if environment variables are used instead of system properties, but underline can be used (for example SPRING_CONFIG_NAME instead of spring.config.name).

Note: If you are running JNDI properties in a container (in Java: comp/env) or servlets can use context initialization parameters instead of environment variables or system properties.

1.4 Configuration file specific properties

In addition to the application.properties file, you can also define configuration file-specific properties using the naming convention application- {profile}.properties. The Environment has a default profile (default is [default]) if the active profile is not set (that is, properties from application-default.properties are loaded if the profile is not explicitly activated).

Profile specific properties are loaded from the same location as the standard application.properties, and profile specific files always overwrite non-specific files regardless of whether the profile specific files are inside or outside the packaged JAR.

If several profiles are specified, the last priority policy is applied. For example, profiles specified by the spring.profiles.active property are added after configuration through the SpringApplication API and therefore take precedence.

Note: If you specify any files in spring.config.location, configuration file-specific variables for those files are not considered. Use If you also want to use configuration file-specific properties, specify the directory in spring.config.location.

Placeholders in 1.5 properties

The values in application.properties are filtered by using the existing Environment so that you can refer to previously defined values (for example, from system properties).

app.name = MyApp 
app.description = $ {app.name} is a Spring Boot application
Copy the code

You can also use this technique to create “short” variants of existing Spring Boot properties.

1.6 Use YAML instead of Properties

YAML is a superset of JSON, so it’s a very convenient format for specifying hierarchical configuration data. As long as you have the SnakeYAML library in your classpath, the SpringApplication class will automatically support YAML as an alternative method for properties.

Note: If you use “Starters”, SnakeYAML will be provided automatically through spring-boot-starter.

1.6.1 load YAML

The Spring Framework provides two convenient classes that you can use to load YAML documents. YamlPropertiesFactoryBean will load YAML as Properties, and YamlMapFactoryBean will load YAML as a Map. For example, the following YAML document:

environments:
    dev:
        url: http://dev.bar.com
        name: Developer Setup
    prod:
        url: http://foo.bar.com
        name: My Cool App
Copy the code

Will be converted to these properties:

environments.dev.url=http://dev.bar.com
environments.dev.name=Developer Setup
environments.prod.url=http://foo.bar.com
environments.prod.name=My Cool App
Copy the code

YAML lists are represented as property keys with [index] dereference, such as YAML:

my:
   servers:
       - dev.bar.com
       - foo.bar.com
Copy the code

Will be converted to these properties:

my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
Copy the code

To bind to such a property using the Spring DataBinder utility (which is what @ConfigurationProperties does), you need to have a property in the target bean of type java.util.list (or Set), And you need to provide a setter, or initialize it with mutable values, such as this will bind to the property above

@ConfigurationProperties(prefix="my") public class Config { private List<String> servers = new ArrayList<String>(); public List<String> getServers() { return this.servers; }}Copy the code

Note:

You need to be careful when configuring lists, because overwriting will not work properly. In the example above, when I redefined my. Servers in several places, the individual element was targeted for overlays, not lists. To ensure that a higher-priority PropertySource can override a list, you need to define it as a single property:

my:
   servers: dev.bar.com,foo.bar.com
Copy the code
1.6.2 YAML as a property in the Spring environment

You can use the YamlPropertySourceLoader class to expose YAML as an PropertySource in the SpringEnvironment. This allows you to access YAML properties using the familiar @value annotation and placeholder syntax.

1.6.3 Multiple YAML Files

You can use the spring.profiles key to specify multiple profile specific YAML documents in a single file to indicate when the document is applied. Such as:

Server: address: 192.168.1.100 -- spring: profiles: development server: address: 127.0.0.1 -- spring: profiles: Production server: address: 192.168.1.120Copy the code

In the example above, if the Development profile was active, the server.address property would be 127.0.0.1. If the development and Production profiles are not enabled, the value of this property will be 192.168.1.100.

If the application context is not explicitly activated when it starts, the default configuration file is activated. So in this YAML, we set a value for security.user.password that is only available in the “default” configuration file:

server:
  port: 8000
---
spring:
  profiles: default
security:
  user:
    password: weak
Copy the code

In this example, because the password is not attached to any configuration files, the password is always set and must be reset explicitly in all other configuration files if necessary:

server:
  port: 8000
security:
  user:
    password: weak
Copy the code

The spring profile specified using the “spring.profiles” element is optionally used! Characters. If negative and non-negative profiles are specified for a single document, at least one of the non-negative profiles must match, and no negative profiles may match.

1.6.4 Disadvantages of YAML

YAML files cannot be loaded through the @propertysource annotation. Therefore, in cases where you need to load values in this way, you need to use properties files.

1.6.5 Merging YAML Lists

As mentioned above, any YAML content is ultimately converted to attributes. This process can be intuitive when overwriting the list property through a configuration file.

For example, consider MyPojo objects whose name and description attributes are null by default. Let’s expose the list of myPOJOs from FooProperties:

@ConfigurationProperties("foo") public class FooProperties { private final List<MyPojo> list = new ArrayList<>(); public List<MyPojo> getList() { return this.list; }}Copy the code

Consider the following configuration:

foo:
  list:
    - name: my name
      description: my description
---
spring:
  profiles: dev
foo:
  list:
    - name: my another name
Copy the code

If the dev profile is inactive, fooProperties.list will contain a MyPojo entry as defined above. If the dev profile is enabled, the list will still contain only one entry (named “my other name” and described as NULL). This configuration does not add a second instance of MyPojo to the list, and it does not merge items.

foo:
  list:
    - name: my name
      description: my description
    - name: another name
      description: another description
---
spring:
  profiles: dev
foo:
  list:
     - name: my another name
Copy the code

In the example above, given that the dev profile is active, fooProperties.list will contain a MyPojo entity (containing the name “My Another is described as null).

When a collection is specified in multiple configuration files, the collection with the highest priority is used (and only that collection is used) :