@aliasfor对自定义注解中的属性无效

qyzbxkaa  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(595)

我用的是springboot2.4.2。我正在为@aliasfor和自定义注解而挣扎。
我实现了下面的自定义注解。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CustomAnnotation {

  @AliasFor("aliasAttribute")
  String value() default "";

  @AliasFor("value")
  String aliasAttribute() "";
}

像这样使用它。

@CustomAnnoatation("test")
@Component
public class TestClass() {
 // codes here
}

这个测试代码失败了。

@SpringBootTest(classes = TestClass.class)
public class CustomAnnotationTest {

  @Autowired
  TestClass testClass;

  @Test
  public void valueTest1() {
    Annotation annotation = testClass.getClass().getAnnotation(CustomAnnotation.class);

    assertThat(((CustomAnnotation) annotation).value()).isEqualTo(((CustomAnnotation) annotation).aliasAttribute());
  }
}

带消息

org.opentest4j.AssertionFailedError: 
Expecting:
 <"">
to be equal to:
 <"test">

我不知道为什么,有人知道吗?

pxyaymoc

pxyaymoc1#

注解是类、字段等的静态元数据,因此spring不能对其进行任何更改。使要素成为 @AliasFor 可能的spring使用了他们所说的合成注解。对于那些要使用/检测的对象,您需要利用spring内部构件来获得综合注解和 @AliasFor 去工作。用于此用途 AnnotationUtils.findAnnotation (spring在内部也使用了这个功能)。 @AliasFor 是一个spring特性,因此如果不使用spring组件,这将不起作用。
你的测试方法和我的基本相同

@Test
  public void valueTest1() {
    Annotation annotation = TestClass.class.getAnnotation(CustomAnnotation.class);

    assertThat(((CustomAnnotation) annotation).value()).isEqualTo(((CustomAnnotation) annotation).aliasAttribute());
  }

此测试和您的测试都将失败,因为它们根本不使用spring基础结构来检测注解并应用spring的特性。
使用时 AnnotationUtils.findAnnotation 考试会通过的。

class CustomAnnotationTest {

    @Test
    void testStandardJava() {
        CustomAnnotation annotation = TestClass.class.getAnnotation(CustomAnnotation.class);
        assertThat(annotation.value()).isEqualTo(annotation.aliasAttribute());
    }

    @Test
    void testWithSpring() {
        CustomAnnotation annotation = AnnotationUtils.findAnnotation(TestClass.class, CustomAnnotation.class);
        assertThat(annotation.value()).isEqualTo(annotation.aliasAttribute());
    }
}

这个 testStandardJava 一旦失败 testWithSpring 将通过,因为它使用适当的机制。

相关问题