インタフェース注釈はapplication.properties値を受け入れません

フェデリコ・ガッティ:

私は、単純な開発した注釈インターフェイス

@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")し、それがログに記録becuaseすべてが、あまりにも正常に動作123を

今私は、注釈に渡された値がで取得されることを望むapplication.properties私は私の注釈付きクラスを変更しているので、

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

しかし、今のログは文字列を返し${my.vlaue}ずに値をapplication.properties

私はそれが可能な用途の知っている${}私はいつも使用しているため、注釈内の命令@RestControllerのように@GetMapping(path = "${path.value:/}")、すべてが正常に動作します。


Githubのリポジトリに私の解決策:https://github.com/federicogatti/annotatedexample

kj007:

あなたはとして直接のような何かを行うことはできません annotation attribute's value must be a constant expression.

あなたにできることはあなたのような文字列としてFOO値を渡すことができ、ある@CustomAnnotation(foo = "my.value")と注釈文字列値を取得し、アプリケーションのプロパティで検索するアドバイスAOPを作成します。

AOPを作成する@Pointcut@AfterReturnまたは一致させるために他人を提供し@annotation、メソッドなど、文字列を対応するためのルックアッププロパティに、あなたのロジックを記述します。

  1. 設定し@EnableAspectJAutoProxy、メインアプリケーションまたは構成クラスによって設定に関する。

  2. AOPの依存関係を追加します。 spring-boot-starter-aop

  3. 作成@Aspectポイントカットで。

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

より公式ガイドで見て:春とアスペクト指向プログラミング

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=176548&siteId=1