Quickly build a spring entry case and integrate logs

Table of contents

Environmental requirements

building blocks

program development

Introduce dependencies

create java class

Create configuration file

Create a test class test

run test program

program analysis

Configure and enable Log4j2 log framework in spring

 Log4j2 logging overview

Introduce Log4j2 dependency

Add log configuration file

test

 usage log


Environmental requirements

  • JDK: Java17+ (Spring6 requires the minimum version of JDK to be Java17)

  • Maven:3.6+

  • Spring:6.0.2

building blocks

(1) Build the parent module spring6

In idea, click File -> New -> Project -> New Project

Click "Create"

delete the src directory

(2) Build the submodule spring6-first

 

 Click Create to finish

program development

Introduce dependencies

Add dependencies:

<dependencies>
    <!--spring context依赖-->
    <!--当你引入Spring Context依赖之后,表示将Spring的基础依赖引入了-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.0.2</version>
    </dependency>

    <!--junit5测试-->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.3.1</version>
    </dependency>
</dependencies>

View dependencies:

create java class

public class HelloWorld {
    
    public void sayHello(){
        System.out.println("helloworld");
    }
}

Create configuration file

Create a Spring configuration file bean.xml in the resources directory (the name of the configuration file can be named freely, such as: springs.xm)

<?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">

    <!--
    配置HelloWorld所对应的bean,即将HelloWorld的对象交给Spring的IOC容器管理
    通过bean标签配置IOC容器所管理的bean
    属性:
        id:设置bean的唯一标识
        class:设置bean所对应类型的全类名
	-->
    <bean id="helloWorld" class="com.atguigu.spring6.bean.HelloWorld"></bean>
    
</beans>

Create a test class test

public class HelloWorldTest {

    @Test
    public void testHelloWorld(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        HelloWorld helloworld = (HelloWorld) ac.getBean("helloWorld");
        helloworld.sayHello();
    }
}

run test program

program analysis

1. How does the bottom layer create objects? Is the no-argument construction method called through the reflection mechanism?

Modify the HelloWorld class:

public class HelloWorld {

    public HelloWorld() {
        System.out.println("无参数构造方法执行");
    }

    public void sayHello(){
        System.out.println("helloworld");
    }
}

 2. How does Spring create objects? What is the principle?

// dom4j解析beans.xml文件,从中获取class属性值,类的全类名
 // 通过反射机制调用无参数构造方法创建对象
 Class clazz = Class.forName("com.atguigu.spring6.bean.HelloWorld");
 //Object obj = clazz.newInstance();
 Object object = clazz.getDeclaredConstructor().newInstance();

3. What kind of data structure is the created object stored in?

The bean object is finally stored in the spring container. At the bottom of the spring source code is a map collection. The map storing the bean is in the DefaultListableBeanFactory class:

private final Map<String, BeanDefinition> beanDefinitionMap =
             new ConcurrentHashMap<>(256);

When the Spring container loads the Bean class, it will store the description information of this class in the beanDefinitionMap in the form of the package name plus the class name, Map<String,BeanDefinition>, where String is the Key, and the default is the first letter of the class name in lowercase, BeanDefinition , which stores the definition (descriptive information) of the class, we usually call the BeanDefinition interface as: the definition object of the bean.  

Configure and enable Log4j2 log framework in spring

 Log4j2 logging overview

In project development, logs are very important. Whether it is recording the running status or locating online problems, it is inseparable from the analysis of logs. The log records the time, location, status and other related information of the system behavior, which can help us understand and monitor the system status, remind us to deal with it in time when an error occurs or is close to a certain dangerous state, and at the same time, it can help us when the system has problems. Quickly locate, diagnose and solve problems.

Apache Log4j2 is an open source logging component that is widely used. In the project, it replaces print statements such as System.out with ease of use and convenience. It is the most popular log input tool under JAVA.

Log4j2 is mainly composed of several important components:

(1) The priority of log information , the priority of log information from high to low is TRACE < DEBUG < INFO < WARN < ERROR < FATAL

  • TRACE: Tracking, which is the lowest log level, is equivalent to the execution of the tracking program
  • DEBUG: Debugging, generally in development, set it to the lowest log level
  • INFO: information, output important information, used more
  • WARN: warning, output warning information ERROR: error, output error information FATAL: serious error

These levels are used to specify the importance of this log information; the higher level will automatically shield the lower level logs, that is, if the WARN log is set, the INFO and DEBUG log level logs will not be displayed

(2) The output destination of the log information , the output destination of the log information specifies whether the log will be printed to the console or to a file ;

(3) The output format of the log information , and the output format controls the display content of the log information.

Introduce Log4j2 dependency

<!--log4j2的依赖-->
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.19.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j2-impl</artifactId>
    <version>2.19.0</version>
</dependency>

Add log configuration file

Provide the log4j2.xml configuration file under the root path of the class (the file name is fixed as: log4j2.xml, and the file must be placed under the root path of the class.)

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <loggers>
        <!--
            level指定日志级别,从低到高的优先级:
                TRACE < DEBUG < INFO < WARN < ERROR < FATAL
                trace:追踪,是最低的日志级别,相当于追踪程序的执行
                debug:调试,一般在开发中,都将其设置为最低的日志级别
                info:信息,输出重要的信息,使用较多
                warn:警告,输出警告的信息
                error:错误,输出错误信息
                fatal:严重错误
        -->
        <root level="DEBUG">
            <appender-ref ref="spring6log"/>
            <appender-ref ref="RollingFile"/>
            <appender-ref ref="log"/>
        </root>
    </loggers>

    <appenders>
        <!--输出日志信息到控制台-->
        <console name="spring6log" target="SYSTEM_OUT">
            <!--控制日志输出的格式-->
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss SSS} [%t] %-3level %logger{1024} - %msg%n"/>
        </console>

        <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,适合临时测试用-->
        <File name="log" fileName="d:/spring6_log/test.log" append="false">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>

        <!-- 这个会打印出所有的信息,
            每次大小超过size,
            则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,
            作为存档-->
        <RollingFile name="RollingFile" fileName="d:/spring6_log/app.log"
                     filePattern="log/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
            <SizeBasedTriggeringPolicy size="50MB"/>
            <!-- DefaultRolloverStrategy属性如不设置,
            则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
    </appenders>
</configuration>

The project directory at this time is:

test

 usage log

public class HelloWorldTest {

    private Logger logger = LoggerFactory.getLogger(HelloWorldTest.class);

    @Test
    public void testHelloWorld(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        HelloWorld helloworld = (HelloWorld) ac.getBean("helloWorld");
        helloworld.sayHello();
        logger.info("执行成功");
    }
}

Guess you like

Origin blog.csdn.net/m0_62436868/article/details/130517143