我有一个使用
检索的注释列表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 suppliedAnnotation
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 suppliedAnnotation
type, returning aMap
of bean names with corresponding bean instances.
关于java - 在运行时使用 java.lang.annotation 检索 Spring 中的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31308248/