发布于2020-11-19 20:49 阅读(1499) 评论(0) 点赞(9) 收藏(5)
1、实现功能结果如下图所示,用红框框住的就是实现的打印功能,而下边带?号的是原始的:
2、具体springboot+mybatis项目的搭建请看:spring-boot+mybatis搭建一个后端restfull服务:https://blog.csdn.net/sunxiaoju/article/details/109607322,此文就是在此基础上延伸出来的。
3、要实现此功能需要加入如下依赖:
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.4.0</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.7.30</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.7.30</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-log4j2</artifactId>
- </dependency>
3、将spring-boot-starter-logging从spring-boot-starter-web中排除,如:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-logging</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
4、将原来的mybatis-spring-boot-starter去掉,最后pom.xml文件为:
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>com.best</groupId>
- <artifactId>spring-boot-mybatis</artifactId>
- <version>1.0-SNAPSHOT</version>
-
- <properties>
- <java.version>1.8</java.version>
- <fastjson.version>1.2.74</fastjson.version>
- <spring.version>5.3.5.RELEASE</spring.version>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- </properties>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.3.5.RELEASE</version>
- </parent>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-logging</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-log4j2</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-jdbc</artifactId>
- <exclusions>
- <!-- 排除 tomcat-jdbc 以使用 HikariCP -->
- <exclusion>
- <groupId>org.apache.tomcat</groupId>
- <artifactId>tomcat-jdbc</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>2.1.3</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>8.0.22</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.2.1</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>${fastjson.version}</version>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <version>1.18.10</version>
- </dependency>
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.4.0</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.7.30</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.7.30</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.8.0</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- </plugin>
- </plugins>
- <resources>
- <resource>
- <directory>src/main/java</directory>
- <includes>
- <include>**/dao/*Mapper.xml</include>
- </includes>
- </resource>
- </resources>
- </build>
- </project>
5、既然是打印日志,那么肯定需要日志框架,这里使用的是log4j2,那么就需要再resources中新建一个log4j2.xml文件,文件内容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
- <!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
- <!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
- <configuration status="WARN" monitorInterval="30">
- <properties>
- <property name="LOG_HOME">../../../../build/logs</property>
- </properties>
- <!-- 先定义所有的appender -->
- <appenders>
- <!-- 这个输出控制台的配置 -->
- <Console name="Console" target="SYSTEM_OUT">
- <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
- <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
- <!-- 这个都知道是输出日志的格式 -->
- <PatternLayout charset="UTF-8" pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
- </Console>
-
- <!-- 文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
- <!-- append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
- <RollingFile name="DaoFileTrace" fileName="${LOG_HOME}/test.log"
- filePattern="${LOG_HOME}/$${date:yyyy-MM}/DaoFileTrace-%d{yyyy-MM-dd}-%i.log">
- <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
- <PatternLayout>
- <MarkerPatternSelector defaultPattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n">
- <PatternMatch key="spark" pattern="%m%n"/>
- </MarkerPatternSelector>
- </PatternLayout>
- <Policies>
- <TimeBasedTriggeringPolicy/>
- <SizeBasedTriggeringPolicy size="100 MB"/>
- </Policies>
- </RollingFile>
-
-
- <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
- <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
- filePattern="${LOG_HOME}/${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
- <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
- <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
- <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
- <Policies>
- <TimeBasedTriggeringPolicy/>
- <SizeBasedTriggeringPolicy size="100 MB"/>
- </Policies>
- </RollingFile>
-
- <RollingFile name="RollingFileWarn" fileName="${LOG_HOME}/warn.log"
- filePattern="${LOG_HOME}/${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
- <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
- <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
- <Policies>
- <TimeBasedTriggeringPolicy/>
- <SizeBasedTriggeringPolicy size="100 MB"/>
- </Policies>
- <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
- <DefaultRolloverStrategy max="20"/>
- </RollingFile>
-
- <RollingFile name="RollingFileError" fileName="${LOG_HOME}/error.log"
- filePattern="${LOG_HOME}/${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
- <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
- <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
- <Policies>
- <TimeBasedTriggeringPolicy/>
- <SizeBasedTriggeringPolicy size="100 MB"/>
- </Policies>
- </RollingFile>
-
- </appenders>
-
- <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
- <loggers>
- <!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
- <logger name="org.springframework" level="INFO"></logger>
- <logger name="com.alibaba.druid.*" level="INFO" additivity="false">
- <AppenderRef ref="Console"/>
- </logger>
- <logger name="org.mybatis" level="INFO" additivity="false">
- <AppenderRef ref="Console" />
- <AppenderRef ref="DaoFileTrace" />
- </logger>
-
-
- <logger name="com.best.common.sqllog" level="DEBUG" additivity="false">
- <AppenderRef ref="Console" />
- <AppenderRef ref="DaoFileTrace" />
- </logger>
-
- <logger name="org.apache.ibatis.logging" level="INFO" additivity="false">
- <AppenderRef ref="Console" />
- <AppenderRef ref="DaoFileTrace" />
- </logger>
-
- <root level="all">
- <appender-ref ref="Console"/>
- <appender-ref ref="RollingFileInfo"/>
- <appender-ref ref="RollingFileWarn"/>
- <appender-ref ref="RollingFileError"/>
- </root>
- </loggers>
- </configuration>
6、在添加完log4j2.xml文件后,就需要让springboot程序可以加载该配置文件,那么只需要再application.yml中加入:
- logging:
- config: classpath:log4j2.xml
如下图所示:
7、经过以上配置,在springboot中就可以使用log4j2框架来打印日志了。
8、开始创建拦截器,创建自定义拦截器必须实现Interceptor接口,那么我们新建一个SqlLoggerInterceptor类并实现Interceptor接口,并且通过@Intercepts和@Signature注解来配置拦截的方法和对象,这里我们拦截的是Executor,也就是mybatis具体执行sql语句的对象,而Executor对象中有如下方法:
- public interface Executor {
- ResultHandler NO_RESULT_HANDLER = null;
- int update(MappedStatement var1, Object var2) throws SQLException;
- <E> List<E> query(MappedStatement var1, Object var2, RowBounds var3, ResultHandler var4, CacheKey var5, BoundSql var6) throws SQLException;
- <E> List<E> query(MappedStatement var1, Object var2, RowBounds var3, ResultHandler var4) throws SQLException;
- <E> Cursor<E> queryCursor(MappedStatement var1, Object var2, RowBounds var3) throws SQLException;
- List<BatchResult> flushStatements() throws SQLException;
- void commit(boolean var1) throws SQLException;
- void rollback(boolean var1) throws SQLException;
- CacheKey createCacheKey(MappedStatement var1, Object var2, RowBounds var3, BoundSql var4);
- boolean isCached(MappedStatement var1, CacheKey var2);
- void clearLocalCache();
- void deferLoad(MappedStatement var1, MetaObject var2, String var3, CacheKey var4, Class<?> var5);
- Transaction getTransaction();
- void close(boolean var1);
- boolean isClosed();
- void setExecutorWrapper(Executor var1);
- }
不过我们经常用到的就只有update和两个query,因此在@Intercepts内写上3个Signature,如:
- @Intercepts({
- //type指定代理的是那个对象,method指定代理Executor中的那个方法,args指定Executor中的query方法都有哪些参数对象
- //由于Executor中有两个query,因此需要两个@Signature
- @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),//需要代理的对象和方法
- @Signature(type = Executor.class,method = "query",args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
- @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class })//需要代理的对象和方法
- })
由此可以看出update、query、query中的args中的对象是和Executor中的update、query、query方法中的参数是一一对应的,
9、实现Interceptor接口中的方法,主要有三个方法分别是plugin、setProperties、intercept,而我们主要做的就是intercept方法,plugin方法一般固定即可,setProperties是在外部传近来的值,如:
- @Override
- public Object plugin(Object target) {
- return Plugin.wrap(target, this);
- }
- @Override
- public void setProperties(Properties properties) {
- System.out.println(properties);
- }
10、最后在intercept填写拦截后要进行的处理逻辑,代码如下:
- package com.best.common.sqllog;
-
- import org.apache.ibatis.cache.CacheKey;
- import org.apache.ibatis.executor.Executor;
- import org.apache.ibatis.mapping.BoundSql;
- import org.apache.ibatis.mapping.MappedStatement;
- import org.apache.ibatis.mapping.ParameterMapping;
- import org.apache.ibatis.plugin.*;
- import org.apache.ibatis.reflection.MetaObject;
- import org.apache.ibatis.session.Configuration;
- import org.apache.ibatis.session.ResultHandler;
- import org.apache.ibatis.session.RowBounds;
- import org.apache.ibatis.type.TypeHandlerRegistry;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import java.lang.reflect.InvocationTargetException;
- import java.text.DateFormat;
- import java.util.Date;
- import java.util.List;
- import java.util.Locale;
- import java.util.Properties;
-
- /**
- * @author:sunxj
- * @date:2020-11-10 23:16:22
- * @description:打印sql语句
- */
- @Intercepts({
- //type指定代理的是那个对象,method指定代理Executor中的那个方法,args指定Executor中的query方法都有哪些参数对象
- //由于Executor中有两个query,因此需要两个@Signature
- @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),//需要代理的对象和方法
- @Signature(type = Executor.class,method = "query",args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
- @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class })//需要代理的对象和方法
- })
- public class SqlLoggerInterceptor implements Interceptor {
- Logger logger = LogManager.getLogger(SqlLoggerInterceptor.class.getName());
- @Override
- public Object intercept(Invocation invocation) throws Throwable {
- MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
- Object parameter = null;
- if (invocation.getArgs().length > 1) {
- //获得查询方法的参数,比如selectById(Integer id,String name),那么就可以获取到四个参数分别是:
- //{id:1,name:"user1",param1:1,param2:"user1"}
- parameter = invocation.getArgs()[1];
- }
- String sqlId = mappedStatement.getId();//获得mybatis的*mapper.xml文件中映射的方法,如:com.best.dao.UserMapper.selectById
-
- //将参数和映射文件组合在一起得到BoundSql对象
- BoundSql boundSql = mappedStatement.getBoundSql(parameter);
- //获取配置信息
- Configuration configuration = mappedStatement.getConfiguration();
- Object returnValue = null;
-
- logger.debug("/*---------------java:"+sqlId+"[begin]---------------*/");
- //通过配置信息和BoundSql对象来生成带值得sql语句
- String sql = geneSql(configuration, boundSql);
- //打印sql语句
- logger.debug("==> sql:"+sql);
- //先记录执行sql语句前的时间
- long start = System.currentTimeMillis();
- try {
- //开始执行sql语句
- returnValue = invocation.proceed();
- } catch (InvocationTargetException | IllegalAccessException e) {
- e.printStackTrace();
- }
- //记录执行sql语句后的时间
- long end = System.currentTimeMillis();
- //得到执行sql语句的用了多长时间
- long time = (end - start);
- //以毫秒为单位打印
- logger.debug("<== sql执行历时:"+time+"毫秒");
- //返回值,如果是多条记录,那么此对象是一个list,如果是一个bean对象,那么此处就是一个对象,也有可能是一个map
- return returnValue;
- }
-
- /**
- * 如果是字符串对象则加上单引号返回,如果是日期则也需要转换成字符串形式,如果是其他则直接转换成字符串返回。
- * @param obj
- * @return
- */
- private static String getParameterValue(Object obj) {
- String value;
- if (obj instanceof String) {
- value = "'" + obj.toString() + "'";
- } else if (obj instanceof Date) {
- DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
- value = "'" + formatter.format(obj) + "'";
- } else {
- if (obj != null) {
- value = obj.toString();
- } else {
- value = "";
- }
-
- }
- return value;
- }
-
- /**
- * 生成对应的带有值得sql语句
- * @param configuration
- * @param boundSql
- * @return
- */
- public static String geneSql(Configuration configuration, BoundSql boundSql) {
-
- Object parameterObject = boundSql.getParameterObject();//获得参数对象,如{id:1,name:"user1",param1:1,param2:"user1"}
- List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();//获得映射的对象参数
- String sql = boundSql.getSql().replaceAll("[\\s]+", " ");//获得带问号的sql语句
- if (parameterMappings.size() > 0 && parameterObject != null) {//如果参数个数大于0且参数对象不为空,说明该sql语句是带有条件的
- TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
- if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {//检查该参数是否是一个参数
- //getParameterValue用于返回是否带有单引号的字符串,如果是字符串则加上单引号
- sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));//如果是一个参数则只替换一次,将问号直接替换成值
-
- } else {
- MetaObject metaObject = configuration.newMetaObject(parameterObject);//将映射文件的参数和对应的值返回,比如:id,name以及对应的值。
- for (ParameterMapping parameterMapping : parameterMappings) {//遍历参数,如:id,name等
- String propertyName = parameterMapping.getProperty();//获得属性名,如id,name等字符串
- if (metaObject.hasGetter(propertyName)) {//检查该属性是否在metaObject中
- Object obj = metaObject.getValue(propertyName);//如果在metaObject中,那么直接获取对应的值
- sql = sql.replaceFirst("\\?", getParameterValue(obj));//然后将问号?替换成对应的值。
- } else if (boundSql.hasAdditionalParameter(propertyName)) {
- Object obj = boundSql.getAdditionalParameter(propertyName);
- sql = sql.replaceFirst("\\?", getParameterValue(obj));
- }
- }
- }
- }
- return sql;//最后将sql语句返回
- }
- @Override
- public Object plugin(Object target) {
- return Plugin.wrap(target, this);
- }
-
- @Override
- public void setProperties(Properties properties) {
- //properties可以通过
- System.out.println(properties);
- }
- }
11、此拦截写好之后还需要springboot使用,如果是通过@Component扫描是无法正常注入到IOC容器中的,因此需要通过@Configuration和@Bean的方式进行,新建一个配置BatisPlusConfig类,代码如下:
- package com.best.db;
-
- import com.best.common.sqllog.SqlLoggerInterceptor;
- import org.apache.ibatis.plugin.Interceptor;
- import org.apache.ibatis.session.SqlSessionFactory;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
-
- import java.util.Properties;
-
- /**
- * @author:sunxj
- * @date:2020-11-11 22:18:55
- * @description:mybatis插件配置类
- */
- @Configuration
- public class BatisPlusConfig {
- @Bean
- public String myInterceptor(SqlSessionFactory sqlSessionFactory) {
- //实例化插件
- SqlLoggerInterceptor sqlInterceptor = new SqlLoggerInterceptor();
- //创建属性值
- Properties properties = new Properties();
- properties.setProperty("prop1","value1");
- //将属性值设置到插件中
- sqlInterceptor.setProperties(properties);
- //将插件添加到SqlSessionFactory工厂
- sqlSessionFactory.getConfiguration().addInterceptor(sqlInterceptor);
- return "interceptor";
- }
- }
12、到此配置完成,启动springboot然后在浏览器中输入:http://localhost:8080/best/getUser1即可打印如下图所示:
原文链接:https://blog.csdn.net/sunxiaoju/article/details/109660493
作者:gogogo
链接:http://www.javaheidong.com/blog/article/984/161c8ca3609695e799ea/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!