无法使用spring classpathscanningcandidatecomponentprovider返回所有标记有特定注解的类

tp5buhyn  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(364)

我有一个遗留的spring(而不是boot)应用程序,我想用特定的注解来标记所有的类。为了达到这个目的,我使用以下答案:https://stackoverflow.com/a/1415338/2674303
所以我创建了以下类:

  1. @Component
  2. public class MyVerifier {
  3. public void verify() {
  4. ClassPathScanningCandidateComponentProvider scanner =
  5. new ClassPathScanningCandidateComponentProvider(false);
  6. scanner.addIncludeFilter(new AnnotationTypeFilter(MyAnnotation.class));
  7. Set<BeanDefinition> set = scanner.findCandidateComponents("base.pack")
  8. }

在代码中,我有:

  1. package base.pack.ololo.qwery;
  2. @MyAnnotation
  3. public class MyClass...
  1. package base.pack.another.packagename;
  2. @MyAnnotation
  3. public class MyOtherClass...

但是 set 变量为空集。为什么?
如何修复?

wa7juj8i

wa7juj8i1#

我对注解保留策略有问题,所以注解在运行时不可用
旧(坏)版本

  1. @Inherited
  2. @Target({ ElementType.TYPE })
  3. public @interface MyAnnotation{
  4. }

新(工作)版本:

  1. @Inherited
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target({ ElementType.TYPE })
  4. public @interface MyAnnotation{
  5. }

相关问题