SpringBoot Learning Notes-004

II. Profiles

2.1. Profile

SpringBoot uses a global profile with a fixed profile name:

  • application.protperties

  • application.yml

The role of configuration files: modify the default values of SpringBoot auto-configuration; SpringBoot automatically configures us at the bottom level;

YAML ( YAML Ain't Markup Language )

YAML A Markup Language: is a markup language;

YAML is't Markup Language: not a markup language;

Markup Language:

Previous configuration files; mostly xxx.xml files are used;

YAML: Data-centric, more suitable for configuration files than json. xml, etc.

YAML: Configuration example

server:
  port: 8081

XML:

<server>
    <port>8081</port>
</server>

2.2, YAML syntax

2.2.1, Basic Grammar

k:(space) v: means-pair key-value pairs (spaces must have);

Control hierarchical relationships by indentation of spaces; as long as a left-aligned column of data is the same hierarchy

server: 
  port: 8081
  path: /hello

Attributes and values are also case sensitive;

2.2.2, Writing of values

1. Literal quantity: normal value (number, string, Boolean)

k:v: Write literally directly;

String does not need single or double quotation marks by default;

"": double quotation marks; special characters inside strings are not escaped; special characters are used as their own meaning

For example: name:'zhangsan \n lisi': output; Zhangsan newline Lisi

'': single quotation mark; escapes special characters, which are ultimately just plain string data

For example: name:'zhangsan \n lisi': output; Zhangsan \n Lisi

2. Objects, Map s (attributes and values) (key-value pairs):

k: v: Write the relationship between the object's attributes and values in the next industry; note indentation

Object or way of k: v

friends:
    lastName: zhangsan
    age: 20

Inline Writing:

friends: {lastName: zhangsan,age: 18}

3. Arrays (List, Set):

Represent an element in an array with a value

pets:
  - cat
  - dog
  - pig

Inline writing

pets: [cat,dog,pig]

2.3, Profile Value Injection

configuration file

person:
  lastName: hello
  age: 18
  boss: fasle
  birth: 2019/12/12
  maps: {k1: v1,k2: 12}
  list:
    - list
    - zhaoliu
  dog:
    name: puppy
    age: 12

javaBean:

/**
 * Map the value of each property configured in the configuration file to this component
 * @ConfigurationProperties: Tell SpringBoot to bind all the properties in this class to the related configurations in the configuration file;
 *      prefix = "person": Which of the following properties in the configuration file maps one at a time
 *
 * Only if this component is a component in a container can the @ConfigurationProperties function provided by the container be enabled;
 *  @ConfigurationProperties(prefix = "person")Get the value from the global configuration file by default;
 *
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

We can import the profile processor to write the configuration

<!--Import the profile processor and you will be prompted to bind the profile-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

2.3.1, Properrties profile scrambling problem

Note the file properties, just use UTF-8.

2.3.2, @Value get value and @ConfigurationProperties get value comparison

@ConfigurationProperties @Value
function Bulk Injection Properties in Configuration File Specify one by one
Loose Binding (Loose Syntax) Support I won't support it
SpEL I won't support it Support
JSR303 Data Check Support I won't support it
Complex Type Encapsulation Support I won't support it

Configuration file ym or properties both get values;

If we just need to get a value in the configuration file in some business logic, use @Value

If we wrote a javaBean specifically to map to the configuration file, we would use @ConfigurationProperties directly.

2.3.3, Profile Injection Data Check

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="Literal /${key} Gets the value from the environment variable, configuration file /#{SpEL} ">
     *      </property>
     * <bean/>
     */

    //lastName must be in mailbox format
    @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

    private Date birth;
    //@Value("${person.maps}")
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

2.3.4,@PropertySource&@ImportResource&@Bean

@PropertySource: Load the specified configuration file;

/**
 * Map the value of each property configured in the configuration file to this component
 * @ConfigurationProperties: Tell SpringBoot to bind all the properties in this class to the related configurations in the configuration file;
 *      prefix = "person": Which of the following properties in the configuration file maps one at a time
 *
 * Only if this component is a component in a container can the @ConfigurationProperties function provided by the container be used;
 *  @ConfigurationProperties(prefix = "person")Get the value from the global configuration file by default;
 *
 */
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="Literal /${key} Gets the value from environment variables, configuration files /#{SpEL}'></property>
     * <bean/>
     */

   //lastName must be in mailbox format
   // @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

    private Date birth;
    //@Value("${person.maps}")
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

@lmportResource: Import Spring's configuration file so that the contents of the configuration file take effect;

There are no Spring profiles in Spring Boot, and the profiles we write ourselves cannot be automatically identified.

To make Spring's configuration file valid, load it; @lmportResource is labeled on a configuration class

\\Import Spring Profile to make it work
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot02ConfigApplication {

Don't write Spring's profile

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>

SpringBoo recommends adding components to containers; full annotation is recommended

1), Configuration class @Configuration---->Spring configuration file

2) Add components to containers using @Bean

/**
 * @Configuration: Indicates that the current class is a configuration class; that is, to replace the previous Spring configuration file
 *
 * Add components in the configuration file with the <bean><bean/>tag
 *
 */
@Configuration
public class MyAppConfig {

    //Add the return value of the method to the container; the default id for this component in the container is the method name
    @Bean
    public HelloService helloService02(){
        System.out.println("Configuration Class@Bean Add Components to Container...");
        return new HelloService();
    }
}

2.4, Profile point bits

2.4.1, random numbers

${random.value},${random.long},${random.int}
${random.int(10)},${random.int[1024,65536]}

2.4.2, Placeholder to get the previously configured value, if not available: Use the default value

person.last-name=\u5F20\u4E09${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15

2.5 Profile

2.5.1, Multiple Profile Files

When we write the main configuration file, the file name can be application-{profile}.properties/yml

Use the configuration of application.properties by default;

2.5.2, yml support multi-document block mode


server:
  port: 8081
spring:
  profiles:
    active: prod

---
server:
  port: 8083
spring:
  profiles: dev


---
server:
  port: 8084
spring:
  profiles: prod #Specify which environment to belong to

2.5.3, Activate specified Profile

1) Specify spring.profiles.active=dev in the configuration file

2) Command line:

    java -jar  spring-boot-02-config-0.0.1-SNAPSHOT.ja **--spring.profiles.active=dev**

    You can configure incoming command line parameters directly when testing

3) Virtual machine parameters:

​ -Dspring.profiles.active=dev

2.6. Loading location of configuration file

Spring boot startup scans application.properties or pplication.yml| files in the following locations as default configuration files for Spring boot

1. file:.config/
2. file:./
3. classpath:/config/
4. classpath:/

From high priority to low priority, high priority configuration overrides low priority configuration.

SpringBoot loads the main configuration file from all four locations; complementary configuration*

You can also change the default configuration file location through spring.config.location

Once the project is packaged, we can use command line parameters to specify the new location of the configuration file when starting the project; specify the configuration file and the configuration files loaded by default work together to form complementary configurations;

java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties

Tags: Programming Spring SpringBoot xml Java

Posted on Tue, 10 Mar 2020 12:39:41 -0400 by Duke555