使用jersey 注解包扫描类PackageNamesScanner
Jersey 中自带一个包扫描,可以是包,或者具体类名 ,扫描的类型是自己定注解类型,实现功能更加大,可以是jar 包 可以是虚拟地址下的
Jersey 主要用来扫描Path Provider 类中同时包括以上的Annotation,使用Jersey 包扫描只需要三步。
1 String aa[] = new String[]{"com.jerweb"}; 2 Scanner scanner = new PackageNamesScanner(checkNotNull(aa)); 3 final AnnotationScannerListener asl = new PathProviderScannerListener(); 4 scanner.scan(asl); 5 Set<Class<?>> sets= asl.getAnnotatedClasses();
1、包地址传入PackageNamesScanner
2、自定义的注解实现AnnotationScannerListener 的子类
3、scan
查看Jesery PathProviderScannerListener源码
1 public final class PathProviderScannerListener extends AnnotationScannerListener { 2 3 /** 4 * Create a scanning listener to check for Java classes in Java 5 * class files annotated with {@link Path} or {@link Provider}. 6 * 7 */ 8 public PathProviderScannerListener() { 9 super(Path.class, Provider.class); 10 } 11 12 /** 13 * Create a scanning listener to check for Java classes in Java 14 * class files annotated with {@link Path} or {@link Provider}. 15 * 16 * @param classloader the class loader to use to load Java classes that 17 * are annotated with any one of the annotations. 18 */ 19 public PathProviderScannerListener(ClassLoader classloader) { 20 super(classloader, Path.class, Provider.class); 21 } 22 }
View Code
很简单。自定义实现AnnotationScannerListener 的子类,就可以用来扫描自定义注解
@Inherited @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Err { String value(); }
@Inherited @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Info { String value(); }
public class ErrInfoScannerListener extends AnnotationScannerListener { public ErrInfoScannerListener() { super(Err.class, Info.class); } /** * Create a scanning listener to check for Java classes in Java * class files annotated with {@link Err} or {@link Info}. * * @param classloader the class loader to use to load Java classes that * are annotated with any one of the annotations. */ public ErrInfoScannerListener(ClassLoader classloader) { super(classloader, Err.class, Info.class); } }
测试以上代码
1 public static void main(String[] args) 2 { 3 String aa[] = new String[]{"com.jerweb"}; 4 Scanner scanner = new PackageNamesScanner(checkNotNull(aa)); 5 final AnnotationScannerListener asl = new PathProviderScannerListener(); 6 final AnnotationScannerListener asl1 = new ErrInfoScannerListener(); 7 scanner.scan(asl1); 8 scanner.scan(asl); 9 Set<Class<?>> sets1 = asl1.getAnnotatedClasses(); 10 Set<Class<?>> sets= asl.getAnnotatedClasses(); 11 12 }
Maven 引用包
<dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <version>1.18.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.18.1</version> </dependency>