1. 程式人生 > 實用技巧 >可用於springboot的jar的掃描特定包的所有類的方法

可用於springboot的jar的掃描特定包的所有類的方法

之前有遇到過本地測試跑的通的程式碼,上到線上就失敗的情況,當時是一個檔案處理的操作。

後面才發現spring boot打的jar包,和直接本地用IDEA執行的程式碼多多少少還是有區別的,再一個就是windonws和linux系統,也多多少少有點不同。

這回寫了掃描包程式碼,然後用jar測試了下,

下面是兩個獲取某個包下所有有特定註解類的程式碼,都是網上copy的

/**
* 不可用於jar
*/
public
List<Class<?>> a() { List<Class<?>> classList = new ArrayList<>(); ResourcePatternResolver resolver
= new PathMatchingResourcePatternResolver(); MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(); try { Resource[] resources = resolver.getResources("classpath*:com/bzua/jingdata/service/**/*.class"); ClassLoader loader = ClassLoader.getSystemClassLoader();
for (Resource resource : resources) { MetadataReader reader = metaReader.getMetadataReader(resource); String className = reader.getClassMetadata().getClassName(); Class<?> clazz = loader.loadClass(className); if (clazz.isAnnotationPresent(Report.class
)) { classList.add(clazz); } } } catch (ClassNotFoundException | IOException e) { log.error("錯誤資訊: ", e); } return classList; }
  /**
  * 可用於jar
  */
public List<Class<?>> b() { List<Class<?>> classList = new ArrayList<>(); ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); final String BASE_PACKAGE = "com.bzua.jingdata.service"; final String RESOURCE_PATTERN = "/**/*.class"; try { String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE) + RESOURCE_PATTERN; Resource[] resources = resourcePatternResolver.getResources(pattern); //MetadataReader 的工廠類 MetadataReaderFactory readerfactory = new CachingMetadataReaderFactory(resourcePatternResolver); for (Resource resource : resources) { //用於讀取類資訊 MetadataReader reader = readerfactory.getMetadataReader(resource); //掃描到的class String classname = reader.getClassMetadata().getClassName(); Class<?> clazz = Class.forName(classname); //判斷是否有指定主解 if (clazz.isAnnotationPresent(Report.class)) { classList.add(clazz); } } } catch (IOException | ClassNotFoundException e) { } return classList; }