• Spring boot 打jar包启动后无法正常扫描class的问题(Idea直接运行正常)


    import com.google.common.collect.Lists;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.core.io.Resource;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import org.springframework.core.io.support.ResourcePatternResolver;
    import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
    import org.springframework.core.type.classreading.MetadataReader;
    import org.springframework.core.type.classreading.MetadataReaderFactory;
    import org.springframework.util.ClassUtils;
    
    import java.io.IOException;
    import java.util.Collections;
    import java.util.List;
    
    /**
     * 注意,如果是jar包启动的,需要打包的时候加上<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
     */
    @Slf4j
    public class ClassUtil {
    
        public static List<Class<?>> getAllClasses(Class<?> c) {
            String packageName = c.getPackage().getName();
            return getClasses(packageName);
        }
    
        /**
         * 根据包名查询出所有子类信息
         *
         */
        private static List<Class<?>> getClasses(String packageName) {
            ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
            final String RESOURCE_PATTERN = "/**/*.class";
            // 扫描的包名
            List<Class<?>> classCache = Lists.newArrayList();
            try {
                String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(packageName)
                        + RESOURCE_PATTERN;
                Resource[] resources = resourcePatternResolver.getResources(pattern);
                MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
                for (Resource resource : resources) {
                    if (resource.isReadable()) {
                        MetadataReader reader = readerFactory.getMetadataReader(resource);
                        //扫描到的class
                        String className = reader.getClassMetadata().getClassName();
                        Class<?> clazz = Class.forName(className);
                        classCache.add(clazz);
                    }
                }
                return classCache;
            } catch (ClassNotFoundException | IOException e) {
                log.error("读取class失败", e);
            }
            return Collections.emptyList();
        }
    
    
    }
  • 相关阅读:
    数据结构习题
    POJ 2965 The Pilots Brothers' refrigerator
    POJ 1753 Flip Game
    HDU 1172 猜数字
    假币问题
    HDU 1425 sort
    Java基础知识
    P1650 田忌赛马
    SQL注入之Sqli-labs系列第十九关(基于头部的Referer POST报错注入)
    SQL注入之Sqli-labs系列第十八关(基于错误的用户代理,头部POST注入)
  • 原文地址:https://www.cnblogs.com/gabin/p/14788433.html
Copyright © 2020-2023  润新知