且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

扫描Java标注在运行时

更新时间:2023-01-10 18:41:54

使用org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider

API


  

这是扫描从基础包classpath中的组件供应商。然后,它适用排除和包括过滤器生成的类来寻找候选人。


块引用>
  ClassPathScanningCandidateComponentProvider扫描仪=
新ClassPathScanningCandidateComponentProvider(小于DO_YOU_WANT_TO_USE_DEFALT_FILTER&GT);scanner.addIncludeFilter(新AnnotationTypeFilter(小于TYPE_YOUR_ANNOTATION_HERE>的.class));为(的BeanDefinition BD:scanner.findCandidateComponents(小于TYPE_YOUR_BASE_PACKAGE_HERE&GT))
    的System.out.println(bd.getBeanClassName());

What is the best way of searching the whole classpath for an annotated class?

I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.

Do you know a library or a Java facility to do this?

Edit: I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with @WebService or @EJB and the system find these classes while loading so they are accessible remotely.

Use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider

API

A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates.

ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>);

scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));

for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
    System.out.println(bd.getBeanClassName());