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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:03:03  来源:igfitidea点击:

value for the annotation attribute must be constant expression

javaspringannotations

提问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 platformparameter 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 finalor static finalamong others (ie Enum).

该参数在编译时进行评估。所以它需要是finalstatic final其中之一(即Enum)。

I don't know if the @Valueannotation 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 platformdirectly 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;