Chapter 01 Spring-Boot application file application configuration

Chapter 01 Spring-Boot application file application configuration

foreword

  • Why use Spring-Boot?

    You can refer to the official documentation.

  • What is Spring-Boot?

    Refer to the official documentation for instructions.

  • official address

    https://spring.io/projects/spring-boot

Target

  • Complete the installation and configuration of Jenkins in Docker.
  • Jenkins installed in Docker can provide external services normally.
  • The Jenkins continuous integration service can be accessed and used normally in the external development environment.

environment

  • **VMware:**VMware Workstation 14 Pro

  • **Linux:**CentOS7.4

  • **Docker:**18.06.0-ce, build 0ffa825

  • **Jenkins:**Jenkins2.121.1

  • **JDK:**jdk1.8.0_172

  • **Spring-Boot:**2.0.4

  • **Eclipse:**Eclipse Neon.3 (4.6.3)

  • spring-tool-suite:

    Version: 3.8.4.RELEASE
    Build Id: 201703310825
    Platform: Eclipse Neon.3 (4.6.3)

  • **Maven:**3.5.0

Random value configuration

xxx.secret=${random.value}
xxx.number=${random.int}
xxx.bignumber=${random.long}
xxx.number.less.than.ten=${random.int(10)}
xxx.number.in.range=${random.int[1024,65536]} 

Annotations can be used in application code to read:@Value(value = "${xxx.secret}")

Note: The yellow dot prompt appears, it is to prompt to configure metadata, and it is not necessary to configure

attribute placeholder

When values ​​in application.properties are used, they are filtered by the existing Environment, so you can refer to previously defined values ​​(for example, system properties).

xxx.name=www.google.com
xxx.desc=${xxx.name} is a domain name

Application configuration file load order

Application configuration files are loaded in order of priority, and those with higher positions will overwrite those with lower positions

  1. A /config subdirectory under the current directory

  2. Current directory

  3. A /config package on the classpath

  4. classpath root path (root)

The list is ordered by priority (higher in the list will override lower ones)

Apply configuration file key-value pair overrides

The loading order of application configuration files, the same key-value pair will overwrite the value, and the later one will overwrite the previous one.

  1. @TestPropertySource annotation
  2. command line parameters
  3. Java System Properties (System.getProperties())
  4. operating system environment variables
  5. Only properties contained in random.* will generate a RandomValuePropertySource
  6. Application configuration file (application.properties, containing YAML and profile variables) outside the packaged jar
  7. Application configuration file (application.properties, containing YAML and profile variables) inside the packaged jar
  8. @PropertySource annotation on @Configuration class
  9. Default properties (specified using SpringApplication.setDefaultProperties)

Common configuration

Application port configuration

server.port=8090

Time formatting configuration

spring: 
  jackson.time-zone: Asia/Shanghai
  jackson.date-format: yyyy-MM-dd HH:mm:ss

time zone setting

spring: 
  jackson.time-zone: Asia/Shanghai

Note: use YAMLalternative Propertieswriting, add a space after the colon

Multi-environment configuration

Benefits of a multi-environment configuration

1. Different environment configurations can configure different parameters

2. Easy to deploy, improve efficiency and reduce errors

Properties multi-environment configuration

1. Configure activation options

spring.profiles.active=dev

2. Add other configuration files

application-dev.properties
application-test.properties
application-prod.properties
application.properties

YAML multi-environment configuration

1. Configure activation options

spring:
  profiles:
    active: dev

2. Add three short horizontal lines in the English state to the configuration file to distinguish

---
spring:
  profiles: dev

Comparison of two configurations

  1. Properties configure multiple environments, you need to add multiple configuration files, YAMLonly one accessory file is required

    2. The difference in writing format yamlis relatively simple and elegant

  2. YAMLDisadvantages: cannot be @PropertySourceloaded via annotations. If you need to @PropertySourceload values ​​using annotations, you need to use the properties file.

how to use

java -jar myapp.jar --spring.profiles.active=dev

Advanced Configuration

1. Configuration method

1. The configuration content of the Spring Boot application can be centrally configured in the src/main/resource/application.properties file.

According to the different Starter modules we introduced, various configuration information such as container port number, database connection ixnxi, and log level can be defined here.

2. Support YAML files that are now widely recommended.

YAML (English pronunciation is similar to camel) is a highly readable format for expressing data sequences.

The full name is: YAML Ain't a Markup Language, not a markup language.

The meaning of YAML is actually: Yet Another Markup Language (still a markup language), but in order to emphasize that this language is data-centric rather than markup language-focused, it is renamed with a reverse acronym.

The YMAL design refers to a variety of languages, including C language, python, perl, and gets inspiration from XML, email data format (RFC 2822).

YMAL features:

The syntax of YMAL is similar to other high-level languages, and can simply express forms such as lists, hash tables, and scalars.

It is especially suitable for expressing or editing data structures, various setting documents, and file outlines using whitespace indentation and a large number of appearance-dependent features.

It is more suitable for expressing hierarchical data structures, and can also express relational model data with exquisite syntax.

YMAL uses whitespace and line breaks to separate data, making it especially suitable for grep/python/perl/ruby operations.

Cleverly avoid all kinds of closed symbols, such as quotation marks, various brackets, etc. These symbols will become complicated and difficult to recognize when nested.

--Wikipedia

The configuration format adopted by YAML is not expressed in the form of simple key-value pairs like the configuration of properties, but in an indented form similar to an outline.

YMAL can also define multiple different environment variables in a single file by using the spring.profies property. Such as default, specified and other forms.

server:

port: 8881

spring:

profiles: test

server:

    port: 8882

\---

spring:

    profiles: prod

server:

    port: 8883

Note: YMAL still has some shortcomings, it cannot load configuration through @PropertySource annotation. However, YAML loads properties into memory in an orderly manner, so when the information in the configuration file needs to have sequential meaning, the YAML configuration method has more advantages than the properties configuration file.

2. How to implement multi-environment configuration

In Spring Boot, the file name of the multi-environment configuration needs to meet the format of application-{profile}.properties, where {profile} corresponds to your environment ID, for example:

application-dev.properties: development environment

application-test.properties: test environment

application-prod.properties: production environment

As for which configuration file will be loaded, it needs to be set through the spring.profiles.active property in the application.properties file.

The value of this configuration property can be dynamically modified at startup:

java -jar xxx.jar --spring.profiles.active=prod

Summarize the configuration ideas of multiple environments:

1. Configure common content in application.properties, and set spring.profiles.active=dev, with the development environment as the default configuration

2. Configure each environment in application-{profile}.properties.

3. Deactivate the configuration of different environments through the command line.

3. Loading order of configuration information

In order to rewrite the value of each attribute more reasonably, Spring Boot uses the following special attribute loading order:

1. The parameters passed in on the command line.

2. Properties in SPRING_APPLICATION_JSON. SPRING_APPLICATION_JSON is the content configured in the system environment variable in JSON format.

3. JNDI properties in java:com/env.

4. The Java system properties can be obtained through System.getProperties().

5. Environment variables of the operating system.

6. Random attributes configured by random.*.

7. The contents of the configuration file for different {profile} environments located outside the current application jar package, such as application-{profile}.properties or configuration files defined by YMAL.

8. Located in the jar package of the current application, the contents of configuration files for different {profile} environments, such as application-{profile}.properties or configuration files defined by YMAL.

9. Application.properties and YMAL configuration content located outside the current application jar package.

10. The application.properties and YMAL configuration content located in the current application jar package.

11. In the class modified by the @Configuration annotation, the property defined by the @PropertySource annotation.

12. To apply default properties, use the content defined by SpringApplication.setDefaultProperties.

The priority is from high to low in the above order, and the smaller the number, the higher the priority.

It can be seen that items 7 and 9 read configuration files from outside the application jar package. Therefore, the principle of implementing external configuration is to start from this point and specify the loading location of the external configuration file to replace the jar package. configuration content within.

In this way, the configuration of our project becomes very clean. We only need to place the configuration required for development locally, and it does not need to be related to the configuration of other environments, and the person in charge of the corresponding environment can maintain it.

4. Custom parameters

In addition to setting the predefined configuration properties in each Starter module in the Spring Boot configuration file, you can also define some custom properties we need in the configuration file, defined in application.properties:

you.name=kony

you.age=18

These custom parameters can be loaded in the application through the @Value annotation.

@Service

public class person{

@Value("${you.name}")

private String name;

@Value("${you.age}")

private int age;

getter...

setter...

}

The @Value annotation loads attribute values ​​to support two expressions for configuration:

1. One is the PlaceHolder method, the format is ${…}.

2. The other is to use SpEL expression (Spring Expression Language), the format is #{…}.

Five, parameter reference

The parameters in application.properties can be directly referenced by using PlaceHolder.

you.name=kony

you.age=18

person.desc=my name is ${you.name} and age ${you.age}

6. Use random numbers

In some special cases, it is hoped that some parameters are not a fixed value each time they are loaded, such as passwords, service ports, etc. In Spring Boot's property files, random int, long, and string values ​​can be interpreted by using ${random} configuration. It is not necessary to implement these logics through coding in the program.

The configuration methods are as follows:

# random string

you.name=${random.value}

#random int

you.age=${random.int}

#random long

you.long=${random.long}

Random numbers within #10

you.random.scope1=${random.int(10)}

#10-20 random number

you.random.scope2=${random.int(10,20)}

This configuration can set application port scenarios to avoid port conflicts.

7. Command line parameters

How to start a Spring Boot application?

Use the command: java -jar, in addition to starting the application, this command can also specify the parameters of the application in the command line, such as java -jar xxx.jar --server.port=8080, directly set the server in the command line .port property.

Two consecutive minus signs – it is the identification of assigning the property value in application.properties, which is equivalent to adding the property server.port=8080 in the file.

you.age=${random.int}

#random long

you.long=${random.long}

Random numbers within #10

you.random.scope1=${random.int(10)}

#10-20 random number

you.random.scope2=${random.int(10,20)}

This configuration can set application port scenarios to avoid port conflicts.

7. Command line parameters

How to start a Spring Boot application?

Use the command: java -jar, in addition to starting the application, this command can also specify the parameters of the application in the command line, such as java -jar xxx.jar --server.port=8080, directly set the server in the command line .port property.

Two consecutive minus signs – it is the identification of assigning the property value in application.properties, which is equivalent to adding the property server.port=8080 in the file.

Modifying property values ​​​​through the command line is a very important feature of Spring Boot.

Guess you like

Origin blog.csdn.net/pointdew/article/details/108541332