在运行时使用 java.lang.annotation 在 Spring 中检索 bean

Retrieve a bean in Spring using java.lang.annotation in runtime

我有一个使用

检索到的注释列表
java.lang.reflect.Method.getDeclaredAnnotations()

使用这些注释,我如何检索 spring 个被 标记为 的 bean 有这些注释吗?

伪代码:

public interface Work{...}

@Component
@A1
public class SpringBean1 implements Work{}

@Component
@A2
public class SpringBean2 implements Work{}

public class Test 
{

  public void doSomething() 
  {

    Annotation[] annotations = getAnnotationsListUsingReflection();

    for(Annotation annotation: annotations) 
    {
      Work work = /* Retrieve bean using annotation, how to do this? */
      work.xyz(); 
      ......
    }    

  }
}

假设您的注释是在注释 bean 类型而不是它们的方法,您可以使用 ListableBeanFactory#getBeanNamesForAnnotation(Class)

Find all names of beans whose Class has the supplied Annotation type, without creating any bean instances yet.

AnnotationConfigApplicationContext 是该接口的一种实现。

鉴于这样的例子

AnnotationConfigApplicationContext ctx = ...;
String[] beanNames = ctx.getBeanNamesForAnnotation(Annotation.class);

然后遍历 bean 名称并获取每个 bean

for (String beanName : beanNames) {
    Object bean = ctx.getBean(beanName);
    // use it
}

或者,ListableBeanFactory#getBeansWithAnnotation(Class) 可以为您完成这项工作:

Find all beans whose Class has the supplied Annotation type, returning a Map of bean names with corresponding bean instances.