Spring Boot development diary

Spring Boot log

1.SLF4j use

(1) How to use SLF4j in the system

In development, the call of logging method should not directly call the implementation class of log, but call the methods in the log abstraction layer. Import slf4j jars and logback implementation jars 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");

Each log implementation framework has its own configuration file. After using slf4j, the configuration file is still made into the configuration file of the log implementation framework

(2) How to unify all logs in the system to slf4j

(1) Exclude other log frames in the system first
(2) Replace the original log framework with an intermediate package
(3) We import slf4j other implementations

2. Log relationship

(1) The bottom layer of SpringBoot also uses slf4j+logback for logging
(2) SpringBoot also replaced other logs with slf4j
Note: if we want to introduce other frameworks, we must remove the default log dependency of this framework.
SpringBoot can automatically adapt all logs, and the bottom layer uses slf4j+logback to record logs. When introducing other frameworks, you only need to send the log framework that this framework depends on

3. Log usage

 * Recorder
Logger logger = LoggerFactory.getLogger(getClass());
void contextLoads() {
    //Log level
    //From low to high trace < debug < info < warn < error
    //You can adjust the log level of the output, and the log will only take effect at the higher level after this level
    logger.trace("This is trace journal...");
    logger.debug("This is debug journal...");
    //SpringBoot uses info level by default
    logger.info("This is debug journal...");
    logger.warn("This is warn journal...");
    logger.error("This is error journal...");

(1) Specify configuration

Just put each logging framework's own configuration file on the classpath, and SpringBoot will not use the default configuration
logback.xml: directly recognized by the logging framework
logback-spring.xml: the log framework does not directly load the log configuration items, but the log configuration is parsed by SpringBoot. You can use the advanced function Profile function of SpringBoot

<springProfile name="staging">
	You can specify that a certain configuration only takes effect in a certain environment

Introduction to boot web development

1. Use Spring Boot

(1) Create a SpringBoot application and select the required template
(2) SpringBoot has configured these scenarios by default. You only need to specify a small number of configurations in the configuration file to run
(3) Write business code

2. Automatic configuration principle

Detailed introduction of automatic configuration principle

3. Mapping rules for static resources

    prefix = "spring.resources",
    ignoreUnknownFields = false
public class ResourceProperties {

//You can set parameters related to resources, such as cache time
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
        CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
        if (!registry.hasMappingForPattern("/webjars/**")) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
        String staticPathPattern = this.mvcProperties.getStaticPathPattern();
        if (!registry.hasMappingForPattern(staticPathPattern)) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));

(1) All / webjars / * *, go to classpath:/META-INF/resources/webjars / to find resources. Webjars: introducing static resources in the form of jar package
webjars official website


<!-- introduce jquery-webjar -->

(2) "/ * *" access any resources of the current project (folder of static resources)

"/" //The root path of the current project

(3) Welcome page, all indx in the static resource folder HTML page, mapped by "/ * *"

//Configure the mapping of the welcome page
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
    WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    return welcomePageHandlerMapping;

(4) All * * / favicon ICO is found under the static resource file

Introduction to Thymeleaf

1. Template engine


2. Template engine idea (function)

Thymeleaf recommended by SpringBoot has simpler syntax and more powerful functions.

3. Import template engine


4.Thymeleaf usage & syntax

(1) Thymeleaf use

    prefix = "spring.thymeleaf"
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";

As long as the HTML page is placed in classpath:/templates /, thymeleaf can render automatically;

(2) Thymeleaf grammar

(1) Import the namespace of thymeleaf

<html lang="en" xmlns:th="http://www.thymeleaf.org">

(2) Grammar rules
Th: textchange the text content in the current element
Th can be used with any HTML attribute, such as th:href, to replace the value of the native attribute.

(3) Expression

Simple expressions:(Expression syntax)     
	Variable Expressions: ${...}: Obtain variable value; OGNL;      
		1),Get the properties and call methods of the object               
		2),Use built-in basic objects:               
		3),Some built-in tool objects;
	Selection Variable Expressions: *{...}: Select expressions: and ${}It is the same in function;      
	Supplement: Cooperation th:object="${session.user}";
	Selection Variable Expressions: *{...};
	Select expressions: and ${}It is the same in function;
	Supplement: Cooperation th:object="${session.user}";
	<div th:object="${session.user}">
		<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
		<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
		<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
	Message Expressions: #{...}:  Get international content
	Link URL Expressions: @{...}: definition URL;      
	Fragment Expressions: ~{...}: Fragment reference expression
	<div th:insert="~{commons :: main}">...</div>
	Text literals: 'one text' , 'Another one!' ,... 
	Number literals: 0 , 34 , 3.0 , 12.3 ,... 
	Boolean literals: true , false
	Null literal: null
	Literal tokens: one , sometext , main ,... 
Text operations:((text operation)
	String concatenation: +
	Literal substitutions: |The name is ${name}| 
Arithmetic operations:(Mathematical operation)
    Binary operators: + , ‐ , * , / , %
Boolean operations:(Boolean operation)
	Binary operators: and , or 
	Boolean negation (unary operator): ! , not
Comparisons and equality:(Comparison operation)     
	Comparators: > , < , >= , <= ( gt , lt , ge , le )     
	Equality operators: == , != ( eq , ne )
Conditional operators:Conditional operation (ternary operator)     
	If‐then: (if) ? (then)     
	If‐then‐else: (if) ? (then) : (else)     
	Default: (value) ?: (defaultvalue) 
Special tokens:     
	No‐Operation: _ 

Added by lessthanthree on Tue, 08 Feb 2022 05:46:32 +0200