java - Spring中从 'composed Annotations'获取值

标签 java spring spring-annotations

使用 Spring,您可以拥有某种组合注释。一个突出的例子是 @SpringBootApplication -注释,它是 @Configuration 的组合, @EnableAutoConfiguration@ComponentScan .

我试图获取受某个注释影响的所有 Bean,即 ComponentScan .

已关注 this回答,我正在使用以下代码:

for (T o : applicationContext.getBeansWithAnnotation(ComponentScan.class).values()) {
    ComponentScan ann = (ComponentScan) o.getClass().getAnnotation(ComponentScan.class);
    ...
}

这不起作用,因为不是所有的bean都由getBeansWithAnnotation(ComponentScan.class)返回确实用该注释进行了注释,因为那些例如注释为 @SpringBootApplication (通常)不是。

现在我正在寻找某种通用方法来检索注释的值,即使它仅作为另一个注释的片段添加。 我怎样才能做到这一点?

最佳答案

事实证明,有一个实用程序集AnnotatedElementUtils,它允许您处理这些合并注释

for (Object annotated : context.getBeansWithAnnotation(ComponentScan.class).values()) {
    Class clazz = ClassUtils.getUserClass(annotated) // thank you jin!
    ComponentScan mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(clazz, ComponentScan.class);
    if (mergedAnnotation != null) { // For some reasons, this might still be null.
        // TODO: useful stuff.
    }
}

关于java - Spring中从 'composed Annotations'获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56327068/

相关文章:

java - sudo ln -sfn 有什么作用?

java - 重构超过 50k 行代码的类?

java - `ThreadPoolTaskExecutor` 线程在Spring执行后没有被杀死

java - Spring Profile 不适用于 Aspect 注释

java - 如何在 Java 中使用同一循环来确定三个不同条件的范围?

java - 使用函数作为参数类型使用 getDeclaredMethod

java - Spring MVC 通过表单更新对象

java - 将模型对象从 spring Controller 传递到 jsp

java - 无法使用 spring 检索属性

java - @Autowired 发现不明确的依赖关系并且仍然有效。如何?