咱們經常有掃描項目裏帶有指定註解的class, 下面是利用spring掃描自定義註解的方法, 仍是比較靈活的java
我這裏將掃描到的class放到map, 你能夠放到其餘地方,以便後期使用spring
import lombok.extern.slf4j.Slf4j; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; 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 org.springframework.util.StringUtils; import javax.persistence.Table; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 掃描指定包下帶有指定註解的class * @author jaffreyen * @date 2018/3/5 */ @Slf4j public class MyApplicationListener implements ApplicationListener { /** * Handle an application event. * * @param event the event to respond to */ @Override public void onApplicationEvent(ApplicationEvent event) { ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); final String RESOURCE_PATTERN = "/**/*.class"; // 掃描的包名 final String BASE_PACKAGE = "com.xxx"; Map<String,Class<?>> classCache = new HashMap<>(); try { String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE) + 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); //判斷是否有指定註解 Table annotation = clazz.getAnnotation(Table.class); if(annotation != null){ //這個類使用了自定義註解 classCache.put(className, clazz); } } } } catch (IOException | ClassNotFoundException e) { log.error("讀取class失敗", e); } } }