使用jersey 注解包扫描类PackageNamesScanner

时间:2022-11-30 08:15:32

Jersey 中自带一个包扫描,可以是包,或者具体类名 ,扫描的类型是自己定注解类型,实现功能更加大,可以是jar 包 可以是虚拟地址下的

Jersey 主要用来扫描Path Provider 类中同时包括以上的Annotation,使用Jersey 包扫描只需要三步。

 String aa[] = new String[]{"com.jerweb"};
Scanner scanner = new PackageNamesScanner(checkNotNull(aa));
final AnnotationScannerListener asl = new PathProviderScannerListener();
scanner.scan(asl);
Set<Class<?>> sets= asl.getAnnotatedClasses();

1、包地址传入PackageNamesScanner

2、自定义的注解实现AnnotationScannerListener 的子类

3、scan

查看Jesery PathProviderScannerListener源码

 public final class PathProviderScannerListener extends AnnotationScannerListener {

     /**
* Create a scanning listener to check for Java classes in Java
* class files annotated with {@link Path} or {@link Provider}.
*
*/
public PathProviderScannerListener() {
super(Path.class, Provider.class);
} /**
* Create a scanning listener to check for Java classes in Java
* class files annotated with {@link Path} or {@link Provider}.
*
* @param classloader the class loader to use to load Java classes that
* are annotated with any one of the annotations.
*/
public PathProviderScannerListener(ClassLoader classloader) {
super(classloader, Path.class, Provider.class);
}
}

很简单。自定义实现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);
}
}

测试以上代码

 public static void main(String[] args)
{
String aa[] = new String[]{"com.jerweb"};
Scanner scanner = new PackageNamesScanner(checkNotNull(aa));
final AnnotationScannerListener asl = new PathProviderScannerListener();
final AnnotationScannerListener asl1 = new ErrInfoScannerListener();
scanner.scan(asl1);
scanner.scan(asl);
Set<Class<?>> sets1 = asl1.getAnnotatedClasses();
Set<Class<?>> sets= asl.getAnnotatedClasses(); }

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>