java 注释属性的值必须是常量表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7926596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
value for the annotation attribute must be constant expression
提问by ysnky
I have a properties file that I read by spring annotation like this
我有一个属性文件,我通过这样的 spring 注释读取
@Value("${platform}")
private String platform;
after I get the platform parameter, I would like to read a second parameter depending on platform
parameter value.
获得平台参数后,我想根据platform
参数值读取第二个参数。
@Value("${url." + platform + ."ws}")
private String url;
but this gives error, "value for the annotation attribute must be constant expression". since there are lots of parameter changes depending on "platform" value, I am looking for a generic solution.
但这会产生错误,“注释属性的值必须是常量表达式”。由于根据“平台”值有很多参数更改,因此我正在寻找通用解决方案。
回答by ssedano
The parameter is evaluated in compilation time. So it needs to be final
or static final
among others (ie Enum
).
该参数在编译时进行评估。所以它需要是final
或static final
其中之一(即Enum
)。
I don't know if the @Value
annotation allows that. But you can always implement your own annotation. Extending is not possible in Java annotations.
我不知道@Value
注释是否允许。但是您始终可以实现自己的注释。在 Java 注释中无法扩展。
回答by LucasP
You can't access platform
directly in the @Value expression, but you can use Spring Expression Language to accomplish your end goal.
您不能platform
直接在 @Value 表达式中访问,但您可以使用 Spring 表达式语言来实现您的最终目标。
@Value("${platform}")
private String platform;
@Value("#{'Url.'.concat(${platform}).concat('.ws')}")
private String url;