java - How to supply value to an annotation dynamically?
问题描述
I have created a cutom annotation with a boolean
value attribute.
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
boolean value() default false;
}
The annotation should be set dynamically based on property read from a configuration file.
I've tried to inject the value directly from the configuration:
@CustomAnnotation("${xxxxx.xxxxx.enableFeature:false}")
public void apply(){}
And:
@CustomAnnotation(""#{new Boolean('${xxxxx.xxxxx.enableFeature:false}")
public void apply(){}
I'm getting the same compilation problem for both solutions:
Type mismatch: cannot convert from String to boolean
I've tried a third solution by injecting the value as variable and then using it:
@Component
public class ApplyClass {
@Value("${xxxxx.xxxxx.enableFeature:false}")
private boolean enableFeature;
@CustomAnnotation(enableFeature)
public void apply(){}
}
I've got another compilation issue:
The value for annotation attribute must be a constant expression
Even by switching the variable to constant, this is not working.
@Component
public class ApplyClass {
@Value("${xxxxx.xxxxx.enableFeature:false}")
private static final boolean enableFeature; // ---> Leads to compilation problem
@CustomAnnotation(enableFeature")
public void apply(){}
}
So, a part from doing code smells like:
@Component
public class ApplyClass {
@Value("${xxxxx.xxxxx.enableFeature:false}")
private boolean enableFeature;
private static final ENABLE_FEATURE_CONSTANT = enableFeature
@CustomAnnotation(ENABLE_FEATURE_CONSTANT)
public void apply(){}
}
- Is that a known limitation of
annotations
? - Is there any recommendation or solution a part from using
Strings
instead of other types ?
解决方案
推荐阅读
- javascript - 基于相同的随机排序系统对两个数组进行排序
- html - 从网站上刮桌子
- vue.js - vuejs中来自db的图像url变量
- c - 为什么这个函数的时间复杂度不是 O(m!)?
- c++ - 深度缓冲区未填充阴影贴图渲染通道中的数据
- linux - Linux 基础 - 如何退出正在运行的命令
- c# - C#中锯齿状数组的列(排列)的成对组合
- apache-spark - 尝试在 drools 中使用 KieRuntimeLogger 生成日志
- java - Spring Caching:在运行时通过 application.properties 启用/禁用缓存
- c# - 如何为 Azure App Service 中的 ASP.NET WebForms Web 应用程序中托管的 ASP.NET MVC Web 应用程序配置路由?