java–Interface Annotation不接受application.properties值

概述我开发了一个简单的注释界面@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface CustomAnnotation { String foo() default 'foo'; } 然后我测试它注释一个类@CustomAnnotation publi

我开发了一个简单的注释界面

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface CustomAnnotation {    String foo() default "foo";}

然后我测试它注释一个类

@CustomAnnotationpublic class AnnotatedClass {}

并使用方法调用它

public voID foo()  {    CustomAnnotation customAnnotation = AnnotatedClass.class.getAnnotation(CustomAnnotation.class);    logger.info(customAnnotation.foo());}

并且一切正常,因为它记录了foo.我也尝试将注释类更改为@CustomAnnotation(foo =“123”),所有工作都正常,因为它记录了123.

现在我希望application.propertIEs检索传递给注释的值,所以我已将注释类更改为

@CustomAnnotation(foo = "${my.value}")public class AnnotatedClass {}

但现在日志返回String ${my.vlaue}而不是application.propertIEs中的值.

我知道可以在注释中使用${}指令,因为我总是使用像@GetMapPing这样的@RestController(path =“${path.value:/}”)并且一切正常.

我在Github存储库上的解决方案:https://github.com/federicogatti/annotatedexample最佳答案您不能直接执行某些 *** 作,因为注释属性的值必须是常量表达式.

您可以做的是,您可以将foo值作为字符串传递给@CustomAnnotation(foo =“my.value”)并创建建议AOP以获取注释字符串值并在应用程序属性中查找.

使用@pointcut创建AOP,@ AfterReturn或提供其他匹配@annotation,方法等,并将您的逻辑写入查找属性以获取相应的字符串.

>在主应用程序上配置@EnableAspectJAutoproxy或按配置类进行设置.
>添加aop依赖项:spring-boot-starter-aop
>使用切入点创建@Aspect.

@Aspectpublic class CustomAnnotationAOP {@pointcut("@annotation(it.federicogatti.annotationexample.annotationexample.annotation.CustomAnnotation)") //define your method with logic to lookup application.propertIEs

在官方指南中查看更多内容:Aspect Oriented Programming with Spring 总结

以上是内存溢出为你收集整理的java – Interface Annotation不接受application.properties值全部内容,希望文章能够帮你解决java – Interface Annotation不接受application.properties值所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1248504.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存