如何使用Reflections库(或其他)在Spring Web App中扫描注释

时间:2014-06-04 21:01:28

标签: java spring spring-mvc annotations google-reflections

我有一个使用Spring构建并在Jboss中运行的Web应用程序。我正在尝试在运行时扫描具有特定注释的类。现在我正在使用开源Reflections library

public static List<Class> scanForClassesWithAnnotation(Class<? extends Annotation> annotationClass)
{
    List<Class> classesWithAnnotation = new ArrayList<>();
    for(Package p : Package.getPackages())
    {
        LOGGER.info("scanForClassesWithAnnotation: Examining package " + p.getName());

        try
        {
            List<ClassLoader> classLoadersList = new ArrayList<>();
            classLoadersList.add(ClasspathHelper.contextClassLoader());
            classLoadersList.add(ClasspathHelper.staticClassLoader());

            Reflections reflections = new Reflections(
                new ConfigurationBuilder()
                    .setScanners(new SubTypesScanner(false), new ResourcesScanner())
                    .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[classLoadersList.size()])))
                    .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(p.getName()))));

            Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);

            LOGGER.info("\tscanForClassesWithAnnotation: found classes " + JsonUtils.objectToJson(classes));

            for(Class foundClass : classes)
            {
                if(foundClass.isAnnotationPresent(annotationClass))
                {
                    classesWithAnnotation.add(foundClass);
                }
            }
        } catch (Exception ignored) {}
    }
    return classesWithAnnotation;
}

当这段代码执行时,我在日志中看到了很多这样的消息:

given scan urls are empty. set urls in the configuration

此代码适用于独立的Maven项目,因此我知道它的工作原理。但我认为问题在于代码在servlet上下文中运行。我该如何解决?如何在Spring webapp中扫描带注释的类?提前致谢。

2 个答案:

答案 0 :(得分:0)

开始玩

public class Scanner {

    private static final Log log = LogFactory.getLog(Scanner.class);

    public static void main(String[] args) throws IOException {
        SimpleMetadataReaderFactory metadataFactory = new SimpleMetadataReaderFactory();
        ResourcePatternResolver scaner = new PathMatchingResourcePatternResolver();
        Resource[] resources = scaner.getResources("classpath*:/base.package/**/*.class");
        for (Resource r : resources) {
            log.info("Scanning [" + r.getDescription() + "]");
            MetadataReader metadataReader = metadataFactory.getMetadataReader(r);
            if (metadataReader.getAnnotationMetadata().isAnnotated("org.example.Annotation"))
                log.info("found annotation in [" + r.getDescription() + "]");

        }
    }

答案 1 :(得分:0)

这有效

    public static List<Class> scanForClassesWithAnnotation2(Class<? extends Annotation> annotationClass)
{
    List<Class> classesWithAnnotation = new ArrayList<>();

    ClassPathScanningCandidateComponentProvider scanner =
        new ClassPathScanningCandidateComponentProvider(false);

    scanner.addIncludeFilter(new AnnotationTypeFilter(annotationClass));

    for (BeanDefinition bd : scanner.findCandidateComponents("com.example"))
    {
        try
        {
            classesWithAnnotation.add(Class.forName(bd.getBeanClassName()));
        } catch (ClassNotFoundException e)
        {
            LOGGER.error("Could not create class from class name");
        }
    }

    return classesWithAnnotation;
}