Interface Annotation不接受application.properties值

Fed*_*tti 6 java spring annotations spring-boot property-placeholder

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

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

然后我测试它注释一个类

@CustomAnnotation
public class AnnotatedClass {
}
Run Code Online (Sandbox Code Playgroud)

并使用方法调用它

public void foo()  {
    CustomAnnotation customAnnotation = AnnotatedClass.class.getAnnotation(CustomAnnotation.class);
    logger.info(customAnnotation.foo());
}
Run Code Online (Sandbox Code Playgroud)

并且一切正常,因为它记录了foo.我也尝试将注释类更改为@CustomAnnotation(foo = "123")并且一切正常,因为它记录了123.

现在我希望传递给注释的值由the检索application.properties,因此我将注释类更改为

@CustomAnnotation(foo = "${my.value}")
public class AnnotatedClass {
}
Run Code Online (Sandbox Code Playgroud)

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

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


我在Github存储库上的解决方案:https://github.com/federicogatti/annotatedexample

kj0*_*007 2

你不能直接做类似的事情annotation attribute's value must be a constant expression.

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

@Pointcut使用、@AfterReturn或提供其他方法来匹配、 方法等创建 AOP @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
    
    Run Code Online (Sandbox Code Playgroud)

更多内容请参阅官方指南:使用 Spring 进行面向方面编程