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(); } }