spring获取指定包下面的所有类
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternUtils; 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 org.springframework.util.SystemPropertyUtils; /** * 扫描类工具 * * @project common-utils * @fileName ScanerUtil.java * @Description * @author light-zhang * @date 2019年4月12日 * @version 1.0.0 */ @Configuration public class ScanerUtil implements ResourceLoaderAware { private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver); public static Set<Class<?>> scanner() { try { String scanPath="cc.xx.mall.common.fulltext"; return new ScanerUtil().doScan(scanPath); } catch (Exception e) { } return null; } public Set<Class<?>> doScan(String scanPath) throws IOException { Set<Class<?>> classes = new HashSet<Class<?>>(); String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX .concat(ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(scanPath)) .concat("/**/*.class")); Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); MetadataReader metadataReader = null; for (Resource resource : resources) { if (resource.isReadable()) { metadataReader = metadataReaderFactory.getMetadataReader(resource); try { if (metadataReader.getClassMetadata().isConcrete()) {// 当类型不为抽象类或接口在添加到集合 classes.add(Class.forName(metadataReader.getClassMetadata().getClassName())); } } catch (Exception e) { e.printStackTrace(); } } } return classes; } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader); } public static void main(String[] args) { Set<Class<?>> clazz = ScanerUtil.scanner(); for (Class<?> class1 : clazz) { System.out.println(class1.getName()); } } }

更多精彩