springboot 提前加载类

51 阅读1分钟
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;  


import org.springframework.asm.ClassReader;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class PreloadClassOnContextRefreshed implements ApplicationListener<ContextRefreshedEvent> {
private static final String[] CLASS_PREFIX_ARR = new String[]{"com.*.*.sale"};
private static final List<String> PKGS = Arrays.asList("mapper", "service");
  
    @Override

    public void onApplicationEvent(ContextRefreshedEvent event) {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            for (String classPrefix : CLASS_PREFIX_ARR) {
                Resource[] resources = resolver.getResources("classpath*:" + classPrefix.replace('.', '/') + "/**/*.class");
                for (Resource resource : resources){
                    String className = null;
                    try (InputStream is = resource.getInputStream()) {
                        ClassReader cr = new ClassReader(is);
                        className = cr.getClassName().replace('/', '.');
                        String[] arr = className.split("\\.");
                        if(PKGS.contains(arr[arr.length-2]) || PKGS.contains(arr[arr.length-3])){
                            Class<?> clz = Class.forName(className);
                            log.info("preLoadclass success:" + className + ",classLoader: " + clz.getClassLoader());
                        }

                    } catch (Throwable e) {
                        log.warn("preLoadclass failed:" + className);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

其它方案参见:zhuanlan.zhihu.com/p/627626542