私は、単純な開発した注釈インターフェイス
@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
あなたはとして直接のような何かを行うことはできません annotation attribute's value must be a constant expression.
あなたにできることはあなたのような文字列としてFOO値を渡すことができ、ある@CustomAnnotation(foo = "my.value")
と注釈文字列値を取得し、アプリケーションのプロパティで検索するアドバイスAOPを作成します。
AOPを作成する@Pointcut
、@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
より公式ガイドで見て:春とアスペクト指向プログラミング