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

标签 java spring spring-mvc annotations

我有一个使用

检索的注释列表
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 是该接口(interface)的一种实现。

考虑到这样的例子

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.

关于java - 在运行时使用 java.lang.annotation 检索 Spring 中的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31308248/

相关文章:

java - Mahout - 如何取消设置 Mahout_local 以在 Hadoop 文件系统中运行?

java - 相似的并发任务,运行时间差异很大(Java)

java - 在 Windows 版 Sublime Text 上运行 Java

java - 如何将@RequestBody 值传递给转发 Controller Spring MVC

java - 即使在@CrossOrigin注释之后,Spring Boot CORS也不起作用

java - 如何在 Spring 中创建多 Web 模块应用程序?

java - Maven 配置不起作用

java - Spring MVC 和 jQuery 自动完成

java - @enablesns @enablesqs 注解有什么作用(spring cloud aws)?

java - 具有上下文路径的 Spring Boot 静态内容