java – Interface Annotation不接受application.properties值

前端之家收集整理的这篇文章主要介绍了java – Interface Annotation不接受application.properties值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

然后我测试它注释一个类

  1. @CustomAnnotation
  2. public class AnnotatedClass {
  3. }

并使用方法调用

  1. public void foo() {
  2. CustomAnnotation customAnnotation = AnnotatedClass.class.getAnnotation(CustomAnnotation.class);
  3. logger.info(customAnnotation.foo());
  4. }

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

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

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

但现在日志返回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.

  1. @Aspect
  2. public class CustomAnnotationAOP {
  3. @Pointcut("@annotation(it.federicogatti.annotationexample.annotationexample.annotation.CustomAnnotation)")
  4. //define your method with logic to lookup application.properties

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

猜你在找的Spring相关文章