简体   繁体   English

Spring Framework AliasFor annotation dilema

[英]Spring Framework AliasFor annotation dilema

I am using spring boot (1.3.4.RELEASE) and have a question regarding the new @AliasFor annotation introduced spring framework in 4.2 我正在使用spring boot(1.3.4.RELEASE)并对4.2中引入的新@AliasFor注释弹簧框架有疑问

Consider the following annotations: 请考虑以下注释:

View 视图

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Component
public @interface View {
    String name() default "view";
}

Composite 综合

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@View
public @interface Composite {
    @AliasFor(annotation = View.class, attribute = "name")
    String value() default "composite";
}

We then annotate a simple class as follows 然后,我们按如下方式注释一个简单的类

@Composite(value = "model")
public class Model {
}

When running the following code 运行以下代码时

ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
String[] beanNames = context.getBeanNamesForAnnotation(View.class);
for (String beanName : beanNames) {
    View annotationOnBean = context.findAnnotationOnBean(beanName, View.class);
    System.out.println(annotationOnBean.name());
}

I am expecting the output to be model , but it's view . 我期待输出是模型 ,但它的观点

From my understanding, shouldn't @AliasFor (among other things) allow you to override attributes from meta-annotations (in this case @View )? 根据我的理解,不应该@AliasFor (除其他外)允许你覆盖元注释中的属性(在这种情况下是@View )? Can someone explain to me what am I doing wrong? 有人可以向我解释我做错了什么吗? Thank you 谢谢

Take a look at the documentation for @AliasFor , and you will see this quite in the requirements for using the annotation: 看一下@AliasFor的文档,您将在使用注释的要求中看到这一点:

Like with any annotation in Java, the mere presence of @AliasFor on its own will not enforce alias semantics. 与Java中的任何注释一样,仅仅存在@AliasFor就不会强制执行别名语义。

So, trying to extract the @View annotation from your bean is not going to work as expected. 因此,尝试从bean中提取@View注释不会按预期工作。 This annotation does exist on the bean class, but its attributes were not explicitly set, so they cannot be retrieved in the traditional way. 此注释确实存在于bean类中,但其属性未显式设置,因此无法以传统方式检索它们。 Spring offers a couple utility classes for working with meta-annotations, such as these. Spring提供了一些用于处理元注释的实用程序类,例如这些。 In this case, the best option is to use AnnotatedElementUtils : 在这种情况下,最好的选择是使用AnnotatedElementUtils

ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
String[] beanNames = context.getBeanNamesForAnnotation(View.class);
for (String beanName : beanNames) {
    Object bean = context.getBean(beanName);
    View annotationOnBean = AnnotatedElementUtils.findMergedAnnotation(bean, View.class);
    System.out.println(annotationOnBean.name());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM