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

<profile>
  <id>jdk-1.8</id>
  <activation>
    <activeByDefault>true</activeByDefault>
    <jdk>1.8</jdk>
  </activation>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
  </properties>
</profile>

(2) Importing spring boot-related dependencies

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

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

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

    public static void main(String[] args) {

        // Start Spring App
        SpringApplication.run(HelloWorldMainApplication.class,args);
    }
}

(4) Write related Controller, Service

@Controller
public class HelloController {

    @ResponseBody
    @RequestMapping("/hello")
    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().

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloTests {
    private MockMvc mvc;

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

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Hello World")));
    }
}

(7) Simplified deployment

·   <!-- This plugin packages an application into an executable jar Package;-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

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

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>

His parent project is
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-dependencies</artifactId>
  <version>1.5.9.RELEASE</version>
  <relativePath>../../spring-boot-dependencies</relativePath>
</parent>
He comes to really manage Spring Boot Apply all dependent versions within;

starter

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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
 */
@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) {

        // Start Spring App
        SpringApplication.run(HelloWorldMainApplication.class,args);
    }
}

@**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;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@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;

@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
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

server:
  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

server:
    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

friends:
		lastName: zhangsan
		age: 20

 

  • Array (List, Set):

Represent an element in an array with -value

pets:
 - cat
 - dog
 - pig

3. Profile Value Injection

(1) yml profile

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

(2)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;
 *
 */
@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 and write the configuration later.

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

(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

@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;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

(5)@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 enabled;
 *  @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;

@**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"
       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>

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
 *
 */
@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();
    }
}

4. Profile placeholder

(1) Random number

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

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

person.last-name=Zhang San${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

5,Profile

(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

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

(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

–file:./config/

–file:./

–classpath:/config/

–classpath:/

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
SpringFactoriesLoader.loadFactoryNames()
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();
		filter.setEncoding(this.properties.getCharset().name());
		filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
		filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
		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");

**Essence**

  • 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;

=========================
AUTO-CONFIGURATION REPORT
=========================


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)
-----------------

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

   AopAutoConfiguration:
      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

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
</dependency>

SpringBoot uses it for logging purposes;

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-logging</artifactId>
</dependency>

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?

@SuppressWarnings("rawtypes")
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:

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<exclusions>
		<exclusion>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
		</exclusion>
	</exclusions>
</dependency>

**==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

//Recorder
Logger logger = LoggerFactory.getLogger(getClass());
@Test
public void contextLoads() {
	//System.out.println();
	//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...")
}
logging.level.com.atguigu=trace


#logging.path=
# Generate the springboot.log log under the current project without specifying a path
# You can specify a complete path;
#logging.file=G:/springboot.log

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

# 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
</springProfile>
<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>
        <springProfile name="!dev">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ==== [%thread] ==== %-5level %logger{50} - %msg%n</pattern>
        </springProfile>
    </layout>
</appender>

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:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <artifactId>logback-classic</artifactId>
      <groupId>ch.qos.logback</groupId>
    </exclusion>
    <exclusion>
      <artifactId>log4j-over-slf4j</artifactId>
      <groupId>org.slf4j</groupId>
    </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
</dependency>

Switch to log4j2:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
         <exclusion>
             <artifactId>spring-boot-starter-logging</artifactId>
             <groupId>org.springframework.boot</groupId>
         </exclusion>
    </exclusions>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

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