Spring Boot: Introduction

1. What is Spring Boot

Spring Boot is a new framework provided by the Pivotal team and is designed to simplify the initial build and development of new Spring applications.The framework is configured in a specific way so that developers no longer need to define a template configuration.In my words, Spring Boot is not really a new framework. It configures many frameworks by default, just like Maven integrates all Jar packages and Spring Boot integrates all frameworks.

1. Simplify a framework for spring application development;

2. A big integration of spring technology stack;

3. One-stop solution developed by J2EE;

2. What are the benefits of using Spring Boot

It's simple, fast and convenient!

What do we usually do if we need to build a Spring Web project?

  • Configure web.xml, load spring and springMVC
  • Configure database connections, configure spring transactions
  • Configure loading profile read, open annotations
  • configure log files
  • ...
  • Deploy Tomcat debugging after configuration is complete
  • ...

Microservices are very popular right now, if I just need to send an email for this project, if my project is just producing a credit; I need to do this all over again!

But what if you use Spring Boot?
Simply, I can quickly and easily set up a set of Web projects or build a microservice with just a few configurations!

How cool it is to use Spring Boot, as shown in the figure below

3. Simple examples

1. IDEA Construction Project

(1) Select File -> New -> Project...Pop up a box for a new project

(2) Select Spring Initializr, Next will also appear above similar configuration interface, Idea helps us to integrate

(3) After filling in the relevant content, click Next to select the dependent package, click Next, and finally confirm that the information is correct click Finish.

2. Introduction to project structure

As shown in the figure above, the Spring Boot infrastructure consists of three files:

  • src/main/java program development and main program entry
  • src/main/resources configuration file
  • src/test/java test program

3. Implement Spring Boot HelloWorld

(1) maven configuration

Add profiles tag to maven's settings.xml configuration file


(2) Importing spring boot-related dependencies


(3) Write a main program; Start Spring Boot application

 *  @SpringBootApplication To label a main program class, this is a Spring Boot application
public class HelloWorldMainApplication {

    public static void main(String[] args) {

        // Start Spring App

(4) Write related Controller, Service

public class HelloController {

    public String hello(){
        return "Hello World!";

@RestController means that the methods inside the Controller are all output in json format and there is no need to write any more jackjson configurations.

(5) Run main program tests

(6) How to do unit testing

Open the test entry under src/test/to write a simple http request to test; use mockmvc to do this, and print out the execution results using MockMvc ResultHandlers.print().

public class HelloTests {
    private MockMvc mvc;

    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();

    public void getHello() throws Exception {
                .andExpect(content().string(equalTo("Hello World")));

(7) Simplified deployment

·   <!-- This plugin packages an application into an executable jar Package;-->

Make this application a jar package and execute it directly using java-jar commands

4. Hello World Exploration

(1) POM files

There are two modules in the pom.xml file by default:

The core modules of spring-boot-starter, including automatic configuration support, logging, and YAML, can be removed if the spring-boot-starter-web module is introduced, as spring-boot-starter-web automatically relies on spring-boot-starter.

The spring-boot-starter-test test module, including JUnit, Hamcrest, Mockito.

Parent Project


His parent project is
He comes to really manage Spring Boot Apply all dependent versions within;



spring-boot-starter: spring-boot scene launcher; helps us import the components on which the web module depends to function properly;

Spring Boot pulls out all the feature scenarios and makes them starters one by one, and all the dependencies that need to be introduced into the project for these starter-related scenarios are imported.The launcher that imports any scene with what functionality you want.

(2) Main program class, main entry class

 *  @SpringBootApplication To label a main program class, this is a Spring Boot application
public class HelloWorldMainApplication {

    public static void main(String[] args) {

        // Start Spring App

@**SpringBootApplication**:: The Spring Boot application label indicates in a class that this class is the main configuration class for SpringBoot, and SpringBoot should run the main method of this class to start the SpringBoot application;

@ComponentScan(excludeFilters = {
      @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
      @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

@**SpringBootConfiguration**: Configuration class for Spring Boot;

Labeled on a class means that this is a configuration class for Spring Boot;

@**Configuration**: Label this comment on the configuration class;

Configuration class----- configuration file; configuration class is also a component of the container; @Component

@**EnableAutoConfiguration**: Turn on auto-configuration function;

What we needed to configure before, Spring Boot helps us configure it automatically; @**EnableAutoConfiguration** tells SpringBoot to turn on auto-configuration; this will make the auto-configuration work;

public @interface EnableAutoConfiguration {

@**AutoConfiguration Package**: AutoConfiguration Package

​        @**Import**(AutoConfigurationPackages.Registrar.class):

(Spring's underlying comment @Import imports a component into the container; the imported component is AutoConfiguration Packages.Registrar.class;

==Scan the package in which the main configuration class (@SpringBootApplication labeled class) resides and all components in all subpackages below to the Spring container;==

​    @**Import**(EnableAutoConfigurationImportSelector.class);

Import components into containers?

** EnableAutoConfiguration ImportSelector**: Selectors for which components to import;

Return all components that need to be imported as full class names; these components are added to the container;

(xxxAutoConfiguration) will import a large number of AutoConfiguration classes into the container; that is, all the components needed to import this scene into the container and configure them; (AutoConfiguration Class)! (images/Sogou screenshot 20180129224104.png)

With automatic configuration classes, we avoid writing configuration injection function components manually, etc.

​        SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader);

==Spring Boot gets the values specified by EnableAutoConfiguration from META-INF/spring.factories in the class path at startup, imports them into the container as auto-configuration classes, and the auto-configuration classes will take effect to help us do the auto-configuration work; ==What we needed to configure before, the auto-configuration classes will help us;

J2EE's integrated solution and automatic configuration are both spring-boot-autoconfigure-1.5.9.RELEASE.jar;

3. Profile

1. Profile introduction

SpringBoot uses a global profile with a fixed profile name.

  • application.properties
  • 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 **xxxx.xml**files are used;

YAML:** Data-centric** is better for configuration files than json, xml, etc.

YAML: Configuration example

  port: 8081

2. YAML syntax:

(1) Basic grammar

k:(space) v: represents a pair of key-value pairs (spaces must have);

Controls hierarchical relationships by indentation of **spaces**; as long as a left-aligned column of data is at the same level

    port: 8081
    path: /hello

Attributes and values are also case sensitive;

(2) Writing of values

  • Literal: Normal value (number, string, Boolean)

k: v: write literally directly;

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

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

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

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

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

  • Object, Map (attributes and values) (key-value pairs):

k: v: Write the relationship between the object's properties and values on the next line; note the indentation

​        Object or k: v Ways

		lastName: zhangsan
		age: 20


  • Array (List, Set):

Represent an element in an array with -value

 - cat
 - dog
 - pig

3. Profile Value Injection

(1) yml profile

    lastName: hello
    age: 18
    boss: false
    birth: 2017/12/12
    maps: {k1: v1,k2: 12}
      - lisi
      - zhaoliu
      name: puppy
      age: 12


 * 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")
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 and write the configuration later.

<!--Import the profile processor and the profile will be prompted to bind-->

(3) @Value get value and @ConfigurationProperties get value comparison

Configuration file yml 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.
(4) Configuration File Injection Value Data Check

@ConfigurationProperties(prefix = "person")
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
    private String lastName;
    private Integer age;
    private Boolean boss;

    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;


@**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 enabled;
 *  @ConfigurationProperties(prefix = "person")Get the value from the global configuration file by default;
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
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
    private String lastName;
    private Integer age;
    private Boolean boss;

@**ImportResource**: Import Spring's profile to make the contents of the profile effective;

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

To make Spring's profile valid, load it; @**ImportResource** is labeled on a configuration class

@ImportResource(locations = {"classpath:beans.xml"})
Import Spring's profile to make it work

Don't write Spring's profile

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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>

SpringBoot recommends adding components to containers; full annotation is recommended

  • Configuration Class**@Configuration**---->Spring Configuration File
  • 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
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
    public HelloService helloService02(){
        System.out.println("Configuration Class@Bean Add Components to Container...");
        return new HelloService();

4. Profile placeholder

(1) Random number


(2) The placeholder gets the previously configured value, if not available: Specify the default value

person.last-name=Zhang San${random.uuid}


(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) yml supports multiple document block methods

  port: 8081
    active: prod

  port: 8083
  profiles: dev


  port: 8084
  profiles: prod  #Specify which environment to belong to

(3) Activate the specified profile

  • Specify spring.profiles.active=dev in the configuration file
  • Command line:

​        java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;

You can configure incoming command line parameters directly when testing

  • Virtual machine parameters;

​        -Dspring.profiles.active=dev

6. Configuration file load location

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





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

SpringBoot loads the main profile from all four locations; **Complementary Configuration**;

==We can also change the default profile 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 default loaded configuration files work together to form complementary configurations;**

java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties
7. Loading order of external configuration

**==SpringBoot can also load configurations from the following locations; from high to low priority; high priority configurations override low priority configurations, and all configurations form complementary configurations==**

**1, Command Line Parameters**

All configurations can be specified on the command line

java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087  --server.context-path=/abc

Multiple configurations separated by spaces; --Configuration item = value

2. JNDI properties from java:comp/env

3. Java System Properties (System.getProperties())

4. Operating system environment variables

5. RandomValuePropertySource configuration random. * property value

==** Searched from outside the jar package to inside the jar package; **==

==**Preferred load with profile**==

**6. application-{profile}.properties or application.yml (with spring.profile) configuration file outside the jar package**

**7. application-{profile}.properties or application.yml (with spring.profile) configuration file inside the jar package**

==** Load again without profile**==

**8, application.properties or application.yml (without spring.profile) configuration file outside the jar package**

**9, application.properties or application.yml (without spring.profile) configuration file inside the jar package**

10, @PropertySource on @Configuration annotation class

11. Default properties specified by SpringApplication.setDefaultProperties

All supported configuration loading sources;

[Refer to official documents]

8. Principle of Automatic Configuration

What exactly can a profile write?How do you write it?Automatic configuration principle;

[Attribute reference that profile can configure]

(1) SpringBoot starts with the main configuration class loaded and the auto-configuration function turned on ==@EnableAutoConfiguration==

(2)@EnableAutoConfiguration effect:

  • Import some components into the container using EnableAutoConfiguration ImportSelector?
  • You can view the contents of the selectImports() method;
  • List <String> configurations = getCandidateConfigurations (annotation Metadata,... attributes); get candidate configurations
Scan all jar package class paths for META-INF/spring.factories
Wrap the contents of the scanned files into properties objects
Get the values for the EnableAutoConfiguration.class class class (class name) from properties and add them to the container

Add all EnableAutoConfiguration values configured in META-INF/spring.factories under the class path to the container;

Each of these xxxAutoConfiguration classes is a component of the container and is added to the container; they are used for automatic configuration;

(3) Auto-configuration function for each auto-configuration class;

(4) Using ** Http Encoding AutoConfiguration ** as an example to explain the principle of automatic configuration:

@Configuration //Indicates that this is a configuration class and that components can be added to containers just like previously written configuration files
@EnableConfigurationProperties(HttpEncodingProperties.class)//Starts the Configuration Properties function for the specified class; binds the corresponding values in the configuration file to HttpEncoding Properties; and adds HttpEncoding Properties to the IOC container
@ConditionalOnWebApplication //spring underlying @Conditional annotation, depending on the conditions specified, the configuration within the entire configuration class will fail; determine if the current application is a web class, and if so, the current configuration class will take effect
@ConditionalOnClass(CharacterEncodingFilter.class) //Determine if the current project has this type of CharacterEncodingFilter;
SpringMVC Filter for scrambling resolution;
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)  //Determine if a configuration spring.http.encoding.enabled exists in the configuration file; if it does not, the determination is valid 
//Even if pring.http.encoding.enabled=true is not configured in our configuration file, it will take effect by default;
public class HttpEncodingAutoConfiguration {
    //Mapped to springboot configuration file
    private final HttpEncodingProperties properties;
    //With only one parameter constructor, the value of the parameter is taken from the container
    public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
		this.properties = properties;
    @Bean //Add a component to the container whose values need to be returned from properties
    @ConditionalOnEncodingFilter(CharacterEncodingFilter.class)//Judging that the container does not have this component?
    public CharacterEncodingFilter characterEncodingFilter(){
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
		return filter;

Determine whether this configuration class is valid based on the current conditions?

But this configuration class takes effect; this configuration class adds components to the container; the properties of these components are derived from the corresponding properties class, and each of these properties is bound to the configuration file;

(5) All the properties that can be configured in the configuration file are encapsulated in the xxxxProperties class; the property class corresponding to a function can be referenced by what the configuration file can configure.

@ConfigurationProperties(prefix = "spring.http.encoding")  //Get the specified value from the configuration file and the properties of the bean to bind
public class HttpEncodingProperties {

   public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");


  • springboot startup loads a large number of auto-configuration classes
  • Let's see if the features we need have springboot auto-configuration classes written by default.
  • Let's look again at what components are configured in this auto-configuration class (as long as we have the components we need, we don't need to configure any more)
  • When you add components to an auto-configuration class in a container, you get some properties from the properties class and we can specify their values in the configuration file.

xxxxAutoConfigurartion: Auto-configure classes;

Add Components to Containers

xxxxProperties: Encapsulates related properties in the configuration file;

9. Details

@Conditional Derived Annotation (Native @Conditional Role of Spring Annotation Edition)

Role: The conditions specified by @Conditional must be met before components can be added to the container for all content in the configuration to take effect.

@Conditional Extension Annotation Role (determine whether the current specified condition is met)
@ConditionalOnJava Does the java version of the system meet the requirements
@ConditionalOnBean       The specified Bean exists in the container;
@ConditionalOnMissingBean      The specified Bean does not exist in the container;
@ConditionalOnExpression   Satisfies SpEL expression specification
@ConditionalOnClass  There are specified classes in the system
@ConditionalOnMissingClass There is no specified class in the system
@ConditionalOnSingleCandidate There is only one specified Bean in the container, or this Bean is the preferred Bean
@ConditionalOnProperty     Does the property specified in the system have a specified value
@ConditionalOnResource     Is there a specified resource file under the class path
@ConditionalOnWebApplication Currently a web environment
@ConditionalOnNotWebApplication Currently not a web environment
@ConditionalOnJndi Specified item exists in JNDI

Automatic configuration classes must be in effect under certain conditions;

** We can enable the debug=true property to let the console print the auto-configuration report==** so that we can easily know which auto-configuration classes are in effect;


Positive matches:(Automatic Configuration Class Enabled)

   DispatcherServletAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
      - @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)
Negative matches:(No startup, no matching successful autoconfiguration class)

      Did not match:
         - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)

      Did not match:
         - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', '3. Quick Start

IV. Logs

1. SpringBoot uses SLF4j and logback

In future development, calls to logging methods should not directly call the implementation class of logging, but instead call the methods in the log abstraction layer.

Import the implementation jar of slf4j and logback into the system.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
    logger.info("Hello World");

2. Legacy Issues

a(slf4j+logback): Spring(commons-logging),Hibernate(jboss-logging),MyBatis,xxxx

Unified logging, even if other frameworks work with me to unify slf4j output?

How can I unify all logs in my system to slf4j?

(1) Exclude other log frameworks from the system first

(2) Replace the old log framework with the intermediate package

(3) Import other implementations of slf4j

3. SpringBoot log relationships


SpringBoot uses it for logging purposes;


4. Bottom Dependency

(1) The Spring Boot underlying layer also uses slf4j+logback for logging

(2) Spring Boot has also replaced all other logs with slf4j;

(3) Intermediate replacement package?

public abstract class LogFactory {

    static String UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J = "http://www.slf4j.org/codes.html#unsupported_operation_in_jcl_over_slf4j";

    static LogFactory logFactory = new SLF4JLogFactory();

(4) If we want to introduce another framework?Do you have to remove the default log dependencies for this framework?

commons-logging for the Spring framework:


**==SpringBoot automatically adapts to all logs, and the underlying uses slf4j+logback to log. When introducing other frameworks, just exclude the log frameworks that this framework depends on;**

5. Log Use

(1) Default configuration

Spring Boot helps us configure our logs by default

Logger logger = LoggerFactory.getLogger(getClass());
public void contextLoads() {
	//Level of log;
	//From low to high trace<debug<info<warn<error
	//You can adjust the log level of the output; the log will only take effect at this level and at a later level
	logger.trace("This is trace Journal...");
	logger.debug("This is debug Journal...");
	//SpringBoot defaults to info level for us, SpringBoot default level for no specified level; root level
	logger.info("This is info Journal...");
	logger.warn("This is warn Journal...");
	logger.error("This is error Journal...")

# Generate the springboot.log log under the current project without specifying a path
# You can specify a complete path;

# Create the spring folder and the log folder inside the current disk's root path; use spring.log as the default file

# Format of log output in console
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
# Specify the format of log output in the file
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} ==== %msg%n

(2) Specify configuration

Put each logging framework's own configuration file under the class path; SpringBoot does not use its default configuration.

logback.xml: directly identified by the log framework;

logback-spring.xml: The log framework does not directly load the log's configuration items, it is configured by SpringBoot to parse the log, and it can use SpringBoot's advanced Profile functionality;

<springProfile name="staging">
    <!-- configuration to be enabled when the "staging" profile is active -->
  	You can specify that a configuration only works in a certain environment
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        Log output format:
			%d represents the date and time,
			%threads denotes the thread name,
			%-5level: level shows 5 characters width from left
			%logger{50} means that the logger name has a maximum of 50 characters, otherwise it is split by a period. 
			%msg: Log message,
			%n is a line break
    <layout class="ch.qos.logback.classic.PatternLayout">
        <springProfile name="dev">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ----> [%thread] ---> %-5level %logger{50} - %msg%n</pattern>
        <springProfile name="!dev">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ==== [%thread] ==== %-5level %logger{50} - %msg%n</pattern>

If you use logback.xml as the log configuration file and also use the profile function, the following errors will occur:

no applicable action for [springProfile]

6. Switch Log Framework

The log adapter of slf4j can be used for related switching.

How slf4j+log4j works:



Switch to log4j2:



V. Summary

Using Spring Boot makes it easy and quick to build projects without worrying about compatibility between frameworks, versions, etc. We want to use anything, just add a configuration, so using Spring Boot is ideal for building micro services.

Tags: Programming Spring SpringBoot Maven xml

Posted on Sun, 02 Feb 2020 18:01:34 -0800 by vanlier