importjava.io.IOException;importjava.util.HashSet;importjava.util.Set;importorg.springframework.context.ResourceLoaderAware;importorg.springframework.core.io.Resource;importorg.springframework.core.io.ResourceLoader;importorg.springframework.core.io.support.ResourcePatternResolver;importorg.springframework.core.io.support.ResourcePatternUtils;importorg.springframework.core.type.classreading.CachingMetadataReaderFactory;importorg.springframework.core.type.classreading.MetadataReader;importorg.springframework.core.type.classreading.MetadataReaderFactory;importorg.springframework.util.ClassUtils;importorg.springframework.util.SystemPropertyUtils;importxxxxx.mall.common.application.MallApplication;importxxxxx.common.assertion.Assert;/*** SPRING扫描包下面的类
*
* @project common-utils
* @fileName Scaner.java
* @Description
*@authorlight-zhang
* @date 2019年5月5日
*@version1.0.0*/
public class ScanSupport implementsResourceLoaderAware {/*** Spring容器注入*/
privateResourceLoader resourceLoader;private ResourcePatternResolver resolver =ResourcePatternUtils.getResourcePatternResolver(resourceLoader);private MetadataReaderFactory metadataReaderFactory = newCachingMetadataReaderFactory(resourceLoader);private static final String FULLTEXT_SACN_PACKAGE_PATH = "fulltext.scan.package";/*** set注入对象*/@Overridepublic voidsetResourceLoader(ResourceLoader resourceLoader) {this.resourceLoader =resourceLoader;
}/*** 利用spring提供的扫描包下面的类信息,再通过classfrom反射获得类信息
*
*@paramscanPath
*@return*@throwsIOException*/
public Set> doScan(String scanPath) throwsIOException {
Set> classes = new HashSet>();
String packageSearchPath=ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
.concat(ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(scanPath))
.concat("/**/*.class"));
Resource[] resources=resolver.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();
}
}
}returnclasses;
}/*** 指定包下面的类信息
*
*@return多个类信息*/
public static Set>classInfos() {try{
String scanPath=MallApplication.getApplicationContext().getEnvironment()
.getProperty(FULLTEXT_SACN_PACKAGE_PATH);return newScanSupport().doScan(scanPath);
}catch(Exception e) {
Assert.RuntimeException("扫描包类信息错误");
}return null;
}
}