Skip to content

@AliasFor doesn’t work on attribute in custom annotation

I’m using SpringBoot 2.4.2. And I’m struggling with @AliasFor with custom annotation.

I implemented below custom annotation.

public @interface CustomAnnotation {

  String value() default "";

  String aliasAttribute() "";

And using it like this.

public class TestClass() {
 // codes here

And this test code fails.

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

  TestClass testClass;

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

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

with message

to be equal to:

I don’t know why, anyone know?


An annotation is static metadata for a class, field etc. so Spring cannot change anything about it. To make features as @AliasFor possible Spring uses, what they call, synthesized annotations. For those to be used/detected you need to utilize the Spring internals to obtain that synthesized annotation and for the @AliasFor to work. For this use AnnotationUtils.findAnnotation (Spring uses that internally as well).

@AliasFor is a Spring feature so without using the Spring components this won’t work.

Your test method is basically the same as

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

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

Both this test and your test will fail, because they simply don’t use the Spring infrastructure for detecting annotations and apply the features of Spring.

When using AnnotationUtils.findAnnotation the test will pass.

class CustomAnnotationTest {

    void testStandardJava() {
        CustomAnnotation annotation = TestClass.class.getAnnotation(CustomAnnotation.class);

    void testWithSpring() {
        CustomAnnotation annotation = AnnotationUtils.findAnnotation(TestClass.class, CustomAnnotation.class);

The testStandardJava will fail, the testWithSpring will pass because it uses the proper mechanisms.