Home Mybatis学习 Mybatis—自定义插件(脱敏及SQL性能分析)

Mybatis—自定义插件(脱敏及SQL性能分析)

https://www.bilibili.com/video/BV1LK4y1S7v2?p=4

 

项目地址:Mybatis-Study-04

代码:Desensitizer:

package plugins;

import java.util.function.Function;

public interface Desensitizer extends Function<String,String> {
}
Tuomin注解:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Tuomin {
    TuominStrategy strategy();
}
Tuomin策略(枚举):
public enum TuominStrategy {
    USERNAME(s->s.replaceAll("(\\S)\\S(\\S*)","$1*$2"));
    private  final Desensitizer desensitizer;
    TuominStrategy(Desensitizer d) {
        this.desensitizer = d;
    }

    public Desensitizer getDesensitizer() {
        return desensitizer;
    }
}

Tuomin逻辑:
package plugins;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Stream;


@Intercepts(@Signature(type= ResultSetHandler.class,method = "handleResultSets",args = Statement.class))
public class TuominPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        List<Object> records = (List<Object>) invocation.proceed();
        records.forEach(this::tuomin);
        return records;
    }
    private void tuomin(Object source){
        Class<?> sourceClass = source.getClass();
        MetaObject metaObject = SystemMetaObject.forObject(source);
        Stream.of(sourceClass.getDeclaredFields()).filter(field -> field.isAnnotationPresent(Tuomin.class)).forEach(field -> doTuomin(metaObject,field));

    }

    private void doTuomin(MetaObject metaObject, Field field) {
        String name = field.getName();
        Object value = metaObject.getValue(name);
        if(String.class == metaObject.getGetterType(name) && value!=null){
            Tuomin tuomin = field.getAnnotation(Tuomin.class);
            TuominStrategy type = tuomin.strategy();
            Object o = type.getDesensitizer().apply((String)value);
            metaObject.setValue(name,o);
        }

    }
}

实体类:
@Getter
//实体类
public class User {
    private int id;
    @Tuomin(strategy = TuominStrategy.USERNAME)
    private String name;
    private String pwd;

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
}

mybatis核心配置文件:
<plugins>
    <plugin interceptor="plugins.TuominPlugin"></plugin>
</plugins>


插件原理及说明:

版权声明:本文为CSDN博主「湖畔微风」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/hupanfeng/article/details/9247379

SIMILAR ARTICLES

发表评论

发表评论