jdk21

mybatisplus + mybatis 自定义插件

  1. 配置文件写在同一个类中生效
  2. 分开就只有写入生效,读取不生效
  3. 通过EventListener(ContextRefreshedEvent.class)双重检查锁,自定义注入然后生效

import com.wright.conf.mybatis.interceptor.EncryptFieldInterceptor;
import com.wright.criminalcase.service.CaseOperationLogService;
import com.wright.criminalcase.util.WrightCaseEncUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

@Configuration
@Slf4j
public class CaseMybatisPlusConfig {
    
    
    @Autowired
    private ApplicationContext applicationContext;
    
    private final AtomicBoolean interceptorAdded = new AtomicBoolean(false);
    
    
    @EventListener(ContextRefreshedEvent.class)
    public void addEncryptInterceptor() {
        if (interceptorAdded.compareAndSet(false, true)) {
            log.info("应用程序上下文刷新完成,开始注册加密拦截器");
            EncryptFieldInterceptor encryptFieldInterceptor = new 插件();
            try {
                // 在所有的SqlSessionFactory都初始化完成后从ApplicationContext获取
                Map<String, SqlSessionFactory> sqlSessionFactoryMap = applicationContext.getBeansOfType(
                        SqlSessionFactory.class);
                for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryMap.values()) {
                    sqlSessionFactory.getConfiguration().addInterceptor(插件);
                    log.info("向SqlSessionFactory [{}] 添加插件成功",
                            sqlSessionFactory.getClass().getName());
                }
            } catch (Exception e) {
                // 如果添加失败,重置标志位以便下次可以重试
                interceptorAdded.set(false);
                log.error("添加加密拦截器失败: {}", e.getMessage(), e);
            }
        }
    }
    
}