Introduction to learning day01 springboot in microservice architecture

Basic concepts

  • Advantages of SpringBoot:
    • You can create independent Spring applications
    • SpringBoot embeds Tomcat,Jetty and Unsertow, and does not need to deploy war files
    • Get the starter through maven as needed
    • Auto configure Spring
    • Provide production ready functions, including indicators, health check and external configuration

SpringBoot parent project

  • Manage all dependent versions in the SpringBoot application, so that the version number does not need to be written by default when importing dependencies in the future, and the development version can be managed uniformly (the version number needs to be declared only for dependencies that are not managed in dependencies)


  • Spring boot starter: springboot scenario launcher
  • Spring boot starter Web: import the components that the web module depends on for normal operation
  • SpringBoot extracts all the functional scenarios and makes them into various starter starters, which only needs to be in the project POM These starter dependencies are introduced into XML, and all dependencies of related scenarios will be imported.


  • @SpringBootApplication: marked in the main configuration class of SpringBoot, SpringBoot will run the main method of this class to start the application of SpringBoot.
@SpringBootConfiguration 	//SpringBoot configuration class, similar to configuration file. Configuration classes are also components in containers. The label on the class indicates that it is a SpringBoot configuration class
@EnableAutoConfiguration	//Enable SpringBoot auto configuration
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
public @interface SpringBootApplication {
        annotation = EnableAutoConfiguration.class,
        attribute = "exclude"
    Class<?>[] exclude() default {};

        annotation = EnableAutoConfiguration.class,
        attribute = "excludeName"
    String[] excludeName() default {};

        annotation = ComponentScan.class,
        attribute = "basePackages"
    String[] scanBasePackages() default {};

        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    Class<?>[] scanBasePackageClasses() default {};
  • @SpringBootConfiguration: SpringBoot configuration class, similar to configuration file. Configuration classes are also components in containers. The label on the class indicates that it is a SpringBoot configuration class
@Configuration	// Indicates that this class is a Spring configuration class
public @interface SpringBootConfiguration {
		annotation = Configuration.class
	boolean proxyBeanMethods() default true;
@Component	// Indicates that this class is a component of Spring
public @interface Configuration {
		annotation = Component.class
	String value default "";
	boolean proxyBeanMethods() default true; 
  • @EnableAutoConfiguration: enable SpringBoot auto configuration
package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;

public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {};

    String[] excludeName() default {};

  • @AutoConfigurationPackage: the automatic configuration package is completed through @ Import({Registrar.class}). By checking the Registrar source code, it is found that all components in the package and all sub packages of the main configuration class, that is, the class marked by @ SpringBootApplication, are scanned into the Spring container
  • Among them, @ Import is the bottom annotation of Spring, which imports a component into the container, and the imported component is imported by registrar Class.
  • AutoConfigurationImportSelector: a selector for importing components. All components that need to be imported are returned in the form of full class names, so that the components will be added to the container
    • The automatic configuration class will be imported into the container: that is, all components of the scene will be imported into the container and configured This eliminates the need to manually write configurations and inject functional components
  • SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader):
    • From meta-inf / spring. Under the classpath Get the value specified by EnableAutoConfiguration from factories
  • Process summary:
    • SpringBoot starts from meta-inf / spring. In the classpath Get the value specified by EnableAutoConfiguration from factories
    • Import these values into the container as automatic configuration class, and the automatic configuration class will take effect for configuration.
  • < font color = Red > the overall integration solution and automatic configuration of J2EE are in spring-boot-autoconfigure-2.0.1 RELEASE. < / font > in jar

resources folder in SpringBoot project:

  • Static: save all static resources, such as js, css and images
  • templates: save all template pages. In SpringBoot, the default jar package uses embedded tomcat, and jsp pages are not supported by default. You can use template engines: freemaker, thymeleaf
  • application. Properties: the configuration file of the springboot application. You can modify some default settings

SpringBoot configuration

configuration file

SpringBoot uses a global configuration file with a fixed name:

  • application.yml
  • Function of configuration file: modify the default value of SpringBoot automatic configuration.


  • yml: (YAML Ain't Markup Language) data centric, more suitable for configuration files than json, xml, etc.
YAML basic syntax
  • key: value (indicates a pair of key value pairs. Value must be preceded by a space.)
  • Indent the space to indicate the hierarchical relationship. As long as it is a left aligned column of data, it is 1.1 of the same level Tab key is not allowed when indenting, only spaces are allowed 2 The number of indented spaces is not important, as long as the elements of the same level are aligned to the left
  • Attributes and values are case sensitive
  • Write value:
    • Literal: ordinary value (number, string, Boolean)
  • key: value: the literal quantity is written directly. Strings are not quoted by default.
  • Single quotation marks - escape characters are output as normal strings
  • Double quotation marks - escape characters are converted to format
  • Object, Map (attribute and value, key value pair):
    • Object or key: value
          lastName: Chova
          firstName: Vea

Inline writing:

friends: {lastName: Chova,firstName: Vea}
  • Array (List, Set)
    • Use the - value to represent the elements in the array
  - dog
  - cat
  - pig

Inline writing:

pets: [dog,cat,pig]

@Comparison between Value and @ ConfigurationProperties

@Value @ConfigurationProperties
function Specify the injection one by one on the attribute Properties in batch injection profile
Loose binding (loose syntax) I won't support it support
SpEL support I won't support it
JSR303 data verification I won't support it support
Complex type encapsulation I won't support it support
  • If we only need to obtain a certain value of the configuration file in a certain business logic, use < font color = Red > @ value < / font >
  • If the JavaBean needs to be mapped with the configuration file, use < font color = Red > @ configurationproperties < / font >

Configuration file injection value value verification (JSR303)

  • You must use @ ConfigurationProperties
  • JSR303 data verification: @ Validate-@Email

@PropertySource and @ ImportResource

  • @PropertySource: loads the specified configuration file
@PropertySource(value = {""})
  • @ImportResource: import the Spring configuration file to make the contents of the configuration file take effect
  • SpringBoot recommends adding components to the container: the method of < font color = Red > full annotation < / font > is recommended. 1 Configuration class - Spring configuration file 2 Use @ Bean to add components to the container in the configuration class

Profile placeholder

  • RandomValuePropertySource: random numbers can be used in the configuration file
  • Property configuration placeholder: 1 You can refer to the previously configured attributes in the configuration file (the priority previously configured can be used here) 2$ {app. Name: default} to specify the default value when the attribute value cannot be found


  • Multiple Profile files: 1 When writing the configuration file, the file name can be: application - {Profile} properties/yml 2. Application. Is used by default Configuration of properties
  • yml supports multiple document blocks
    • Dividing document blocks with "---"

Activate the specified Profile: 1 In the main configuration file application Specify activation in properties:

2. Command line activation: (Program arguments)

3. Virtual machine parameter activation: (VM options)

Configuration file loading location

  • SpringBoot startup will scan the application in the following location Properties or application The YML file is used as the default configuration file for SpringBoot
  1. file:./config/
  2. file:./
  3. classpath:/config
  4. classpath:/
  • All the above files will be loaded according to the priority from high to low, complementary configuration. High priority content overwrites low priority content.
  • You can configure * * -- spring config. Location * * to change the default configuration location: after the project is packaged, use the form of command line parameters to specify the new location of the configuration file when starting the project. The specified configuration file and the default loaded configuration file will work together to complement the configuration.

Loading order of external configuration

  • SpringBoot supports a variety of external configuration modes, with the following priorities: 1< Font color = Red > command line parameter < / font > (--, multiple commands are separated by spaces) 2 JNDI attribute from java:comp/env 3 Java system properties (System.getProperties()) 4 Operating system environment variable 5 Randomvaluepropertysource configured random* The attribute value is searched from the outside of the jar package to the inside of the jar package: priority loading with profile: 6< Font color = Red > Application - {profile} outside the jar package Properties / YML (with spring.profile) configuration file < / font > 7< Font color = Red > Application - {profile} inside the jar package Properties / YML (with spring.profile) configuration file < / font > and then load the configuration file without profile: 8< Font color = Red > Application - {profile} outside the jar package Properties / YML (without spring.profile) configuration file < / font > 9< Font color = Red > Application - {profile} inside the jar package Properties / YML (without spring.profile) configuration file < / font > 10@ @ propertysource on configuration annotation class 11 Via springapplication Setdefaultproperties specifies the default properties

Automatic configuration principle

  • When SpringBoot starts, the main configuration class is loaded and the automatic configuration function @ EnableAutoConfiguration is enabled
  • @EnableAutoConfiguration function: use EnableAutoConfigurationImportSelector to import components into the container. See the selectImports() method for specific implementation:
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);Get candidate configuration
SpringFactoriesLoader.loadFactoryNames();Scan all jar Package class path: META-INF/spring.factories. Package the contents of these scanned documents into properties Object, from properties Get from EnableAutoConfiguration.class(Class name)Class, and then add them to the container

Drop the class path to meta-inf / spring All EnableAutoConfiguration values configured in factories are added to the container.

  • Each automatic configuration class performs automatic configuration function.
@Configuration	// Indicates that this is a configuration class, similar to a configuration file, which can add components to the container
@EnableConfigurationProperties({HttpProperties.class})	// Enable the ConfigurationProperties function of the specified class (get the specified value from the configuration file and bind it with the properties of the bean)
@ConditionalOnWebApplication(	// Spring bottom @ conditional annotation, according to different conditions, if the specified conditions are met, the configuration in the whole configuration class will take effect (judge whether the current application is a web application)
   type = Type.SERVLET
@ConditionalOnClass({CharacterEncodingFilter.class})	// Determine whether the current project has this class. Characterencoding filter: a filter for garbled code resolution in spring MVC
@ConditionalOnProperty(	// Determine whether a configuration exists in the file
   prefix = "spring.http.encoding",
   value = {"enabled"},
   matchIfMissing = true	// Even if spring is not configured in the configuration file http. encoding. Enable = true, which is also effective by default
public class HttpEncodingAutoConfiguration {

According to different current conditions, to determine whether the configuration class is effective, various components will be added to the container through @ Bean. The values of these components need to be obtained from properties, and each property in properties is bound to the configuration file< Font color = Red > notes: < / font >

  • @Conditional derived annotation (from Spring underlying annotation @ conditional) 1 Function: only when the conditions specified by @ conditional are true can components be added to the container and all contents in the configuration take effect. 2. The automatic configuration class will take effect only under certain conditions: in the configuration file

The automatic configuration report can be printed on the console, and you can view which automatic configurations are effective and which automatic configurations are not effective.


  • SpringBoot boot will load a large number of auto configuration classes.
  • Judge whether the auto configuration class written by SpringBoot by default has the required functions.
  • Judge whether the automatic configuration class configures the required components. If not, you need to configure them yourself.
  • When adding components to the automatic configuration class in the container, the properties will be obtained from the properties, and the values of these properties will be specified in the configuration file.
  • xxAutoConfiguration: auto configuration class, add components to the container = = = xxProperties: encapsulate the relevant properties in the configuration file and bind to the configuration file

Posted by tdelobe on Tue, 19 Apr 2022 11:34:12 +0930