Distributed -- SpringBoot configuration principle

Maven tool advanced usage

Note: in maven, if A ----- > b -------- > C is introduced into the project, BC can be automatically introduced!!! How to achieve???

Analysis principle of Maven tool:
1). When the user relies on the jar package through the dependency tag, maven tool will look for the modified jar package file in the local warehouse through the coordinates

2). After Maven looks up the jar package file, it parses the pom.exe of the current jar package XML file, introducing related dependencies

Principle description:

  1. When passing POM When adding dependencies to XML files, maven tool will find jar package files by coordinates
  2. After loading the jar package, it will parse the current POM XML file. If there are any dependencies of jar package in it, parse and load the jar package again Finally, the transitivity of jar package is realized

Transmission principle of jar package in maven

Question: how to ensure that the jar package file is not tampered with by others in the process of remote transmission???
Algorithm Introduction: SHA1 algorithm

SHA-1 (English: Secure Hash Algorithm 1, Chinese Name: Secure Hash Algorithm 1) is a cryptographic hash function designed by the national security agency and published as the federal data processing standard (FIPS) by the National Institute of standards and Technology (NIST). SHA-1 can generate a 160 bit (20 byte) hash value called message digest, which is usually presented as 40 hexadecimal numbers.

SpringBoot configuration

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <!--
      Maven: Maven It is a one-stop project management tool, which is responsible for the construction of the project/pack/test/Release and other work.


      Knowledge point 1: understand the function of coordinates
      maven Project identification group id/entry name/The version is called maven Coordinates of
      1.maven Managed in jar There are many package files. How to manage them effectively? In the form of coordinates
      2.In the local warehouse jar The position of the package is the position of the coordinates, maven Work performed by coordinate lookup jar

      Knowledge point 2: maven Medium jar The package file has transitivity of dependency
      example: A.jar ~~~ B.jar ~~~ C.jar ~~~ D.jar
      maven. jar How to realize the transitivity of package?

      When passed pom.xml When adding a dependency to a file, maven Will find based on coordinates jar Package file.
      When loading jar After the package is completed, the current will be parsed pom.xml File, if any jar The dependencies of the package are parsed and loaded again jar package
      Final realization jar Transitivity of packages
   -->
   <groupId>com.jt</groupId>
   <artifactId>springboot_demo1</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>springboot_demo1</name>
   <description>Demo project for Spring Boot</description>

   <!--
      effect:1.parent The label set defines springboot All dependencies jar Package version information( version),Solved by the official website jar Package conflict problem
         2.The file does not exist in the local warehouse jar Bag, parent Represents an aggregation project (definition: there are many small projects under a large project)
   -->
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.3.4.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

      <!--maven Configuration information of the project-->
   <properties>
      <!--Specified jdk Version information-->
      <java.version>1.8</java.version>
      <!--Skip the test class run. By default, the program packaging will execute the test class. If there is a problem with the test class, the program packaging fails-->
      <skipTests>true</skipTests>
   </properties>

   <dependencies>
      <!--
         Manual dependency. The dependency is springBoot Highly integrated
         springBoot Help you dynamically generate configuration items and simplify the steps of configuration. This configuration is called automatic configuration information
         spring-boot-starter springBoot Automated startup items
         Out of the box: just import jar The corresponding functions can be realized by simple configuration of the package
      -->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
         <exclusions>
            <exclusion>
               <groupId>org.junit.vintage</groupId>
               <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
         </exclusions>
      </dependency>


      <!--Support hot deployment -->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
      </dependency>

   </dependencies>

   <!--SpringBoot utilize maven Project packaging with management tools/release/Other operations-->
   <!--Without this build Label, we will prompt when packaging and publishing( jar (no main list attribute in)-->
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
About Maven command execution

1. Empty the target file
2. Compile the project
3. Project packaging

The projects that are made into jar packages are issued with dos commands

java -jar xxx.jar

SpringBoot main startup class description

Question Description: why is the main startup class specified? The tomcat server can run automatically, and the spring MVC framework can be configured automatically?

Description of meta annotation
1.@Target(ElementType.TYPE) identifies who the annotation is valid for This annotation indicates that it is valid for the class
2.@Retention(RetentionPolicy.RUNTIME) identifies that the validity period of the annotation is valid at runtime Usually write runtime
3.@Documented dynamically generates documents
4. Whether @ inherited allows child annotations to inherit this annotation

@SpringBootConfiguration description

Function: identify that the main startup class is a large configuration file, and all small configuration files will be loaded at startup

@Configuration

Indicates that this class is a configuration class

excludeFilters property description

Note: some filters do not need to be loaded when the springboot container starts Because all associated jar package file information is defined in the parent tag It may cause accidents when starting, and all need to be eliminated in advance
example:

@SpringBootApplication(exclude=DataSourceAutoConfiguration.class)
//Indicates that the database driven dependency configuration is not loaded

@EnableAutoConfiguration

Out of the box: as long as the specified jar package file is imported, the configuration can be realized automatically!!!

@AutoConfigurationPackage

Note: when the program starts, its descendant packages will be scanned according to the package path of the main startup class. Therefore, when writing code after springboot, it should be edited under its descendant package

@Import(AutoConfigurationImportSelector)

Note: this configuration internally integrates all selectors in SpringBoot The main task of these selectors is to check whether they have the configuration of startup items managed by their own selectors If the startup item is found, the selector will execute the startup item, thus realizing the operation out of the box

Load class information of the third party

@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),

@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

Description of SpringBoot configuration file

properties description

1. Syntax: k-v structure key=value
2. Data type: the default is String data type. Don't add extra ""
3. Character data type: the default loaded encoding format of properties is ISO-8859-1, so adding Chinese requires character conversion
4. Disadvantages: all key s must be edited manually and cannot be reused, so yml configuration is introduced

YML profile description

1. Syntax K-V structure: key:value in essence, key=value
key:value is separated by (: + space)
There is a parent-child relationship between key and key So pay attention to indent items when writing
The default format of YML configuration files is UTF-8 coding, so you can edit Chinese directly

About spring MVC calling process

1. All requested transfer stations of the front-end controller
2. The processor mapper maps (binds) the user's request to the executed business method
3. Processor adapter
4. View parser

About assignment operation of configuration file

@Value annotation attribute assignment

Requirement: sometimes the value of the attribute in the object may change. If it is written directly into the code, it may lead to high coupling Can I use the configuration file to dynamically assign values to attributes

Edit YML profile

# Syntax: 1 Key value structure 2 Use: (space) to split between key and value 
#         2. The YML configuration file has a hierarchical structure
server:
  port: 8090
  servlet:
    context-path: / #Project publishing path information default / root directory
    # The default publishing path address of tomcat server is webapps directory    
    # /ROOT project path
    # /JT JT project path
    
#Specify user profile information
msg:
  username: Xu Sanduo
  age: 10 

Using annotation value

 @RestController
public class MsgController {
    
    //Sometimes, attributes may be assigned dynamically in the form of configuration files
    
    /**
     * @Value Represents the dynamic acquisition of data from the spring container
     * Dynamic value through spel expression
     */
    @Value("${msg.username}")
    private String  username;    //user name
    @Value("${msg.age}")
    private Integer age;        //Age
    
    
    @RequestMapping("/getMsg")
    public String getMsg() {
        
        return "Return value result:"+username+":"+age;
    }
    
}

Batch assignment of attributes

Requirement description

When springBoot integrates the third-party framework, it may encounter the problem of multiple attribute assignment If the Value is assigned by @ Value, the code is cumbersome Can you optimize???

Import package jar

 `<!--Add attribute injection dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>` 

Implement attribute assignment

package com.jt.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@ConfigurationProperties(prefix = "msg")
public class MsgController {
    
    //Sometimes, attributes may be assigned dynamically in the form of configuration files
    /**
     * Assign values to attributes in batch. You must cooperate with the set method to assign values
     */
    private String  username;    //user name
    private Integer age;    
    
    
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @RequestMapping("/getMsg")
    public String getMsg() {
        
        return "Return value result:"+username+":"+age;
    }
    
}

Use the properties file to assign values to the properties

Note: since YML configuration files are generally used to configure the integrated information of the third party, it is not standardized to add business data to YML It is best to add the business operations to the properties file

Add profile:

Edit RedisPro profile:
@RestController
//The configuration file needs to be loaded through the spring container and loaded in utf-8 format
@PropertySource(value="classpath:/properties/redis.properties",encoding = "UTF-8")
public class RedisProController {

    @Value("${redis.pro.host}")
    private String proHost;
    @Value("${redis.pro.port}")
    private Integer proPort;

    @RequestMapping("/getMsgPro")
    public String getMsg2(){

        return proHost + ":" + proPort;
    }

}

SpringBoot environment switching problem

Business requirements

Business scenario:
Employees are outsourcing personnel, who often need to go back and forth between the company and Party A. due to different locations during code debugging, the server IP address must be different If you have to edit the IP address, port and other data every time you change the environment, it must be cumbersome. Can you optimize it??

Business implementation - specify multiple environments

Note: no matter what kind of environment, the number of configurations is the same, only the values are different

# This configuration file is loaded when the spring container starts
spring:
  profiles:
    active: prod
---

# Define development environment
spring:
  profiles: dev

server:
  port: 8080

#Configure redis node information
redis:
  host: 192.168.1.100
  port: 6379

# If you need multi environment configuration, you need to split the YML environment
---
spring:
  profiles: prod

server:
  port: 8090

#Configure redis node information
redis:
  host: 10.0.0.1
  port: 6379

Add hot deployment configuration

1. Add jar package file

 `<!--Support hot deployment -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>` 
  1. Configure IDEA tools

Key combination: ctrl + shift + alt +/

Turn on automatic compilation:

Edit POJO

About LOMBOK interview questions

Question: after the java project is developed, you need to deploy the project in the Linux system Question: does the LomBok plug-in need to be installed separately in the Linux environment???
Test point: is the working principle of LOMBOK plug-in clear
A: B: No
Answer: B
Parsing: LOMBOK plug-in compiler is valid XXX Java file -- compile ----- XXX Class dynamically generates methods such as set/get/toString and adds them to Class file The jar package running in Linux is The collection of class files already has a get/set method Therefore, there is no need to introduce plug-ins

Focus on the principle of chain loading structure

@Data   //Dynamically generate get/set/toString/equals and other methods
@Accessors(chain = true)    //Open chain loading structure
@NoArgsConstructor//Nonparametric structure
@AllArgsConstructor//Full parameter construction} when adding a full parameter construction, you must add a nonparametric construction
public class User implements Serializable {
    private static final long serialVersionUID = -3205763327437547534L;
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
//Chain connection structure principle, the return value is this object
//User setName("ssss"). setId(100). setAge(100);
//    public User setId(Integer id){
//        this.id=id;
//        return this;
//    }
}

Sql connection description

1. Servertimezone = GMT% 2B8% 2B stands for "+" sign stands for time zone
2. Useunicode = true & characterencoding = utf8 specifies the encoding as utf-8
3. Autoreconnect = true & whether to reconnect if the program is disconnected from the database
4.allowMultiQueries=true allow batch operations
eg: it is required to store three table data at a time... It is required to use one row of sql to realize this operation

Edit YML profile

server:
  port: 80
  servlet:
    context-path: /
spring:
  datasource:
    #Driver version problem: the jc keyword needs to be added to the higher version, which can generally be omitted
    #driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/jtdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: 1234


mybatis:
  #The definition of alias package defines the package name of resultType in Mapper. We only need to write the class name and splice it automatically
  type-aliases-package: com.jt.pojo
  #Loads the specified xml Mapping file
  mapper-locations: classpath:/mybatis/mappers/*.xml
  #Turn on hump mapping. The details are in the XML file
  configuration:
    map-underscore-to-camel-case: true

Edit UserMapper mapping file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jt.mapper.UserMapper">
   
   <select id="findAll" resultType="User">
      select * from user
   </select>


   <!--Turn on hump mapping
      Business requirements:
         It is required to query the database, but the database fields are inconsistent with the attributes of the object,
      eg:
         user surface(field user_id,user_name,user_age......)
         User object(attribute userId,userName,userAge......)
      explain:
         The rule of hump mapping is introduced to solve the underline problem
      Execution sequence:
         obtain user_id~~~Remove the extra underline"_"Capital letters~~~~userId(Implement data mapping)
      matters needing attention:
         If a rule is used, it must meet the specification, otherwise it cannot be mapped to.
   -->
</mapper>

About AutoWired error reporting

Tags: Spring Boot

Posted by lostnucleus on Sat, 07 May 2022 06:01:37 +0300