Spring Boot separates the declaration log step into a reusable class

Above, in the basic use of Spring Boot logs to set the log level, we wrote a relatively basic log operation
, but it also raised a question.
Insert image description here
Can we not write this line of code?

Specifically, we don’t want every class that needs logging to declare one, which would look too unsightly.
Our simplest method is of course inheritance.

Let’s find a directory and create a class called BaseClass.
The reference code is as follows

package com.example.webdom.controller;

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

public class BaseClass {
    
    
    private Class<?> clazz;
    public static Logger log;

    public BaseClass(){
    
    
        clazz = this.getClass();
        log = LoggerFactory.getLogger(clazz);
    }
}

Insert image description here
Here we first define the log object and the object of the current class but do not assign values.

Then, after assigning the current class in the constructor, pass it to the log object.
In this way, whoever inherits our log set will achieve the effect of code reuse.

Then we will remove the code that originally declared the log in this class and inherit this general log class we wrote ourselves. After writing it,
Insert image description here
let’s test it
and then start the project.

Then we access this interface
Insert image description here
and we can see that everything is normal here.
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/132818828