【发布时间】:2021-02-24 08:01:18
【问题描述】:
我正在使用 SpringBoot 2.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">
我不知道为什么,有人知道吗?
【问题讨论】:
-
因为你没有使用 Spring 来读取注解,所以它不起作用。您将需要使用 Spring 注释工具来读取注释以获得适当的支持。
-
@M.春季初始化bean时不会发生Deinum吗? '@SpringBootTest' 注释的作用。此外,这篇文章没有使用 Spring 注释工具。 examples.javacodegeeks.com/spring-aliasfor-annotation-example
-
该样本中测试的第 27 行清楚地使用了
AnnotationUtils。 -
是的,但它是'findAnnotation',所以我认为它只是用于查找特定注释。这个怎么样? gist.github.com/SomboChea/0324964054c8269ce5f21e7f8ff4c01a 完整示例代码没有使用任何注解工具。
-
该代码不是因为 bean 是由内部使用的 spring 构造的,如果您要编写测试,您仍然需要
AnnotationUtils。因此它仍然被使用。如果不使用合成注释的弹簧功能,您将无法获得别名的值,因为它是弹簧功能。
标签: java spring spring-boot annotations