加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – Interface Annotation不接受application.properties值

发布时间:2020-12-15 01:27:13 所属栏目:大数据 来源:网络整理
导读:我开发了一个简单的注释界面 @Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface CustomAnnotation { String foo() default "foo";} 然后我测试它注释一个类 @CustomAnnotationpublic class AnnotatedClass {} 并使用方法调用

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

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

然后我测试它注释一个类

@CustomAnnotation
public 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.

@Aspect
public class CustomAnnotationAOP {


@Pointcut("@annotation(it.federicogatti.annotationexample.annotationexample.annotation.CustomAnnotation)")
 //define your method with logic to lookup application.properties

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读