gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:32:16 26 4
gpt4 key购买 nike

我有一个使用

检索的注释列表
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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com